g1t/apps/api/src/index.ts

194 lines7,251 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,
Work service in Rust, with RFC 3339 timestamps10 workClient,
Rust repos service with shipping; pull requests kept in the model11} from "@g1t/contracts";
API and MCP server, Rust identity service, registration, site redesign12
13import { handleMcp } from "./mcp";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer14import { openApiDocument } from "./openapi";
API and MCP server, Rust identity service, registration, site redesign15import { type ApiEnv, operations, operationsByName } from "./operations";
16
17type Input = Record<string, unknown>;
Rust repos service with shipping; pull requests kept in the model18/** The Worker's raw bindings; Rust services are reached through clients. */
Work service in Rust, with RFC 3339 timestamps19type Bindings = Omit<ApiEnv, "IDENTITY" | "REPOS" | "WORK"> & {
Rust repos service with shipping; pull requests kept in the model20 IDENTITY: ServiceBinding;
21 REPOS: ServiceBinding;
Work service in Rust, with RFC 3339 timestamps22 WORK: ServiceBinding;
Rust repos service with shipping; pull requests kept in the model23};
24type App = { Bindings: Bindings; Variables: { viewer: Viewer; services: ApiEnv } };
API and MCP server, Rust identity service, registration, site redesign25
26/**
27 * REST routes. Each maps an HTTP request onto one operation; `input` builds
28 * the operation's input from the path, query string and JSON body.
29 */
30const ROUTES: {
31 method: "GET" | "POST";
32 path: string;
33 operation: string;
34 input?: (params: Record<string, string>, query: Input, body: Input) => Input;
35}[] = [
36 { method: "GET", path: "/v1/user", operation: "whoami" },
Workspaces own repositories37 { method: "POST", path: "/v1/workspaces", operation: "create_workspace", input: (_p, _q, b) => b },
API and MCP server, Rust identity service, registration, site redesign38 { method: "GET", path: "/v1/repos", operation: "list_repos", input: (_p, q) => ({ query: q.q }) },
39 { method: "POST", path: "/v1/repos", operation: "create_repo", input: (_p, _q, b) => b },
40 { method: "GET", path: "/v1/repos/:owner/:name", operation: "get_repo", input: repo },
41 { method: "GET", path: "/v1/repos/:owner/:name/intents", operation: "list_intents", input: (p, q) => ({ ...repo(p), status: q.status }) },
42 { method: "POST", path: "/v1/repos/:owner/:name/intents", operation: "open_intent", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
43 { method: "GET", path: "/v1/repos/:owner/:name/intents/:number", operation: "get_intent", input: (p) => ({ ...repo(p), number: Number(p.number) }) },
44 { method: "GET", path: "/v1/repos/:owner/:name/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
45 { method: "POST", path: "/v1/intents/:intent_id/attempts", operation: "start_attempt", input: (p, _q, b) => ({ ...b, intent_id: p.intent_id }) },
46 { method: "GET", path: "/v1/attempts/:attempt_id", operation: "get_attempt", input: (p) => p },
47 { method: "GET", path: "/v1/attempts/:attempt_id/session", operation: "read_session", input: (p, q) => ({ ...p, after: Number(q.after) || 0 }) },
48 { method: "POST", path: "/v1/attempts/:attempt_id/session", operation: "record_session", input: (p, _q, b) => ({ ...b, ...p }) },
49 { method: "POST", path: "/v1/attempts/:attempt_id/submit", operation: "submit_attempt", input: (p, _q, b) => ({ ...b, ...p }) },
50 { method: "POST", path: "/v1/attempts/:attempt_id/abandon", operation: "abandon_attempt", input: (p) => p },
Rust repos service with shipping; pull requests kept in the model51 { method: "POST", path: "/v1/attempts/:attempt_id/ship", operation: "ship_attempt", input: (p) => p },
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer52 { method: "GET", path: "/v1/attempts/:attempt_id/changes", operation: "get_attempt_changes", input: (p) => p },
API and MCP server, Rust identity service, registration, site redesign53];
54
55function repo(params: Record<string, string>): Input {
56 return { repo: `${params.owner}/${params.name}` };
57}
58
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer59/** The section of the API reference an operation is listed under. */
60function tagFor(operation: string): string {
Workspaces own repositories61 if (operation === "whoami" || operation.includes("workspace")) return "Accounts";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer62 if (operation.includes("session")) return "Sessions";
63 if (operation.includes("attempt")) return "Attempts";
64 if (operation.includes("intent")) return "Intents";
65 return "Repositories";
66}
67
API and MCP server, Rust identity service, registration, site redesign68const app = new Hono<App>();
69
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer70// The API is called from browsers too: the reference's explorer, and apps
71// built on g1t. It carries no cookies, so any origin may call it.
72app.use(cors({ origin: "*", allowHeaders: ["authorization", "content-type"] }));
73
API and MCP server, Rust identity service, registration, site redesign74// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
75// wrong one is rejected so a typo does not silently look signed out.
76app.use(async (c, next) => {
77 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
Rust repos service with shipping; pull requests kept in the model78 const services: ApiEnv = {
79 ...c.env,
80 IDENTITY: identityClient(c.env.IDENTITY),
81 REPOS: reposClient(c.env.REPOS),
Work service in Rust, with RFC 3339 timestamps82 WORK: workClient(c.env.WORK),
Rust repos service with shipping; pull requests kept in the model83 };
84 c.set("services", services);
API and MCP server, Rust identity service, registration, site redesign85 let viewer: Viewer = null;
86 if (scheme?.toLowerCase() === "bearer" && token) {
Rust repos service with shipping; pull requests kept in the model87 viewer = await services.IDENTITY.userForAccessToken(token);
API and MCP server, Rust identity service, registration, site redesign88 if (!viewer) {
89 return c.json(
90 { error: { code: "unauthenticated", message: "Invalid access token." } },
91 401,
92 );
93 }
94 }
95 c.set("viewer", viewer);
96 await next();
97});
98
99app.all("*", async (c, next) => {
100 if (new URL(c.req.url).hostname.startsWith("mcp.")) {
Rust repos service with shipping; pull requests kept in the model101 return handleMcp(c.req.raw, c.get("services"), c.get("viewer"));
API and MCP server, Rust identity service, registration, site redesign102 }
103 await next();
104});
105
Device sign-in replaces registering and minting tokens over the API106// Signing in from a tool. Accounts are created, and passwords typed, only
107// in a browser; a tool gets its token by having a person approve a code.
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)108
109async function jsonBody(request: Request): Promise<Record<string, unknown>> {
110 try {
111 return await request.json();
112 } catch {
113 return {};
114 }
115}
116
Device sign-in replaces registering and minting tokens over the API117app.post("/v1/device/code", async (c) => {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)118 const body = await jsonBody(c.req.raw);
Device sign-in replaces registering and minting tokens over the API119 const started = await c
120 .get("services")
121 .IDENTITY.deviceStart(String(body.client_name ?? ""));
122 return c.json({
123 device_code: started.deviceCode,
124 user_code: started.userCode,
125 verification_uri: "https://g1t.sh/device",
126 verification_uri_complete: `https://g1t.sh/device?code=${started.userCode}`,
127 expires_in: started.expiresIn,
128 interval: started.interval,
129 });
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)130});
131
Device sign-in replaces registering and minting tokens over the API132app.post("/v1/device/token", async (c) => {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)133 const body = await jsonBody(c.req.raw);
Device sign-in replaces registering and minting tokens over the API134 const claim = await c
135 .get("services")
136 .IDENTITY.deviceClaim(String(body.device_code ?? ""));
137 if (claim.status !== "approved") return c.json({ status: claim.status });
138 return c.json({
139 status: "approved",
140 token: claim.token,
141 username: claim.user.username,
142 verified: claim.user.verified === true,
143 });
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)144});
145
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer146app.get("/openapi.json", (c) =>
147 c.json(
148 openApiDocument(
149 ROUTES.map(({ method, path, operation }) => ({
150 method,
151 path,
152 operation,
153 tag: tagFor(operation),
154 })),
155 ),
156 ),
157);
158
API and MCP server, Rust identity service, registration, site redesign159app.get("/", (c) =>
160 c.json({
161 name: "g1t API",
162 version: "v1",
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer163 documentation: "https://docs.g1t.sh/api",
164 openapi: "https://api.g1t.sh/openapi.json",
API and MCP server, Rust identity service, registration, site redesign165 operations: operations.map(({ name, description }) => ({ name, description })),
166 }),
167);
168
169for (const route of ROUTES) {
170 const operation = operationsByName.get(route.operation)!;
171 app.on(route.method, route.path, async (c) => {
172 let body: Input = {};
173 if (route.method === "POST") {
174 try {
175 body = await c.req.json();
176 } catch {
177 // An empty or non-JSON body is treated as no input.
178 }
179 }
180 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
Rust repos service with shipping; pull requests kept in the model181 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
API and MCP server, Rust identity service, registration, site redesign182 if (outcome.ok) return c.json(outcome.value);
183 return c.json(
184 { error: outcome.error },
185 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
186 );
187 });
188}
189
190app.notFound((c) =>
191 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
192);
193
194export default app;