Skip to content

g1t/apps/api/src/lib.rs

839 lines35,010 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 'main' into worktree-agent-a69aeabc4b0deeb977mod about;
Merge branch 'worktree-agent-aaf03bdceac799c89'8mod addresses;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily9mod alerts;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API10mod audit;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit11mod billing;
A repository has its own sidebar, as settings do12mod blobs;
Merge checks: statuses and check runs on every commit13mod checks;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9714mod deployments;
API and MCP server in Rust; a public index at the API root15mod mcp;
API: notifications over REST and MCP, with notifications scopes16mod notifications;
API and MCP server in Rust; a public index at the API root17mod oauth;
18mod openapi;
API: pinned projects over REST and MCP19mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9720mod projects;
API and MCP server in Rust; a public index at the API root21mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains22mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API23#[cfg(test)]
24mod responses;
API and MCP server in Rust; a public index at the API root25mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge26mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents27mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar28mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step29mod tools;
API and MCP server in Rust; a public index at the API root30
Merge branch 'model-routing'31use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root32use g1t_contracts::identity::{
33 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
34};
Agents as a team: lifecycle, merge queue, billing and a new shell35use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains36 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
37 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell38};
39use g1t_contracts::identity::AgentScope;
40use 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 API41use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root42use serde_json::{Value, json};
43use worker::{Context, Env, Method, Request, Response, Result, event};
44
45use operations::Services;
46
47fn method_name(method: Method) -> &'static str {
48 match method {
49 Method::Get => "GET",
50 Method::Post => "POST",
51 Method::Patch => "PATCH",
52 Method::Put => "PUT",
53 Method::Delete => "DELETE",
54 Method::Options => "OPTIONS",
55 Method::Head => "HEAD",
56 _ => "OTHER",
57 }
58}
59
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API60/// A JSON response. Every body the API sends has its keys in `snake_case`;
61/// the contracts it passes through are `camelCase`, so they are converted
62/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
63/// the MCP protocol's own envelope keep the spelling their standards use.
64pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
65 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
66}
67
68/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
69/// workflow file, GitHub's contexts and event, and where to check out, all
70/// passed through as they are.
71const JOB_SPEC_AS_GIVEN: &[&str] = &[
72 "spec", "workflow", "github", "event", "contexts", "checkout",
73];
74
API and MCP server in Rust; a public index at the API root75/// An error in the shape every endpoint uses.
76fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API77 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root78}
79
80fn fail(code: FailureCode, message: &str) -> Result<Response> {
81 failure(&Failure {
82 code,
83 message: message.to_owned(),
84 })
85}
86
87/// A request body as JSON. An empty or malformed body is no input.
88async fn json_body(request: &mut Request) -> Value {
89 request.json().await.unwrap_or(Value::Null)
90}
91
92/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
93/// an anonymous viewer; a wrong one is refused, so that a typo does not
94/// silently look signed out.
95async fn authenticate(
96 request: &Request,
97 services: &Services,
98) -> Result<std::result::Result<Viewer, Response>> {
99 let header = request.headers().get("authorization")?.unwrap_or_default();
100 let token = match header.split_once(' ') {
101 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
102 token.trim()
103 }
104 _ => return Ok(Ok(None)),
105 };
106 let viewer: Viewer = g1t_kit::call(
107 &services.identity,
108 "user_for_access_token",
109 &TokenArgs {
110 token: token.to_owned(),
111 },
112 )
113 .await?;
114 if viewer.is_some() {
115 return Ok(Ok(viewer));
116 }
117 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
118 // Tells an MCP client where to sign in again.
119 response.headers_mut().set(
120 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'121 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root122 )?;
123 Ok(Err(response))
124}
125
126/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'127fn index(addresses: &addresses::Addresses) -> Value {
128 let api = &addresses.api;
129 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root130 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'131 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'132 "openapi_url": format!("{api}/openapi.json"),
133 "mcp_url": addresses.mcp,
134 "current_user_url": format!("{api}/user"),
135 "workspaces_url": format!("{api}/workspaces"),
136 "repositories_url": format!("{api}/repos{{?q}}"),
137 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root138 "repository_url": repo,
139 "repository_events_url": format!("{repo}/events{{?before}}"),
140 "labels_url": format!("{repo}/labels"),
141 "issues_url": format!("{repo}/issues{{?state,label}}"),
142 "issue_url": format!("{repo}/issues/{{number}}"),
143 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
144 "pulls_url": format!("{repo}/pulls{{?state}}"),
145 "pull_url": format!("{repo}/pulls/{{number}}"),
146 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts147 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root148 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'149 "device_code_url": format!("{api}/device/code"),
150 "device_token_url": format!("{api}/device/token"),
151 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
152 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
153 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read154 "context_url": format!("{repo}/context{{?reference}}"),
155 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'156 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root157 })
158}
159
160// Signing in from a tool. Accounts are created, and passwords typed, only
161// in a browser; a tool gets its token by having a person approve a code.
162
Integrations: your own model provider, alerts that open issues, tickets agents read163/// Passes a request from an outside system to its connection, as it came:
164/// its signature covers the exact bytes of the body.
165async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
166 let headers: std::collections::HashMap<String, String> = request
167 .headers()
168 .entries()
169 .map(|(name, value)| (name.to_lowercase(), value))
170 .collect();
171 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look172 // A push to GitHub with many commits makes a large payload.
173 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
174 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API175 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read176 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look177 // g1t's GitHub App has one webhook for every installation; it is
178 // checked against the app's own secret.
179 let (method, args) = if id == "github" {
180 ("github_receive", json!({ "headers": headers, "body": body }))
181 } else {
182 ("receive", json!({ "id": id, "headers": headers, "body": body }))
183 };
184 let received: g1t_contracts::integrations::Received =
185 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 API186 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read187}
188
Stripe webhooks, enterprise invoices, and sudo for both189async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
190 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
191 let payload = request.text().await.unwrap_or_default();
192 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 API193 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both194 }
195 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
196 &env.service("BILLING")?,
197 "stripe_webhook",
198 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
199 )
200 .await?;
201 // A refusal is a 400, so Stripe shows it as failed; anything handled,
202 // or already handled, is a 200, so Stripe stops sending it.
203 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API204 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both205 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API206 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both207 }
208 })
209}
210
API and MCP server in Rust; a public index at the API root211async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
212 let body = json_body(request).await;
213 let started: DeviceStart = g1t_kit::call(
214 &services.identity,
215 "device_start",
216 &DeviceStartArgs {
217 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
218 },
219 )
220 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API221 reply(&json!({
API and MCP server in Rust; a public index at the API root222 "device_code": started.device_code,
223 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'224 "verification_uri": format!("{}/device", services.addresses.site),
225 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root226 "expires_in": started.expires_in,
227 "interval": started.interval,
228 }))
229}
230
231async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
232 let body = json_body(request).await;
233 let claim: DeviceClaim = g1t_kit::call(
234 &services.identity,
235 "device_claim",
236 &DeviceClaimArgs {
237 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
238 },
239 )
240 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API241 reply(&match claim {
API and MCP server in Rust; a public index at the API root242 DeviceClaim::Approved { token, user } => json!({
243 "status": "approved",
244 "token": token,
245 "username": user.username,
246 "verified": user.verified,
247 }),
248 DeviceClaim::Pending => json!({ "status": "pending" }),
249 DeviceClaim::Denied => json!({ "status": "denied" }),
250 DeviceClaim::Expired => json!({ "status": "expired" }),
251 })
252}
253
Fast pages, required checks on the branch, self-hosted runners, honest incidents254/// A sandbox reporting on a run of an issue's commands, from before a pull
255/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts256/// The run's own token, in the body, is the credential: it was given to
257/// that sandbox and to nothing else.
258async fn report_checks(
259 request: &mut Request,
260 services: &Services,
261 run_id: &str,
262) -> Result<Response> {
263 let body = json_body(request).await;
264 let reported: Outcome<CheckRun> = g1t_kit::call(
265 &services.work,
266 "report_checks",
267 &ReportChecksArgs {
268 run_id: run_id.to_owned(),
269 token: body["token"].as_str().unwrap_or_default().to_owned(),
270 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
271 error: body["error"].as_str().map(str::to_owned),
272 skip: false,
273 },
274 )
275 .await?;
276 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API277 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts278 Outcome::Fail(refused) => failure(&refused),
279 }
280}
281
Agents as a team: lifecycle, merge queue, billing and a new shell282/// A sandbox reporting one tested state of a merge queue. As with checks,
283/// the entry's own token is the credential.
284async fn report_queue(
285 request: &mut Request,
286 services: &Services,
287 entry_id: &str,
288) -> Result<Response> {
289 let body = json_body(request).await;
290 let reported: Outcome<QueueState> = g1t_kit::call(
291 &services.work,
292 "report_queue",
293 &ReportQueueArgs {
294 entry_id: entry_id.to_owned(),
295 token: body["token"].as_str().unwrap_or_default().to_owned(),
296 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
297 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
298 error: body["error"].as_str().map(str::to_owned),
299 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains300 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell301 },
302 )
303 .await?;
304 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API305 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell306 Outcome::Fail(refused) => failure(&refused),
307 }
308}
309
Agents and memory, checks and conflicts, profiles, slug renames, custom domains310/// A sandbox reporting whether a pull request merges cleanly. As with
311/// checks, the probe's own token is the credential.
312async fn report_mergecheck(
313 request: &mut Request,
314 services: &Services,
315 pull_id: &str,
316) -> Result<Response> {
317 let body = json_body(request).await;
318 let reported: Outcome<Mergeable> = g1t_kit::call(
319 &services.work,
320 "report_mergecheck",
321 &ReportMergecheckArgs {
322 pull_id: pull_id.to_owned(),
323 token: body["token"].as_str().unwrap_or_default().to_owned(),
324 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
325 error: body["error"].as_str().map(str::to_owned),
326 },
327 )
328 .await?;
329 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API330 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains331 Outcome::Fail(refused) => failure(&refused),
332 }
333}
334
Merge branch 'worktree-agent-ac5b181a013e54348'335/// A backup's sandbox, passed on to the repos service, which holds the
336/// job (services/repos/src/backups.rs; the flow is in
337/// `g1t_contracts::backups`):
338///
339/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
340/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
341/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
342/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
343///
344/// Bodies are passed through as they are: snake_case already, and a
345/// bundle's refs are keyed by ref names, which must not be converted.
346async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
347 use g1t_contracts::backups::TOKEN_HEADER;
348 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
349 let rest = path.trim_start_matches("/backups/");
350 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
351 if job.is_empty() || token.is_empty() {
352 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
353 }
354 if method == "PUT" && action.starts_with("parts/") {
355 let bytes = request.bytes().await?;
356 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
357 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
358 }
359 let headers = worker::Headers::new();
360 headers.set(TOKEN_HEADER, &token)?;
361 let mut init = worker::RequestInit::new();
362 init.with_method(Method::Put)
363 .with_headers(headers)
364 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
365 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
366 let mut answered = services.repos.fetch_request(forwarded).await?;
367 return outcome_as_given(answered.json().await?);
368 }
369 let rpc = match (method, action) {
370 ("POST", "spec") => "backup_spec",
371 ("POST", "complete") => "backup_complete",
372 ("POST", "fail") => "backup_fail",
373 _ => return fail(FailureCode::NotFound, "No such endpoint."),
374 };
375 let mut body = json_body(request).await;
376 if !body.is_object() {
377 body = json!({});
378 }
379 body["job_id"] = json!(job);
380 body["token"] = json!(token);
381 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
382 outcome_as_given(answered)
383}
384
385/// An `Outcome` from a service whose keys are already the API's: the value,
386/// or the failure in the shape every endpoint uses.
387fn outcome_as_given(answered: Value) -> Result<Response> {
388 match serde_json::from_value::<Outcome<Value>>(answered)? {
389 Outcome::Ok(value) => Response::from_json(&value),
390 Outcome::Fail(refused) => failure(&refused),
391 }
392}
393
Agents as a team: lifecycle, merge queue, billing and a new shell394/// A sandbox reporting the review its agent wrote. As with checks, the
395/// run's own token is the credential.
396async fn report_review(
397 request: &mut Request,
398 services: &Services,
399 run_id: &str,
400) -> Result<Response> {
401 let body = json_body(request).await;
402 let reported: Outcome<bool> = g1t_kit::call(
403 &services.work,
404 "report_review",
405 &ReportReviewArgs {
406 run_id: run_id.to_owned(),
407 token: body["token"].as_str().unwrap_or_default().to_owned(),
408 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
409 body: body["body"].as_str().unwrap_or_default().to_owned(),
410 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
411 model: body["model"].as_str().map(str::to_owned),
412 error: body["error"].as_str().map(str::to_owned),
413 },
414 )
415 .await?;
416 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API417 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell418 Outcome::Fail(refused) => failure(&refused),
419 }
420}
421
422/// A sandbox reporting the plan its agent wrote. As with checks, the
423/// plan's own token is the credential.
424async fn report_plan(
425 request: &mut Request,
426 services: &Services,
427 plan_id: &str,
428) -> Result<Response> {
429 let body = json_body(request).await;
430 let reported: Outcome<bool> = g1t_kit::call(
431 &services.work,
432 "report_plan",
433 &ReportPlanArgs {
434 plan_id: plan_id.to_owned(),
435 token: body["token"].as_str().unwrap_or_default().to_owned(),
436 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
437 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
438 error: body["error"].as_str().map(str::to_owned),
439 },
440 )
441 .await?;
442 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API443 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell444 Outcome::Fail(refused) => failure(&refused),
445 }
446}
447
448/// A sandbox reporting what its agent's run cost, so that the workspace
449/// it worked for is charged. As with checks, the run's own token is the
450/// credential.
451async fn report_usage(
452 request: &mut Request,
453 services: &Services,
454 run_id: &str,
455) -> Result<Response> {
456 let body = json_body(request).await;
457 let charged: Outcome<bool> = g1t_kit::call(
458 &services.billing,
459 "finish_run",
460 &FinishRunArgs {
461 run_id: run_id.to_owned(),
462 token: body["token"].as_str().unwrap_or_default().to_owned(),
463 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
464 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'465 // What the harness counted; the agent rate is charged on no
466 // fewer, on a workspace's own model key too.
467 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
468 input: t["input"].as_u64().unwrap_or_default(),
469 output: t["output"].as_u64().unwrap_or_default(),
470 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
471 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
472 }),
Agents as a team: lifecycle, merge queue, billing and a new shell473 },
474 )
475 .await?;
476 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API477 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell478 Outcome::Fail(refused) => failure(&refused),
479 }
480}
481
API and MCP server in Rust; a public index at the API root482async fn respond(mut request: Request, env: &Env) -> Result<Response> {
483 let method = method_name(request.method());
484 if method == "OPTIONS" {
485 return Ok(Response::empty()?.with_status(204));
486 }
487 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell488 // Paths carry no version. An earlier form began with `/v1`, which is
489 // still accepted so that nothing already written against it breaks.
490 let path = match url.path().strip_prefix("/v1") {
491 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
492 _ => url.path().to_owned(),
493 };
494 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'495 // MCP is a host of its own hosted, and may be a path on this one
496 // self-hosted (addresses.rs).
497 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root498
Stripe webhooks, enterprise invoices, and sudo for both499 // Stripe reporting to billing. Signed with the secret of the endpoint
500 // billing registered; the body goes through exactly as received, since
501 // the signature covers its bytes.
502 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
503 return receive_stripe(&mut request, env).await;
504 }
505
Integrations: your own model provider, alerts that open issues, tickets agents read506 // Outside systems reporting to a connection. They sign what they send
507 // with the connection's own secret, which is not a g1t token, so this
508 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide509 if method == "POST" && !on_mcp
510 && 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 read511 return receive_hook(&mut request, &services, id).await;
512 }
513
Deployments: a preview for every pull request, production on g1t.page514 // A sandbox building a deployment, reporting with its build's token,
515 // which is not a g1t token. The body goes through as it is: it can
516 // carry a Worker's bundled code.
517 if method == "POST" && !on_mcp
518 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
519 {
520 let target = format!("https://deployments/jobs/{rest}");
521 let body = request.bytes().await?;
522 let headers = worker::Headers::new();
523 headers.set("content-type", "application/json")?;
524 let mut init = worker::RequestInit::new();
525 init.with_method(Method::Post)
526 .with_headers(headers)
527 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run528 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page529 .service("DEPLOYMENTS")?
530 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run531 .await?;
532 // A fresh response: a fetched one's headers cannot be changed, and
533 // every response gets the API's own on the way out.
534 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API535 let bytes = answer.bytes().await?;
536 let bytes = match serde_json::from_slice::<Value>(&bytes) {
537 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
538 Err(_) => bytes,
539 };
540 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run541 .with_status(status)
542 .with_headers({
543 let headers = worker::Headers::new();
544 headers.set("content-type", "application/json")?;
545 headers
546 }));
Deployments: a preview for every pull request, production on g1t.page547 }
548
A repository has its own sidebar, as settings do549 // A sandbox's artifacts and cache, with its job's token, which is not a
550 // g1t token either.
551 if !on_mcp
552 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents553 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do554 {
555 let rest = rest.to_owned();
556 return blobs::for_job(request, env, &services, method, &rest).await;
557 }
558
Fast pages, required checks on the branch, self-hosted runners, honest incidents559 // A self-hosted runner, with a registration token or its own
560 // credential, neither of which is a g1t access token.
561 if method == "POST"
562 && !on_mcp
563 && path.starts_with("/runners/")
564 && let Some(response) = runners::handle(&mut request, &services, &path).await?
565 {
566 return Ok(response);
567 }
568
API and MCP server in Rust; a public index at the API root569 let viewer = match authenticate(&request, &services).await? {
570 Ok(viewer) => viewer,
571 Err(refused) => return Ok(refused),
572 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API573 services.audit = audit::AuditContext::of(&request, on_mcp);
574 // An agent's token: what it may do comes with it, on the composite
575 // identity identity resolved it to.
576 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
577 services.scope = Some(acting.scope.clone());
578 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell579 let header = request.headers().get("authorization")?.unwrap_or_default();
580 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
581 let scope: Option<AgentScope> = g1t_kit::call(
582 &services.identity,
583 "agent_scope",
584 &TokenArgs {
585 token: token.to_owned(),
586 },
587 )
588 .await?;
589 // A scope is what lets an agent's token do anything at all.
590 let Some(scope) = scope else {
591 return fail(FailureCode::Unauthenticated, "Invalid access token.");
592 };
593 services.scope = Some(scope);
594 }
API and MCP server in Rust; a public index at the API root595 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
596 return Ok(response);
597 }
598 if on_mcp {
599 return mcp::handle(request, &services, &viewer).await;
600 }
601
602 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'603 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root604 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do605 // A run's artifacts: listed, or one downloaded.
606 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
607 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
608 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
609 return match rest {
610 [] => {
611 let seen: Outcome<Value> = g1t_kit::call(
612 &services.actions,
613 "run",
614 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
615 )
616 .await?;
617 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API618 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do619 Outcome::Fail(refused) => failure(&refused),
620 }
621 }
622 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
623 _ => fail(FailureCode::NotFound, "No such endpoint."),
624 };
625 }
626 }
Agents as a team: lifecycle, merge queue, billing and a new shell627 ("POST", "/device/code") => return device_code(&mut request, &services).await,
628 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically629 // Where a pull request lives, for a tool that knows only its fork.
630 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
631 let located: Outcome<Value> = g1t_kit::call(
632 &services.work,
633 "locate_pull",
634 &json!({ "id": &path[7..], "viewer": viewer }),
635 )
636 .await?;
637 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API638 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically639 Outcome::Fail(refused) => failure(&refused),
640 };
641 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains642 ("POST", path) if path.starts_with("/mergechecks/") => {
643 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
644 return report_mergecheck(&mut request, &services, &pull_id).await;
645 }
Merge branch 'worktree-agent-ac5b181a013e54348'646 // A sandbox making a repository's nightly backup. The job's own
647 // token, in its header, is the credential.
648 (method, path) if path.starts_with("/backups/") => {
649 return backup_job(&mut request, &services, method, path).await;
650 }
Agents as a team: lifecycle, merge queue, billing and a new shell651 ("POST", path) if path.starts_with("/queue/") => {
652 let entry_id = path.trim_start_matches("/queue/").to_owned();
653 return report_queue(&mut request, &services, &entry_id).await;
654 }
GitHub Actions on g1t, part two: running workflows655 // A sandbox running a GitHub Actions job: fetching the job, and
656 // reporting how it goes. The job's own token is the credential.
657 ("POST", path) if path.starts_with("/actions/jobs/") => {
658 let rest = path.trim_start_matches("/actions/jobs/");
659 let (job, method) = match rest.strip_suffix("/spec") {
660 Some(job) => (job.to_owned(), "job_spec"),
661 None => (rest.to_owned(), "job_report"),
662 };
663 let body = json_body(&mut request).await;
664 let answered: Outcome<Value> = g1t_kit::call(
665 &services.actions,
666 method,
667 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
668 )
669 .await?;
670 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API671 // A job's spec is the workflow and its contexts as GitHub
672 // has them; only g1t's own keys around them are converted.
673 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows674 Outcome::Fail(refused) => failure(&refused),
675 };
676 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains677 // A sandbox reporting its agent run's steps, cost and end. As with
678 // checks, the run's own token, in the body, is the credential.
679 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
680 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
681 let mut body = json_body(&mut request).await;
682 if !body.is_object() {
683 body = json!({});
684 }
685 body["runId"] = json!(run_id);
686 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
687 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API688 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains689 Outcome::Fail(refused) => failure(&refused),
690 };
691 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API692 // What a run's agent learned, as memory candidates; the same token.
693 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
694 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
695 let body = json_body(&mut request).await;
696 let learned = json!({
697 "runId": run_id,
698 "token": body["token"].as_str().unwrap_or_default(),
699 "items": body["items"].as_array().cloned().unwrap_or_default(),
700 });
701 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
702 return match captured {
703 Outcome::Ok(captured) => reply(&captured),
704 Outcome::Fail(refused) => failure(&refused),
705 };
706 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step707 // How sure a run's agent is of its change; the same token.
708 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
709 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
710 let body = json_body(&mut request).await;
711 let said = json!({
712 "runId": run_id,
713 "token": body["token"].as_str().unwrap_or_default(),
714 "confidence": body["confidence"].as_str().unwrap_or_default(),
715 "uncertainAbout": body["uncertain_about"]
716 .as_array()
717 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
718 .unwrap_or_default(),
719 });
720 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
721 return match recorded {
722 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
723 Outcome::Fail(refused) => failure(&refused),
724 };
725 }
Agents as a team: lifecycle, merge queue, billing and a new shell726 ("POST", path) if path.starts_with("/checks/") => {
727 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts728 return report_checks(&mut request, &services, &run_id).await;
729 }
Agents as a team: lifecycle, merge queue, billing and a new shell730 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
731 let run_id = path
732 .trim_start_matches("/runs/")
733 .trim_end_matches("/usage")
734 .to_owned();
735 return report_usage(&mut request, &services, &run_id).await;
736 }
737 ("POST", path) if path.starts_with("/plans/") => {
738 let plan_id = path.trim_start_matches("/plans/").to_owned();
739 return report_plan(&mut request, &services, &plan_id).await;
740 }
741 ("POST", path) if path.starts_with("/reviews/") => {
742 let run_id = path.trim_start_matches("/reviews/").to_owned();
743 return report_review(&mut request, &services, &run_id).await;
744 }
API and MCP server in Rust; a public index at the API root745 _ => {}
746 }
747
748 let query: Vec<(String, String)> = url
749 .query_pairs()
750 .map(|(name, value)| (name.into_owned(), value.into_owned()))
751 .collect();
752 let body = if method == "GET" {
753 Value::Null
754 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell755 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root756 };
757 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
758 return fail(FailureCode::NotFound, "No such endpoint.");
759 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API760 match audit::run(route.op, &services, &viewer, &input).await? {
761 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 step762 // A token without the scope a call needs is told which one.
763 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
764 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
765 "error": {
766 "code": refused.code,
767 "message": refused.message,
768 "needed_scope": scope.as_str(),
769 }
770 }))?
771 .with_status(403)),
772 _ => failure(&refused),
773 },
API and MCP server in Rust; a public index at the API root774 }
775}
776
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API777/// Request bodies take the same keys as the MCP tools, `snake_case`, as
778/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell779fn snake_case_keys(body: Value) -> Value {
780 let Value::Object(fields) = body else {
781 return body;
782 };
783 let mut out = serde_json::Map::new();
784 for (key, value) in fields {
785 let mut snake = String::with_capacity(key.len() + 4);
786 for c in key.chars() {
787 if c.is_ascii_uppercase() {
788 snake.push('_');
789 snake.push(c.to_ascii_lowercase());
790 } else {
791 snake.push(c);
792 }
793 }
794 // A key given in both spellings keeps the snake_case one.
795 if snake != key && out.contains_key(&snake) {
796 continue;
797 }
798 out.insert(snake, value);
799 }
800 Value::Object(out)
801}
802
803#[cfg(test)]
804mod tests {
805 use super::snake_case_keys;
806 use serde_json::json;
807
808 #[test]
809 fn camel_case_keys_are_accepted() {
810 assert_eq!(
811 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
812 json!({ "count_agent_approvals": false, "title": "x" })
813 );
814 }
815
816 #[test]
817 fn snake_case_wins_when_both_are_given() {
818 assert_eq!(
819 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
820 json!({ "keep_issue_open": true })
821 );
822 }
823}
824
API and MCP server in Rust; a public index at the API root825// The API is called from browsers too: the reference's explorer, and apps
826// built on g1t. It carries no cookies, so any origin may call it.
827#[event(fetch)]
828async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
829 let mut response = respond(request, &env).await?;
830 let headers = response.headers_mut();
831 headers.set("access-control-allow-origin", "*")?;
832 headers.set(
833 "access-control-allow-headers",
834 "authorization, content-type",
835 )?;
836 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
837 headers.set("access-control-expose-headers", "www-authenticate")?;
838 Ok(response)
839}

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