g1t/apps/api/src/index.ts

168 lines6,299 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

API and MCP server, Rust identity service, registration, site redesign1import { Hono } from "hono";
2
Rust repos service with shipping; pull requests kept in the model3import {
4 type ServiceBinding,
5 type Viewer,
6 httpStatus,
7 identityClient,
8 reposClient,
9} from "@g1t/contracts";
API and MCP server, Rust identity service, registration, site redesign10
11import { handleMcp } from "./mcp";
12import { type ApiEnv, operations, operationsByName } from "./operations";
13
14type Input = Record<string, unknown>;
Rust repos service with shipping; pull requests kept in the model15/** The Worker's raw bindings; Rust services are reached through clients. */
16type Bindings = Omit<ApiEnv, "IDENTITY" | "REPOS"> & {
17 IDENTITY: ServiceBinding;
18 REPOS: ServiceBinding;
19};
20type App = { Bindings: Bindings; Variables: { viewer: Viewer; services: ApiEnv } };
API and MCP server, Rust identity service, registration, site redesign21
22/**
23 * REST routes. Each maps an HTTP request onto one operation; `input` builds
24 * the operation's input from the path, query string and JSON body.
25 */
26const ROUTES: {
27 method: "GET" | "POST";
28 path: string;
29 operation: string;
30 input?: (params: Record<string, string>, query: Input, body: Input) => Input;
31}[] = [
32 { method: "GET", path: "/v1/user", operation: "whoami" },
33 { method: "GET", path: "/v1/repos", operation: "list_repos", input: (_p, q) => ({ query: q.q }) },
34 { method: "POST", path: "/v1/repos", operation: "create_repo", input: (_p, _q, b) => b },
35 { method: "GET", path: "/v1/repos/:owner/:name", operation: "get_repo", input: repo },
36 { method: "GET", path: "/v1/repos/:owner/:name/intents", operation: "list_intents", input: (p, q) => ({ ...repo(p), status: q.status }) },
37 { method: "POST", path: "/v1/repos/:owner/:name/intents", operation: "open_intent", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
38 { method: "GET", path: "/v1/repos/:owner/:name/intents/:number", operation: "get_intent", input: (p) => ({ ...repo(p), number: Number(p.number) }) },
39 { method: "GET", path: "/v1/repos/:owner/:name/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
40 { method: "POST", path: "/v1/intents/:intent_id/attempts", operation: "start_attempt", input: (p, _q, b) => ({ ...b, intent_id: p.intent_id }) },
41 { method: "GET", path: "/v1/attempts/:attempt_id", operation: "get_attempt", input: (p) => p },
42 { method: "GET", path: "/v1/attempts/:attempt_id/session", operation: "read_session", input: (p, q) => ({ ...p, after: Number(q.after) || 0 }) },
43 { method: "POST", path: "/v1/attempts/:attempt_id/session", operation: "record_session", input: (p, _q, b) => ({ ...b, ...p }) },
44 { method: "POST", path: "/v1/attempts/:attempt_id/submit", operation: "submit_attempt", input: (p, _q, b) => ({ ...b, ...p }) },
45 { method: "POST", path: "/v1/attempts/:attempt_id/abandon", operation: "abandon_attempt", input: (p) => p },
Rust repos service with shipping; pull requests kept in the model46 { method: "POST", path: "/v1/attempts/:attempt_id/ship", operation: "ship_attempt", input: (p) => p },
API and MCP server, Rust identity service, registration, site redesign47];
48
49function repo(params: Record<string, string>): Input {
50 return { repo: `${params.owner}/${params.name}` };
51}
52
53const app = new Hono<App>();
54
55// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
56// wrong one is rejected so a typo does not silently look signed out.
57app.use(async (c, next) => {
58 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
Rust repos service with shipping; pull requests kept in the model59 const services: ApiEnv = {
60 ...c.env,
61 IDENTITY: identityClient(c.env.IDENTITY),
62 REPOS: reposClient(c.env.REPOS),
63 };
64 c.set("services", services);
API and MCP server, Rust identity service, registration, site redesign65 let viewer: Viewer = null;
66 if (scheme?.toLowerCase() === "bearer" && token) {
Rust repos service with shipping; pull requests kept in the model67 viewer = await services.IDENTITY.userForAccessToken(token);
API and MCP server, Rust identity service, registration, site redesign68 if (!viewer) {
69 return c.json(
70 { error: { code: "unauthenticated", message: "Invalid access token." } },
71 401,
72 );
73 }
74 }
75 c.set("viewer", viewer);
76 await next();
77});
78
79app.all("*", async (c, next) => {
80 if (new URL(c.req.url).hostname.startsWith("mcp.")) {
Rust repos service with shipping; pull requests kept in the model81 return handleMcp(c.req.raw, c.get("services"), c.get("viewer"));
API and MCP server, Rust identity service, registration, site redesign82 }
83 await next();
84});
85
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)86// Onboarding. These two are REST only: they take a password, which has no
87// place in an agent's tool call.
88
89async function jsonBody(request: Request): Promise<Record<string, unknown>> {
90 try {
91 return await request.json();
92 } catch {
93 return {};
94 }
95}
96
97app.post("/v1/register", async (c) => {
98 const body = await jsonBody(c.req.raw);
99 const result = await c.get("services").IDENTITY.register(
100 String(body.username ?? ""),
101 String(body.email ?? ""),
102 String(body.password ?? ""),
103 );
104 if (!result.ok) {
105 return c.json({ error: result.error }, httpStatus(result.error) as 409 | 422);
106 }
107 return c.json(
108 {
109 user: result.value.user,
110 next: "A confirmation link was sent to that email address. The account cannot create or push anything until the link is opened.",
111 },
112 201,
113 );
114});
115
116app.post("/v1/tokens", async (c) => {
117 const body = await jsonBody(c.req.raw);
118 const identity = c.get("services").IDENTITY;
119 const password = String(body.password ?? "");
120 // An existing token must not be usable to mint more tokens.
121 const user = password.startsWith("g1t_")
122 ? null
123 : await identity.userForGitCredentials(String(body.username ?? ""), password);
124 if (!user) {
125 return c.json(
126 { error: { code: "unauthenticated", message: "Incorrect username or password." } },
127 401,
128 );
129 }
130 const created = await identity.createAccessToken(user, String(body.name ?? ""));
131 return c.json({ token: created.token, verified: user.verified === true }, 201);
132});
133
API and MCP server, Rust identity service, registration, site redesign134app.get("/", (c) =>
135 c.json({
136 name: "g1t API",
137 version: "v1",
138 documentation: "https://g1t.sh/syntaqx/g1t",
139 operations: operations.map(({ name, description }) => ({ name, description })),
140 }),
141);
142
143for (const route of ROUTES) {
144 const operation = operationsByName.get(route.operation)!;
145 app.on(route.method, route.path, async (c) => {
146 let body: Input = {};
147 if (route.method === "POST") {
148 try {
149 body = await c.req.json();
150 } catch {
151 // An empty or non-JSON body is treated as no input.
152 }
153 }
154 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
Rust repos service with shipping; pull requests kept in the model155 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
API and MCP server, Rust identity service, registration, site redesign156 if (outcome.ok) return c.json(outcome.value);
157 return c.json(
158 { error: outcome.error },
159 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
160 );
161 });
162}
163
164app.notFound((c) =>
165 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
166);
167
168export default app;