Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

copilot.ts

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

copilot.tsBlame75 lines · 1 contributor
3cbe3d6Claude1/**
2 * Block D9 — Copilot-style completion HTTP surface.
3 *
4 * POST /api/copilot/completions (authed — PAT / OAuth / session)
5 * Body: { prefix, suffix?, language?, repo? }
6 * Returns: { completion, model, cached }
7 *
8 * GET /api/copilot/ping (unauthed)
9 * Returns: { ok: true, aiAvailable: boolean }
10 *
11 * Keep per-user limits tight: IDE plugins call this on every keystroke, so a
12 * misbehaving client can otherwise exhaust the shared Anthropic quota fast.
13 */
14
15import { Hono } from "hono";
16import { requireAuth } from "../middleware/auth";
17import type { AuthEnv } from "../middleware/auth";
18import { rateLimit } from "../middleware/rate-limit";
19import { completeCode } from "../lib/ai-completion";
20import { isAiAvailable } from "../lib/ai-client";
21
22const copilot = new Hono<AuthEnv>();
23
24// Tight per-caller limit: 60/min. NOTE: `rateLimit` keys by bearer-token
25// prefix when Authorization is present, otherwise by IP — so session-cookie
26// callers share a single IP bucket. That's acceptable for an IDE endpoint
27// where the expected caller is almost always a PAT/OAuth token.
28const completionLimit = rateLimit({
29 windowMs: 60_000,
30 max: 60,
31 prefix: "copilot",
32});
33
34copilot.get("/api/copilot/ping", (c) => {
35 return c.json({ ok: true, aiAvailable: isAiAvailable() });
36});
37
38copilot.post(
39 "/api/copilot/completions",
40 completionLimit,
41 requireAuth,
42 async (c) => {
43 let body: any;
44 try {
45 body = await c.req.json();
46 } catch {
47 return c.json({ error: "invalid JSON body" }, 400);
48 }
49 if (!body || typeof body !== "object") {
50 return c.json({ error: "body must be a JSON object" }, 400);
51 }
52
53 const { prefix, suffix, language, repo } = body as {
54 prefix?: unknown;
55 suffix?: unknown;
56 language?: unknown;
57 repo?: unknown;
58 };
59
60 if (typeof prefix !== "string" || prefix.length === 0) {
61 return c.json({ error: "prefix (non-empty string) is required" }, 400);
62 }
63
64 const result = await completeCode({
65 prefix,
66 suffix: typeof suffix === "string" ? suffix : undefined,
67 language: typeof language === "string" ? language : undefined,
68 repoHint: typeof repo === "string" ? repo : undefined,
69 });
70
71 return c.json(result);
72 }
73);
74
75export default copilot;