pr_01m47d15m3e54sn21z27rpy5n9/apps/api/src/index.ts

198 lines7,343 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";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer2import { cors } from "hono/cors";
API and MCP server, Rust identity service, registration, site redesign3
Rust repos service with shipping; pull requests kept in the model4import {
5 type ServiceBinding,
6 type Viewer,
7 httpStatus,
8 identityClient,
9 reposClient,
10} from "@g1t/contracts";
API and MCP server, Rust identity service, registration, site redesign11
12import { handleMcp } from "./mcp";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer13import { openApiDocument } from "./openapi";
API and MCP server, Rust identity service, registration, site redesign14import { type ApiEnv, operations, operationsByName } from "./operations";
15
16type Input = Record<string, unknown>;
Rust repos service with shipping; pull requests kept in the model17/** The Worker's raw bindings; Rust services are reached through clients. */
18type Bindings = Omit<ApiEnv, "IDENTITY" | "REPOS"> & {
19 IDENTITY: ServiceBinding;
20 REPOS: ServiceBinding;
21};
22type App = { Bindings: Bindings; Variables: { viewer: Viewer; services: ApiEnv } };
API and MCP server, Rust identity service, registration, site redesign23
24/**
25 * REST routes. Each maps an HTTP request onto one operation; `input` builds
26 * the operation's input from the path, query string and JSON body.
27 */
28const ROUTES: {
29 method: "GET" | "POST";
30 path: string;
31 operation: string;
32 input?: (params: Record<string, string>, query: Input, body: Input) => Input;
33}[] = [
34 { method: "GET", path: "/v1/user", operation: "whoami" },
35 { method: "GET", path: "/v1/repos", operation: "list_repos", input: (_p, q) => ({ query: q.q }) },
36 { method: "POST", path: "/v1/repos", operation: "create_repo", input: (_p, _q, b) => b },
37 { method: "GET", path: "/v1/repos/:owner/:name", operation: "get_repo", input: repo },
38 { method: "GET", path: "/v1/repos/:owner/:name/intents", operation: "list_intents", input: (p, q) => ({ ...repo(p), status: q.status }) },
39 { method: "POST", path: "/v1/repos/:owner/:name/intents", operation: "open_intent", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
40 { method: "GET", path: "/v1/repos/:owner/:name/intents/:number", operation: "get_intent", input: (p) => ({ ...repo(p), number: Number(p.number) }) },
41 { method: "GET", path: "/v1/repos/:owner/:name/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
42 { method: "POST", path: "/v1/intents/:intent_id/attempts", operation: "start_attempt", input: (p, _q, b) => ({ ...b, intent_id: p.intent_id }) },
43 { method: "GET", path: "/v1/attempts/:attempt_id", operation: "get_attempt", input: (p) => p },
44 { method: "GET", path: "/v1/attempts/:attempt_id/session", operation: "read_session", input: (p, q) => ({ ...p, after: Number(q.after) || 0 }) },
45 { method: "POST", path: "/v1/attempts/:attempt_id/session", operation: "record_session", input: (p, _q, b) => ({ ...b, ...p }) },
46 { method: "POST", path: "/v1/attempts/:attempt_id/submit", operation: "submit_attempt", input: (p, _q, b) => ({ ...b, ...p }) },
47 { method: "POST", path: "/v1/attempts/:attempt_id/abandon", operation: "abandon_attempt", input: (p) => p },
Rust repos service with shipping; pull requests kept in the model48 { method: "POST", path: "/v1/attempts/:attempt_id/ship", operation: "ship_attempt", input: (p) => p },
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer49 { method: "GET", path: "/v1/attempts/:attempt_id/changes", operation: "get_attempt_changes", input: (p) => p },
API and MCP server, Rust identity service, registration, site redesign50];
51
52function repo(params: Record<string, string>): Input {
53 return { repo: `${params.owner}/${params.name}` };
54}
55
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer56/** The section of the API reference an operation is listed under. */
57function tagFor(operation: string): string {
58 if (operation === "whoami") return "Accounts";
59 if (operation.includes("session")) return "Sessions";
60 if (operation.includes("attempt")) return "Attempts";
61 if (operation.includes("intent")) return "Intents";
62 return "Repositories";
63}
64
API and MCP server, Rust identity service, registration, site redesign65const app = new Hono<App>();
66
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer67// The API is called from browsers too: the reference's explorer, and apps
68// built on g1t. It carries no cookies, so any origin may call it.
69app.use(cors({ origin: "*", allowHeaders: ["authorization", "content-type"] }));
70
API and MCP server, Rust identity service, registration, site redesign71// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
72// wrong one is rejected so a typo does not silently look signed out.
73app.use(async (c, next) => {
74 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
Rust repos service with shipping; pull requests kept in the model75 const services: ApiEnv = {
76 ...c.env,
77 IDENTITY: identityClient(c.env.IDENTITY),
78 REPOS: reposClient(c.env.REPOS),
79 };
80 c.set("services", services);
API and MCP server, Rust identity service, registration, site redesign81 let viewer: Viewer = null;
82 if (scheme?.toLowerCase() === "bearer" && token) {
Rust repos service with shipping; pull requests kept in the model83 viewer = await services.IDENTITY.userForAccessToken(token);
API and MCP server, Rust identity service, registration, site redesign84 if (!viewer) {
85 return c.json(
86 { error: { code: "unauthenticated", message: "Invalid access token." } },
87 401,
88 );
89 }
90 }
91 c.set("viewer", viewer);
92 await next();
93});
94
95app.all("*", async (c, next) => {
96 if (new URL(c.req.url).hostname.startsWith("mcp.")) {
Rust repos service with shipping; pull requests kept in the model97 return handleMcp(c.req.raw, c.get("services"), c.get("viewer"));
API and MCP server, Rust identity service, registration, site redesign98 }
99 await next();
100});
101
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)102// Onboarding. These two are REST only: they take a password, which has no
103// place in an agent's tool call.
104
105async function jsonBody(request: Request): Promise<Record<string, unknown>> {
106 try {
107 return await request.json();
108 } catch {
109 return {};
110 }
111}
112
113app.post("/v1/register", async (c) => {
114 const body = await jsonBody(c.req.raw);
115 const result = await c.get("services").IDENTITY.register(
116 String(body.username ?? ""),
117 String(body.email ?? ""),
118 String(body.password ?? ""),
119 );
120 if (!result.ok) {
121 return c.json({ error: result.error }, httpStatus(result.error) as 409 | 422);
122 }
123 return c.json(
124 {
125 user: result.value.user,
126 next: "A confirmation link was sent to that email address. The account cannot create or push anything until the link is opened.",
127 },
128 201,
129 );
130});
131
132app.post("/v1/tokens", async (c) => {
133 const body = await jsonBody(c.req.raw);
134 const identity = c.get("services").IDENTITY;
135 const password = String(body.password ?? "");
136 // An existing token must not be usable to mint more tokens.
137 const user = password.startsWith("g1t_")
138 ? null
139 : await identity.userForGitCredentials(String(body.username ?? ""), password);
140 if (!user) {
141 return c.json(
142 { error: { code: "unauthenticated", message: "Incorrect username or password." } },
143 401,
144 );
145 }
146 const created = await identity.createAccessToken(user, String(body.name ?? ""));
147 return c.json({ token: created.token, verified: user.verified === true }, 201);
148});
149
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer150app.get("/openapi.json", (c) =>
151 c.json(
152 openApiDocument(
153 ROUTES.map(({ method, path, operation }) => ({
154 method,
155 path,
156 operation,
157 tag: tagFor(operation),
158 })),
159 ),
160 ),
161);
162
API and MCP server, Rust identity service, registration, site redesign163app.get("/", (c) =>
164 c.json({
165 name: "g1t API",
166 version: "v1",
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer167 documentation: "https://docs.g1t.sh/api",
168 openapi: "https://api.g1t.sh/openapi.json",
API and MCP server, Rust identity service, registration, site redesign169 operations: operations.map(({ name, description }) => ({ name, description })),
170 }),
171);
172
173for (const route of ROUTES) {
174 const operation = operationsByName.get(route.operation)!;
175 app.on(route.method, route.path, async (c) => {
176 let body: Input = {};
177 if (route.method === "POST") {
178 try {
179 body = await c.req.json();
180 } catch {
181 // An empty or non-JSON body is treated as no input.
182 }
183 }
184 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
Rust repos service with shipping; pull requests kept in the model185 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
API and MCP server, Rust identity service, registration, site redesign186 if (outcome.ok) return c.json(outcome.value);
187 return c.json(
188 { error: outcome.error },
189 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
190 );
191 });
192}
193
194app.notFound((c) =>
195 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
196);
197
198export default app;