Skip to content

g1t/apps/api/src/lib.rs

835 lines34,956 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 in Rust; a public index at the API root1//! The public API: REST at api.g1t.sh and the MCP server at mcp.g1t.sh.
2//!
3//! One Worker, two hostnames. Both are thin adapters over the same
4//! operations (see [`operations::Op`]), which call the services that own
5//! the data. This Worker holds none.
6
Merge branch 'worktree-agent-aaf03bdceac799c89'7mod addresses;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily8mod alerts;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API9mod audit;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit10mod billing;
A repository has its own sidebar, as settings do11mod blobs;
API and MCP server in Rust; a public index at the API root12mod mcp;
API: notifications over REST and MCP, with notifications scopes13mod notifications;
API and MCP server in Rust; a public index at the API root14mod oauth;
15mod openapi;
API: pinned projects over REST and MCP16mod pins;
API and MCP server in Rust; a public index at the API root17mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains18mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API19#[cfg(test)]
20mod responses;
API and MCP server in Rust; a public index at the API root21mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge22mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents23mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar24mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step25mod tools;
API and MCP server in Rust; a public index at the API root26
Merge branch 'model-routing'27use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root28use g1t_contracts::identity::{
29 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
30};
Agents as a team: lifecycle, merge queue, billing and a new shell31use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains32 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
33 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell34};
35use g1t_contracts::identity::AgentScope;
36use g1t_contracts::{Failure, FailureCode, Outcome, PrincipalKind, Viewer};
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API37use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root38use serde_json::{Value, json};
39use worker::{Context, Env, Method, Request, Response, Result, event};
40
41use operations::Services;
42
43fn method_name(method: Method) -> &'static str {
44 match method {
45 Method::Get => "GET",
46 Method::Post => "POST",
47 Method::Patch => "PATCH",
48 Method::Put => "PUT",
49 Method::Delete => "DELETE",
50 Method::Options => "OPTIONS",
51 Method::Head => "HEAD",
52 _ => "OTHER",
53 }
54}
55
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API56/// A JSON response. Every body the API sends has its keys in `snake_case`;
57/// the contracts it passes through are `camelCase`, so they are converted
58/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
59/// the MCP protocol's own envelope keep the spelling their standards use.
60pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
61 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
62}
63
64/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
65/// workflow file, GitHub's contexts and event, and where to check out, all
66/// passed through as they are.
67const JOB_SPEC_AS_GIVEN: &[&str] = &[
68 "spec", "workflow", "github", "event", "contexts", "checkout",
69];
70
API and MCP server in Rust; a public index at the API root71/// An error in the shape every endpoint uses.
72fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API73 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root74}
75
76fn fail(code: FailureCode, message: &str) -> Result<Response> {
77 failure(&Failure {
78 code,
79 message: message.to_owned(),
80 })
81}
82
83/// A request body as JSON. An empty or malformed body is no input.
84async fn json_body(request: &mut Request) -> Value {
85 request.json().await.unwrap_or(Value::Null)
86}
87
88/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
89/// an anonymous viewer; a wrong one is refused, so that a typo does not
90/// silently look signed out.
91async fn authenticate(
92 request: &Request,
93 services: &Services,
94) -> Result<std::result::Result<Viewer, Response>> {
95 let header = request.headers().get("authorization")?.unwrap_or_default();
96 let token = match header.split_once(' ') {
97 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
98 token.trim()
99 }
100 _ => return Ok(Ok(None)),
101 };
102 let viewer: Viewer = g1t_kit::call(
103 &services.identity,
104 "user_for_access_token",
105 &TokenArgs {
106 token: token.to_owned(),
107 },
108 )
109 .await?;
110 if viewer.is_some() {
111 return Ok(Ok(viewer));
112 }
113 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
114 // Tells an MCP client where to sign in again.
115 response.headers_mut().set(
116 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'117 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root118 )?;
119 Ok(Err(response))
120}
121
122/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'123fn index(addresses: &addresses::Addresses) -> Value {
124 let api = &addresses.api;
125 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root126 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'127 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'128 "openapi_url": format!("{api}/openapi.json"),
129 "mcp_url": addresses.mcp,
130 "current_user_url": format!("{api}/user"),
131 "workspaces_url": format!("{api}/workspaces"),
132 "repositories_url": format!("{api}/repos{{?q}}"),
133 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root134 "repository_url": repo,
135 "repository_events_url": format!("{repo}/events{{?before}}"),
136 "labels_url": format!("{repo}/labels"),
137 "issues_url": format!("{repo}/issues{{?state,label}}"),
138 "issue_url": format!("{repo}/issues/{{number}}"),
139 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
140 "pulls_url": format!("{repo}/pulls{{?state}}"),
141 "pull_url": format!("{repo}/pulls/{{number}}"),
142 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts143 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root144 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'145 "device_code_url": format!("{api}/device/code"),
146 "device_token_url": format!("{api}/device/token"),
147 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
148 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
149 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read150 "context_url": format!("{repo}/context{{?reference}}"),
151 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'152 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root153 })
154}
155
156// Signing in from a tool. Accounts are created, and passwords typed, only
157// in a browser; a tool gets its token by having a person approve a code.
158
Integrations: your own model provider, alerts that open issues, tickets agents read159/// Passes a request from an outside system to its connection, as it came:
160/// its signature covers the exact bytes of the body.
161async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
162 let headers: std::collections::HashMap<String, String> = request
163 .headers()
164 .entries()
165 .map(|(name, value)| (name.to_lowercase(), value))
166 .collect();
167 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look168 // A push to GitHub with many commits makes a large payload.
169 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
170 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API171 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read172 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look173 // g1t's GitHub App has one webhook for every installation; it is
174 // checked against the app's own secret.
175 let (method, args) = if id == "github" {
176 ("github_receive", json!({ "headers": headers, "body": body }))
177 } else {
178 ("receive", json!({ "id": id, "headers": headers, "body": body }))
179 };
180 let received: g1t_contracts::integrations::Received =
181 g1t_kit::call(&services.integrations, method, &args).await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API182 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read183}
184
Stripe webhooks, enterprise invoices, and sudo for both185async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
186 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
187 let payload = request.text().await.unwrap_or_default();
188 if payload.len() > 1_000_000 || signature.is_empty() {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API189 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both190 }
191 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
192 &env.service("BILLING")?,
193 "stripe_webhook",
194 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
195 )
196 .await?;
197 // A refusal is a 400, so Stripe shows it as failed; anything handled,
198 // or already handled, is a 200, so Stripe stops sending it.
199 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API200 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both201 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API202 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both203 }
204 })
205}
206
API and MCP server in Rust; a public index at the API root207async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
208 let body = json_body(request).await;
209 let started: DeviceStart = g1t_kit::call(
210 &services.identity,
211 "device_start",
212 &DeviceStartArgs {
213 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
214 },
215 )
216 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API217 reply(&json!({
API and MCP server in Rust; a public index at the API root218 "device_code": started.device_code,
219 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'220 "verification_uri": format!("{}/device", services.addresses.site),
221 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root222 "expires_in": started.expires_in,
223 "interval": started.interval,
224 }))
225}
226
227async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
228 let body = json_body(request).await;
229 let claim: DeviceClaim = g1t_kit::call(
230 &services.identity,
231 "device_claim",
232 &DeviceClaimArgs {
233 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
234 },
235 )
236 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API237 reply(&match claim {
API and MCP server in Rust; a public index at the API root238 DeviceClaim::Approved { token, user } => json!({
239 "status": "approved",
240 "token": token,
241 "username": user.username,
242 "verified": user.verified,
243 }),
244 DeviceClaim::Pending => json!({ "status": "pending" }),
245 DeviceClaim::Denied => json!({ "status": "denied" }),
246 DeviceClaim::Expired => json!({ "status": "expired" }),
247 })
248}
249
Fast pages, required checks on the branch, self-hosted runners, honest incidents250/// A sandbox reporting on a run of an issue's commands, from before a pull
251/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts252/// The run's own token, in the body, is the credential: it was given to
253/// that sandbox and to nothing else.
254async fn report_checks(
255 request: &mut Request,
256 services: &Services,
257 run_id: &str,
258) -> Result<Response> {
259 let body = json_body(request).await;
260 let reported: Outcome<CheckRun> = g1t_kit::call(
261 &services.work,
262 "report_checks",
263 &ReportChecksArgs {
264 run_id: run_id.to_owned(),
265 token: body["token"].as_str().unwrap_or_default().to_owned(),
266 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
267 error: body["error"].as_str().map(str::to_owned),
268 skip: false,
269 },
270 )
271 .await?;
272 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API273 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts274 Outcome::Fail(refused) => failure(&refused),
275 }
276}
277
Agents as a team: lifecycle, merge queue, billing and a new shell278/// A sandbox reporting one tested state of a merge queue. As with checks,
279/// the entry's own token is the credential.
280async fn report_queue(
281 request: &mut Request,
282 services: &Services,
283 entry_id: &str,
284) -> Result<Response> {
285 let body = json_body(request).await;
286 let reported: Outcome<QueueState> = g1t_kit::call(
287 &services.work,
288 "report_queue",
289 &ReportQueueArgs {
290 entry_id: entry_id.to_owned(),
291 token: body["token"].as_str().unwrap_or_default().to_owned(),
292 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
293 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
294 error: body["error"].as_str().map(str::to_owned),
295 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains296 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell297 },
298 )
299 .await?;
300 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API301 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell302 Outcome::Fail(refused) => failure(&refused),
303 }
304}
305
Agents and memory, checks and conflicts, profiles, slug renames, custom domains306/// A sandbox reporting whether a pull request merges cleanly. As with
307/// checks, the probe's own token is the credential.
308async fn report_mergecheck(
309 request: &mut Request,
310 services: &Services,
311 pull_id: &str,
312) -> Result<Response> {
313 let body = json_body(request).await;
314 let reported: Outcome<Mergeable> = g1t_kit::call(
315 &services.work,
316 "report_mergecheck",
317 &ReportMergecheckArgs {
318 pull_id: pull_id.to_owned(),
319 token: body["token"].as_str().unwrap_or_default().to_owned(),
320 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
321 error: body["error"].as_str().map(str::to_owned),
322 },
323 )
324 .await?;
325 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API326 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains327 Outcome::Fail(refused) => failure(&refused),
328 }
329}
330
Merge branch 'worktree-agent-ac5b181a013e54348'331/// A backup's sandbox, passed on to the repos service, which holds the
332/// job (services/repos/src/backups.rs; the flow is in
333/// `g1t_contracts::backups`):
334///
335/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
336/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
337/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
338/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
339///
340/// Bodies are passed through as they are: snake_case already, and a
341/// bundle's refs are keyed by ref names, which must not be converted.
342async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
343 use g1t_contracts::backups::TOKEN_HEADER;
344 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
345 let rest = path.trim_start_matches("/backups/");
346 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
347 if job.is_empty() || token.is_empty() {
348 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
349 }
350 if method == "PUT" && action.starts_with("parts/") {
351 let bytes = request.bytes().await?;
352 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
353 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
354 }
355 let headers = worker::Headers::new();
356 headers.set(TOKEN_HEADER, &token)?;
357 let mut init = worker::RequestInit::new();
358 init.with_method(Method::Put)
359 .with_headers(headers)
360 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
361 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
362 let mut answered = services.repos.fetch_request(forwarded).await?;
363 return outcome_as_given(answered.json().await?);
364 }
365 let rpc = match (method, action) {
366 ("POST", "spec") => "backup_spec",
367 ("POST", "complete") => "backup_complete",
368 ("POST", "fail") => "backup_fail",
369 _ => return fail(FailureCode::NotFound, "No such endpoint."),
370 };
371 let mut body = json_body(request).await;
372 if !body.is_object() {
373 body = json!({});
374 }
375 body["job_id"] = json!(job);
376 body["token"] = json!(token);
377 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
378 outcome_as_given(answered)
379}
380
381/// An `Outcome` from a service whose keys are already the API's: the value,
382/// or the failure in the shape every endpoint uses.
383fn outcome_as_given(answered: Value) -> Result<Response> {
384 match serde_json::from_value::<Outcome<Value>>(answered)? {
385 Outcome::Ok(value) => Response::from_json(&value),
386 Outcome::Fail(refused) => failure(&refused),
387 }
388}
389
Agents as a team: lifecycle, merge queue, billing and a new shell390/// A sandbox reporting the review its agent wrote. As with checks, the
391/// run's own token is the credential.
392async fn report_review(
393 request: &mut Request,
394 services: &Services,
395 run_id: &str,
396) -> Result<Response> {
397 let body = json_body(request).await;
398 let reported: Outcome<bool> = g1t_kit::call(
399 &services.work,
400 "report_review",
401 &ReportReviewArgs {
402 run_id: run_id.to_owned(),
403 token: body["token"].as_str().unwrap_or_default().to_owned(),
404 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
405 body: body["body"].as_str().unwrap_or_default().to_owned(),
406 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
407 model: body["model"].as_str().map(str::to_owned),
408 error: body["error"].as_str().map(str::to_owned),
409 },
410 )
411 .await?;
412 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API413 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell414 Outcome::Fail(refused) => failure(&refused),
415 }
416}
417
418/// A sandbox reporting the plan its agent wrote. As with checks, the
419/// plan's own token is the credential.
420async fn report_plan(
421 request: &mut Request,
422 services: &Services,
423 plan_id: &str,
424) -> Result<Response> {
425 let body = json_body(request).await;
426 let reported: Outcome<bool> = g1t_kit::call(
427 &services.work,
428 "report_plan",
429 &ReportPlanArgs {
430 plan_id: plan_id.to_owned(),
431 token: body["token"].as_str().unwrap_or_default().to_owned(),
432 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
433 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
434 error: body["error"].as_str().map(str::to_owned),
435 },
436 )
437 .await?;
438 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API439 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell440 Outcome::Fail(refused) => failure(&refused),
441 }
442}
443
444/// A sandbox reporting what its agent's run cost, so that the workspace
445/// it worked for is charged. As with checks, the run's own token is the
446/// credential.
447async fn report_usage(
448 request: &mut Request,
449 services: &Services,
450 run_id: &str,
451) -> Result<Response> {
452 let body = json_body(request).await;
453 let charged: Outcome<bool> = g1t_kit::call(
454 &services.billing,
455 "finish_run",
456 &FinishRunArgs {
457 run_id: run_id.to_owned(),
458 token: body["token"].as_str().unwrap_or_default().to_owned(),
459 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
460 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'461 // What the harness counted; the agent rate is charged on no
462 // fewer, on a workspace's own model key too.
463 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
464 input: t["input"].as_u64().unwrap_or_default(),
465 output: t["output"].as_u64().unwrap_or_default(),
466 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
467 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
468 }),
Agents as a team: lifecycle, merge queue, billing and a new shell469 },
470 )
471 .await?;
472 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API473 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell474 Outcome::Fail(refused) => failure(&refused),
475 }
476}
477
API and MCP server in Rust; a public index at the API root478async fn respond(mut request: Request, env: &Env) -> Result<Response> {
479 let method = method_name(request.method());
480 if method == "OPTIONS" {
481 return Ok(Response::empty()?.with_status(204));
482 }
483 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell484 // Paths carry no version. An earlier form began with `/v1`, which is
485 // still accepted so that nothing already written against it breaks.
486 let path = match url.path().strip_prefix("/v1") {
487 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
488 _ => url.path().to_owned(),
489 };
490 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'491 // MCP is a host of its own hosted, and may be a path on this one
492 // self-hosted (addresses.rs).
493 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root494
Stripe webhooks, enterprise invoices, and sudo for both495 // Stripe reporting to billing. Signed with the secret of the endpoint
496 // billing registered; the body goes through exactly as received, since
497 // the signature covers its bytes.
498 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
499 return receive_stripe(&mut request, env).await;
500 }
501
Integrations: your own model provider, alerts that open issues, tickets agents read502 // Outside systems reporting to a connection. They sign what they send
503 // with the connection's own secret, which is not a g1t token, so this
504 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide505 if method == "POST" && !on_mcp
506 && let Some(id) = path.strip_prefix("/hooks/").filter(|id| !id.is_empty() && !id.contains('/')) {
Integrations: your own model provider, alerts that open issues, tickets agents read507 return receive_hook(&mut request, &services, id).await;
508 }
509
Deployments: a preview for every pull request, production on g1t.page510 // A sandbox building a deployment, reporting with its build's token,
511 // which is not a g1t token. The body goes through as it is: it can
512 // carry a Worker's bundled code.
513 if method == "POST" && !on_mcp
514 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
515 {
516 let target = format!("https://deployments/jobs/{rest}");
517 let body = request.bytes().await?;
518 let headers = worker::Headers::new();
519 headers.set("content-type", "application/json")?;
520 let mut init = worker::RequestInit::new();
521 init.with_method(Method::Post)
522 .with_headers(headers)
523 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run524 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page525 .service("DEPLOYMENTS")?
526 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run527 .await?;
528 // A fresh response: a fetched one's headers cannot be changed, and
529 // every response gets the API's own on the way out.
530 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API531 let bytes = answer.bytes().await?;
532 let bytes = match serde_json::from_slice::<Value>(&bytes) {
533 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
534 Err(_) => bytes,
535 };
536 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run537 .with_status(status)
538 .with_headers({
539 let headers = worker::Headers::new();
540 headers.set("content-type", "application/json")?;
541 headers
542 }));
Deployments: a preview for every pull request, production on g1t.page543 }
544
A repository has its own sidebar, as settings do545 // A sandbox's artifacts and cache, with its job's token, which is not a
546 // g1t token either.
547 if !on_mcp
548 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents549 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do550 {
551 let rest = rest.to_owned();
552 return blobs::for_job(request, env, &services, method, &rest).await;
553 }
554
Fast pages, required checks on the branch, self-hosted runners, honest incidents555 // A self-hosted runner, with a registration token or its own
556 // credential, neither of which is a g1t access token.
557 if method == "POST"
558 && !on_mcp
559 && path.starts_with("/runners/")
560 && let Some(response) = runners::handle(&mut request, &services, &path).await?
561 {
562 return Ok(response);
563 }
564
API and MCP server in Rust; a public index at the API root565 let viewer = match authenticate(&request, &services).await? {
566 Ok(viewer) => viewer,
567 Err(refused) => return Ok(refused),
568 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API569 services.audit = audit::AuditContext::of(&request, on_mcp);
570 // An agent's token: what it may do comes with it, on the composite
571 // identity identity resolved it to.
572 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
573 services.scope = Some(acting.scope.clone());
574 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell575 let header = request.headers().get("authorization")?.unwrap_or_default();
576 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
577 let scope: Option<AgentScope> = g1t_kit::call(
578 &services.identity,
579 "agent_scope",
580 &TokenArgs {
581 token: token.to_owned(),
582 },
583 )
584 .await?;
585 // A scope is what lets an agent's token do anything at all.
586 let Some(scope) = scope else {
587 return fail(FailureCode::Unauthenticated, "Invalid access token.");
588 };
589 services.scope = Some(scope);
590 }
API and MCP server in Rust; a public index at the API root591 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
592 return Ok(response);
593 }
594 if on_mcp {
595 return mcp::handle(request, &services, &viewer).await;
596 }
597
598 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'599 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root600 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do601 // A run's artifacts: listed, or one downloaded.
602 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
603 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
604 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
605 return match rest {
606 [] => {
607 let seen: Outcome<Value> = g1t_kit::call(
608 &services.actions,
609 "run",
610 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
611 )
612 .await?;
613 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API614 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do615 Outcome::Fail(refused) => failure(&refused),
616 }
617 }
618 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
619 _ => fail(FailureCode::NotFound, "No such endpoint."),
620 };
621 }
622 }
Agents as a team: lifecycle, merge queue, billing and a new shell623 ("POST", "/device/code") => return device_code(&mut request, &services).await,
624 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically625 // Where a pull request lives, for a tool that knows only its fork.
626 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
627 let located: Outcome<Value> = g1t_kit::call(
628 &services.work,
629 "locate_pull",
630 &json!({ "id": &path[7..], "viewer": viewer }),
631 )
632 .await?;
633 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API634 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically635 Outcome::Fail(refused) => failure(&refused),
636 };
637 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains638 ("POST", path) if path.starts_with("/mergechecks/") => {
639 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
640 return report_mergecheck(&mut request, &services, &pull_id).await;
641 }
Merge branch 'worktree-agent-ac5b181a013e54348'642 // A sandbox making a repository's nightly backup. The job's own
643 // token, in its header, is the credential.
644 (method, path) if path.starts_with("/backups/") => {
645 return backup_job(&mut request, &services, method, path).await;
646 }
Agents as a team: lifecycle, merge queue, billing and a new shell647 ("POST", path) if path.starts_with("/queue/") => {
648 let entry_id = path.trim_start_matches("/queue/").to_owned();
649 return report_queue(&mut request, &services, &entry_id).await;
650 }
GitHub Actions on g1t, part two: running workflows651 // A sandbox running a GitHub Actions job: fetching the job, and
652 // reporting how it goes. The job's own token is the credential.
653 ("POST", path) if path.starts_with("/actions/jobs/") => {
654 let rest = path.trim_start_matches("/actions/jobs/");
655 let (job, method) = match rest.strip_suffix("/spec") {
656 Some(job) => (job.to_owned(), "job_spec"),
657 None => (rest.to_owned(), "job_report"),
658 };
659 let body = json_body(&mut request).await;
660 let answered: Outcome<Value> = g1t_kit::call(
661 &services.actions,
662 method,
663 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
664 )
665 .await?;
666 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API667 // A job's spec is the workflow and its contexts as GitHub
668 // has them; only g1t's own keys around them are converted.
669 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows670 Outcome::Fail(refused) => failure(&refused),
671 };
672 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains673 // A sandbox reporting its agent run's steps, cost and end. As with
674 // checks, the run's own token, in the body, is the credential.
675 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
676 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
677 let mut body = json_body(&mut request).await;
678 if !body.is_object() {
679 body = json!({});
680 }
681 body["runId"] = json!(run_id);
682 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
683 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API684 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains685 Outcome::Fail(refused) => failure(&refused),
686 };
687 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API688 // What a run's agent learned, as memory candidates; the same token.
689 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
690 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
691 let body = json_body(&mut request).await;
692 let learned = json!({
693 "runId": run_id,
694 "token": body["token"].as_str().unwrap_or_default(),
695 "items": body["items"].as_array().cloned().unwrap_or_default(),
696 });
697 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
698 return match captured {
699 Outcome::Ok(captured) => reply(&captured),
700 Outcome::Fail(refused) => failure(&refused),
701 };
702 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step703 // How sure a run's agent is of its change; the same token.
704 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
705 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
706 let body = json_body(&mut request).await;
707 let said = json!({
708 "runId": run_id,
709 "token": body["token"].as_str().unwrap_or_default(),
710 "confidence": body["confidence"].as_str().unwrap_or_default(),
711 "uncertainAbout": body["uncertain_about"]
712 .as_array()
713 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
714 .unwrap_or_default(),
715 });
716 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
717 return match recorded {
718 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
719 Outcome::Fail(refused) => failure(&refused),
720 };
721 }
Agents as a team: lifecycle, merge queue, billing and a new shell722 ("POST", path) if path.starts_with("/checks/") => {
723 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts724 return report_checks(&mut request, &services, &run_id).await;
725 }
Agents as a team: lifecycle, merge queue, billing and a new shell726 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
727 let run_id = path
728 .trim_start_matches("/runs/")
729 .trim_end_matches("/usage")
730 .to_owned();
731 return report_usage(&mut request, &services, &run_id).await;
732 }
733 ("POST", path) if path.starts_with("/plans/") => {
734 let plan_id = path.trim_start_matches("/plans/").to_owned();
735 return report_plan(&mut request, &services, &plan_id).await;
736 }
737 ("POST", path) if path.starts_with("/reviews/") => {
738 let run_id = path.trim_start_matches("/reviews/").to_owned();
739 return report_review(&mut request, &services, &run_id).await;
740 }
API and MCP server in Rust; a public index at the API root741 _ => {}
742 }
743
744 let query: Vec<(String, String)> = url
745 .query_pairs()
746 .map(|(name, value)| (name.into_owned(), value.into_owned()))
747 .collect();
748 let body = if method == "GET" {
749 Value::Null
750 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell751 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root752 };
753 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
754 return fail(FailureCode::NotFound, "No such endpoint.");
755 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API756 match audit::run(route.op, &services, &viewer, &input).await? {
757 Outcome::Ok(value) => reply(&value),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step758 // A token without the scope a call needs is told which one.
759 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
760 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
761 "error": {
762 "code": refused.code,
763 "message": refused.message,
764 "needed_scope": scope.as_str(),
765 }
766 }))?
767 .with_status(403)),
768 _ => failure(&refused),
769 },
API and MCP server in Rust; a public index at the API root770 }
771}
772
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API773/// Request bodies take the same keys as the MCP tools, `snake_case`, as
774/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell775fn snake_case_keys(body: Value) -> Value {
776 let Value::Object(fields) = body else {
777 return body;
778 };
779 let mut out = serde_json::Map::new();
780 for (key, value) in fields {
781 let mut snake = String::with_capacity(key.len() + 4);
782 for c in key.chars() {
783 if c.is_ascii_uppercase() {
784 snake.push('_');
785 snake.push(c.to_ascii_lowercase());
786 } else {
787 snake.push(c);
788 }
789 }
790 // A key given in both spellings keeps the snake_case one.
791 if snake != key && out.contains_key(&snake) {
792 continue;
793 }
794 out.insert(snake, value);
795 }
796 Value::Object(out)
797}
798
799#[cfg(test)]
800mod tests {
801 use super::snake_case_keys;
802 use serde_json::json;
803
804 #[test]
805 fn camel_case_keys_are_accepted() {
806 assert_eq!(
807 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
808 json!({ "count_agent_approvals": false, "title": "x" })
809 );
810 }
811
812 #[test]
813 fn snake_case_wins_when_both_are_given() {
814 assert_eq!(
815 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
816 json!({ "keep_issue_open": true })
817 );
818 }
819}
820
API and MCP server in Rust; a public index at the API root821// The API is called from browsers too: the reference's explorer, and apps
822// built on g1t. It carries no cookies, so any origin may call it.
823#[event(fetch)]
824async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
825 let mut response = respond(request, &env).await?;
826 let headers = response.headers_mut();
827 headers.set("access-control-allow-origin", "*")?;
828 headers.set(
829 "access-control-allow-headers",
830 "authorization, content-type",
831 )?;
832 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
833 headers.set("access-control-expose-headers", "www-authenticate")?;
834 Ok(response)
835}

This file's history is long; its oldest lines are credited to the oldest commit read.