g1t/apps/api/src/index.ts

209 lines8,340 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: {
Issues and pull requests replace intents and attempts31 method: "GET" | "POST" | "PATCH";
API and MCP server, Rust identity service, registration, site redesign32 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/events", operation: "list_events", input: (p, q) => ({ ...repo(p), before: q.before }) },
Issues and pull requests replace intents and attempts42 { method: "GET", path: "/v1/repos/:owner/:name/labels", operation: "list_labels", input: repo },
43 { method: "GET", path: "/v1/repos/:owner/:name/issues", operation: "list_issues", input: (p, q) => ({ ...repo(p), state: q.state, label: q.label }) },
44 { method: "POST", path: "/v1/repos/:owner/:name/issues", operation: "create_issue", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
45 { method: "GET", path: "/v1/repos/:owner/:name/issues/:number", operation: "get_issue", input: numbered },
46 { method: "PATCH", path: "/v1/repos/:owner/:name/issues/:number", operation: "update_issue", input: numbered },
47 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/close", operation: "close_issue", input: numbered },
48 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/reopen", operation: "reopen_issue", input: numbered },
49 { method: "POST", path: "/v1/repos/:owner/:name/issues/:number/comments", operation: "add_comment", input: numbered },
50 { method: "GET", path: "/v1/repos/:owner/:name/pulls", operation: "list_pull_requests", input: (p, q) => ({ ...repo(p), state: q.state }) },
51 { method: "POST", path: "/v1/repos/:owner/:name/pulls", operation: "create_pull_request", input: (p, _q, b) => ({ ...b, ...repo(p) }) },
52 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number", operation: "get_pull_request", input: numbered },
53 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number/changes", operation: "get_pull_request_changes", input: numbered },
54 { method: "GET", path: "/v1/repos/:owner/:name/pulls/:number/session", operation: "read_session", input: (p, q) => ({ ...numbered(p), after: Number(q.after) || 0 }) },
55 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/session", operation: "record_session", input: numbered },
56 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/ready", operation: "mark_pull_request_ready", input: numbered },
57 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/close", operation: "close_pull_request", input: numbered },
58 { method: "POST", path: "/v1/repos/:owner/:name/pulls/:number/merge", operation: "merge_pull_request", input: numbered },
API and MCP server, Rust identity service, registration, site redesign59];
60
61function repo(params: Record<string, string>): Input {
62 return { repo: `${params.owner}/${params.name}` };
63}
64
Issues and pull requests replace intents and attempts65/** An issue or pull request named in the path, with the body's fields. */
66function numbered(params: Record<string, string>, _query: Input = {}, body: Input = {}): Input {
67 return { ...body, ...repo(params), number: Number(params.number) };
68}
69
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer70/** The section of the API reference an operation is listed under. */
71function tagFor(operation: string): string {
Workspaces own repositories72 if (operation === "whoami" || operation.includes("workspace")) return "Accounts";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer73 if (operation.includes("session")) return "Sessions";
Issues and pull requests replace intents and attempts74 if (operation.includes("pull_request")) return "Pull requests";
75 if (/issue|label|comment/.test(operation)) return "Issues";
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer76 return "Repositories";
77}
78
API and MCP server, Rust identity service, registration, site redesign79const app = new Hono<App>();
80
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer81// The API is called from browsers too: the reference's explorer, and apps
82// built on g1t. It carries no cookies, so any origin may call it.
Issues and pull requests replace intents and attempts83app.use(cors({
84 origin: "*",
85 allowHeaders: ["authorization", "content-type"],
86 allowMethods: ["GET", "POST", "PATCH", "OPTIONS"],
87 }));
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer88
API and MCP server, Rust identity service, registration, site redesign89// `Authorization: Bearer g1t_…`. A missing token is an anonymous viewer; a
90// wrong one is rejected so a typo does not silently look signed out.
91app.use(async (c, next) => {
92 const [scheme, token] = (c.req.header("authorization") ?? "").split(" ");
Rust repos service with shipping; pull requests kept in the model93 const services: ApiEnv = {
94 ...c.env,
95 IDENTITY: identityClient(c.env.IDENTITY),
96 REPOS: reposClient(c.env.REPOS),
Work service in Rust, with RFC 3339 timestamps97 WORK: workClient(c.env.WORK),
Rust repos service with shipping; pull requests kept in the model98 };
99 c.set("services", services);
API and MCP server, Rust identity service, registration, site redesign100 let viewer: Viewer = null;
101 if (scheme?.toLowerCase() === "bearer" && token) {
Rust repos service with shipping; pull requests kept in the model102 viewer = await services.IDENTITY.userForAccessToken(token);
API and MCP server, Rust identity service, registration, site redesign103 if (!viewer) {
104 return c.json(
105 { error: { code: "unauthenticated", message: "Invalid access token." } },
106 401,
107 );
108 }
109 }
110 c.set("viewer", viewer);
111 await next();
112});
113
114app.all("*", async (c, next) => {
115 if (new URL(c.req.url).hostname.startsWith("mcp.")) {
Rust repos service with shipping; pull requests kept in the model116 return handleMcp(c.req.raw, c.get("services"), c.get("viewer"));
API and MCP server, Rust identity service, registration, site redesign117 }
118 await next();
119});
120
Device sign-in replaces registering and minting tokens over the API121// Signing in from a tool. Accounts are created, and passwords typed, only
122// 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)123
124async function jsonBody(request: Request): Promise<Record<string, unknown>> {
125 try {
126 return await request.json();
127 } catch {
128 return {};
129 }
130}
131
Device sign-in replaces registering and minting tokens over the API132app.post("/v1/device/code", 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 started = await c
135 .get("services")
136 .IDENTITY.deviceStart(String(body.client_name ?? ""));
137 return c.json({
138 device_code: started.deviceCode,
139 user_code: started.userCode,
140 verification_uri: "https://g1t.sh/device",
141 verification_uri_complete: `https://g1t.sh/device?code=${started.userCode}`,
142 expires_in: started.expiresIn,
143 interval: started.interval,
144 });
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)145});
146
Device sign-in replaces registering and minting tokens over the API147app.post("/v1/device/token", async (c) => {
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)148 const body = await jsonBody(c.req.raw);
Device sign-in replaces registering and minting tokens over the API149 const claim = await c
150 .get("services")
151 .IDENTITY.deviceClaim(String(body.device_code ?? ""));
152 if (claim.status !== "approved") return c.json({ status: claim.status });
153 return c.json({
154 status: "approved",
155 token: claim.token,
156 username: claim.user.username,
157 verified: claim.user.verified === true,
158 });
Account dropdown, llms.txt onboarding, hosted agent runner (not yet deployed)159});
160
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer161app.get("/openapi.json", (c) =>
162 c.json(
163 openApiDocument(
164 ROUTES.map(({ method, path, operation }) => ({
165 method,
166 path,
167 operation,
168 tag: tagFor(operation),
169 })),
170 ),
171 ),
172);
173
API and MCP server, Rust identity service, registration, site redesign174app.get("/", (c) =>
175 c.json({
176 name: "g1t API",
177 version: "v1",
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer178 documentation: "https://docs.g1t.sh/api",
179 openapi: "https://api.g1t.sh/openapi.json",
API and MCP server, Rust identity service, registration, site redesign180 operations: operations.map(({ name, description }) => ({ name, description })),
181 }),
182);
183
184for (const route of ROUTES) {
185 const operation = operationsByName.get(route.operation)!;
186 app.on(route.method, route.path, async (c) => {
187 let body: Input = {};
Issues and pull requests replace intents and attempts188 if (route.method !== "GET") {
API and MCP server, Rust identity service, registration, site redesign189 try {
190 body = await c.req.json();
191 } catch {
192 // An empty or non-JSON body is treated as no input.
193 }
194 }
195 const input = route.input?.(c.req.param(), c.req.query(), body) ?? {};
Rust repos service with shipping; pull requests kept in the model196 const outcome = await operation.run(c.get("services"), c.get("viewer"), input);
API and MCP server, Rust identity service, registration, site redesign197 if (outcome.ok) return c.json(outcome.value);
198 return c.json(
199 { error: outcome.error },
200 httpStatus(outcome.error) as 401 | 403 | 404 | 409 | 422,
201 );
202 });
203}
204
205app.notFound((c) =>
206 c.json({ error: { code: "not_found", message: "No such endpoint." } }, 404),
207);
208
209export default app;