Skip to content

g1t/apps/api/src/lib.rs

826 lines34,420 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;
Fast pages, required checks on the branch, self-hosted runners, honest incidents22mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar23mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step24mod tools;
API and MCP server in Rust; a public index at the API root25
Agents as a team: lifecycle, merge queue, billing and a new shell26use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root27use g1t_contracts::identity::{
28 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
29};
Agents as a team: lifecycle, merge queue, billing and a new shell30use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains31 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
32 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell33};
34use g1t_contracts::identity::AgentScope;
35use 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 API36use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root37use serde_json::{Value, json};
38use worker::{Context, Env, Method, Request, Response, Result, event};
39
40use operations::Services;
41
42fn method_name(method: Method) -> &'static str {
43 match method {
44 Method::Get => "GET",
45 Method::Post => "POST",
46 Method::Patch => "PATCH",
47 Method::Put => "PUT",
48 Method::Delete => "DELETE",
49 Method::Options => "OPTIONS",
50 Method::Head => "HEAD",
51 _ => "OTHER",
52 }
53}
54
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API55/// A JSON response. Every body the API sends has its keys in `snake_case`;
56/// the contracts it passes through are `camelCase`, so they are converted
57/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
58/// the MCP protocol's own envelope keep the spelling their standards use.
59pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
60 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
61}
62
63/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
64/// workflow file, GitHub's contexts and event, and where to check out, all
65/// passed through as they are.
66const JOB_SPEC_AS_GIVEN: &[&str] = &[
67 "spec", "workflow", "github", "event", "contexts", "checkout",
68];
69
API and MCP server in Rust; a public index at the API root70/// An error in the shape every endpoint uses.
71fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API72 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root73}
74
75fn fail(code: FailureCode, message: &str) -> Result<Response> {
76 failure(&Failure {
77 code,
78 message: message.to_owned(),
79 })
80}
81
82/// A request body as JSON. An empty or malformed body is no input.
83async fn json_body(request: &mut Request) -> Value {
84 request.json().await.unwrap_or(Value::Null)
85}
86
87/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
88/// an anonymous viewer; a wrong one is refused, so that a typo does not
89/// silently look signed out.
90async fn authenticate(
91 request: &Request,
92 services: &Services,
93) -> Result<std::result::Result<Viewer, Response>> {
94 let header = request.headers().get("authorization")?.unwrap_or_default();
95 let token = match header.split_once(' ') {
96 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
97 token.trim()
98 }
99 _ => return Ok(Ok(None)),
100 };
101 let viewer: Viewer = g1t_kit::call(
102 &services.identity,
103 "user_for_access_token",
104 &TokenArgs {
105 token: token.to_owned(),
106 },
107 )
108 .await?;
109 if viewer.is_some() {
110 return Ok(Ok(viewer));
111 }
112 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
113 // Tells an MCP client where to sign in again.
114 response.headers_mut().set(
115 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'116 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root117 )?;
118 Ok(Err(response))
119}
120
121/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'122fn index(addresses: &addresses::Addresses) -> Value {
123 let api = &addresses.api;
124 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root125 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'126 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'127 "openapi_url": format!("{api}/openapi.json"),
128 "mcp_url": addresses.mcp,
129 "current_user_url": format!("{api}/user"),
130 "workspaces_url": format!("{api}/workspaces"),
131 "repositories_url": format!("{api}/repos{{?q}}"),
132 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root133 "repository_url": repo,
134 "repository_events_url": format!("{repo}/events{{?before}}"),
135 "labels_url": format!("{repo}/labels"),
136 "issues_url": format!("{repo}/issues{{?state,label}}"),
137 "issue_url": format!("{repo}/issues/{{number}}"),
138 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
139 "pulls_url": format!("{repo}/pulls{{?state}}"),
140 "pull_url": format!("{repo}/pulls/{{number}}"),
141 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts142 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root143 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'144 "device_code_url": format!("{api}/device/code"),
145 "device_token_url": format!("{api}/device/token"),
146 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
147 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
148 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read149 "context_url": format!("{repo}/context{{?reference}}"),
150 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'151 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root152 })
153}
154
155// Signing in from a tool. Accounts are created, and passwords typed, only
156// in a browser; a tool gets its token by having a person approve a code.
157
Integrations: your own model provider, alerts that open issues, tickets agents read158/// Passes a request from an outside system to its connection, as it came:
159/// its signature covers the exact bytes of the body.
160async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
161 let headers: std::collections::HashMap<String, String> = request
162 .headers()
163 .entries()
164 .map(|(name, value)| (name.to_lowercase(), value))
165 .collect();
166 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look167 // A push to GitHub with many commits makes a large payload.
168 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
169 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API170 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read171 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look172 // g1t's GitHub App has one webhook for every installation; it is
173 // checked against the app's own secret.
174 let (method, args) = if id == "github" {
175 ("github_receive", json!({ "headers": headers, "body": body }))
176 } else {
177 ("receive", json!({ "id": id, "headers": headers, "body": body }))
178 };
179 let received: g1t_contracts::integrations::Received =
180 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 API181 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read182}
183
Stripe webhooks, enterprise invoices, and sudo for both184async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
185 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
186 let payload = request.text().await.unwrap_or_default();
187 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 API188 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both189 }
190 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
191 &env.service("BILLING")?,
192 "stripe_webhook",
193 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
194 )
195 .await?;
196 // A refusal is a 400, so Stripe shows it as failed; anything handled,
197 // or already handled, is a 200, so Stripe stops sending it.
198 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API199 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both200 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API201 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both202 }
203 })
204}
205
API and MCP server in Rust; a public index at the API root206async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
207 let body = json_body(request).await;
208 let started: DeviceStart = g1t_kit::call(
209 &services.identity,
210 "device_start",
211 &DeviceStartArgs {
212 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
213 },
214 )
215 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API216 reply(&json!({
API and MCP server in Rust; a public index at the API root217 "device_code": started.device_code,
218 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'219 "verification_uri": format!("{}/device", services.addresses.site),
220 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root221 "expires_in": started.expires_in,
222 "interval": started.interval,
223 }))
224}
225
226async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
227 let body = json_body(request).await;
228 let claim: DeviceClaim = g1t_kit::call(
229 &services.identity,
230 "device_claim",
231 &DeviceClaimArgs {
232 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
233 },
234 )
235 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API236 reply(&match claim {
API and MCP server in Rust; a public index at the API root237 DeviceClaim::Approved { token, user } => json!({
238 "status": "approved",
239 "token": token,
240 "username": user.username,
241 "verified": user.verified,
242 }),
243 DeviceClaim::Pending => json!({ "status": "pending" }),
244 DeviceClaim::Denied => json!({ "status": "denied" }),
245 DeviceClaim::Expired => json!({ "status": "expired" }),
246 })
247}
248
Fast pages, required checks on the branch, self-hosted runners, honest incidents249/// A sandbox reporting on a run of an issue's commands, from before a pull
250/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts251/// The run's own token, in the body, is the credential: it was given to
252/// that sandbox and to nothing else.
253async fn report_checks(
254 request: &mut Request,
255 services: &Services,
256 run_id: &str,
257) -> Result<Response> {
258 let body = json_body(request).await;
259 let reported: Outcome<CheckRun> = g1t_kit::call(
260 &services.work,
261 "report_checks",
262 &ReportChecksArgs {
263 run_id: run_id.to_owned(),
264 token: body["token"].as_str().unwrap_or_default().to_owned(),
265 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
266 error: body["error"].as_str().map(str::to_owned),
267 skip: false,
268 },
269 )
270 .await?;
271 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API272 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts273 Outcome::Fail(refused) => failure(&refused),
274 }
275}
276
Agents as a team: lifecycle, merge queue, billing and a new shell277/// A sandbox reporting one tested state of a merge queue. As with checks,
278/// the entry's own token is the credential.
279async fn report_queue(
280 request: &mut Request,
281 services: &Services,
282 entry_id: &str,
283) -> Result<Response> {
284 let body = json_body(request).await;
285 let reported: Outcome<QueueState> = g1t_kit::call(
286 &services.work,
287 "report_queue",
288 &ReportQueueArgs {
289 entry_id: entry_id.to_owned(),
290 token: body["token"].as_str().unwrap_or_default().to_owned(),
291 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
292 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
293 error: body["error"].as_str().map(str::to_owned),
294 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains295 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell296 },
297 )
298 .await?;
299 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API300 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell301 Outcome::Fail(refused) => failure(&refused),
302 }
303}
304
Agents and memory, checks and conflicts, profiles, slug renames, custom domains305/// A sandbox reporting whether a pull request merges cleanly. As with
306/// checks, the probe's own token is the credential.
307async fn report_mergecheck(
308 request: &mut Request,
309 services: &Services,
310 pull_id: &str,
311) -> Result<Response> {
312 let body = json_body(request).await;
313 let reported: Outcome<Mergeable> = g1t_kit::call(
314 &services.work,
315 "report_mergecheck",
316 &ReportMergecheckArgs {
317 pull_id: pull_id.to_owned(),
318 token: body["token"].as_str().unwrap_or_default().to_owned(),
319 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
320 error: body["error"].as_str().map(str::to_owned),
321 },
322 )
323 .await?;
324 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API325 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains326 Outcome::Fail(refused) => failure(&refused),
327 }
328}
329
Merge branch 'worktree-agent-ac5b181a013e54348'330/// A backup's sandbox, passed on to the repos service, which holds the
331/// job (services/repos/src/backups.rs; the flow is in
332/// `g1t_contracts::backups`):
333///
334/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
335/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
336/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
337/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
338///
339/// Bodies are passed through as they are: snake_case already, and a
340/// bundle's refs are keyed by ref names, which must not be converted.
341async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
342 use g1t_contracts::backups::TOKEN_HEADER;
343 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
344 let rest = path.trim_start_matches("/backups/");
345 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
346 if job.is_empty() || token.is_empty() {
347 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
348 }
349 if method == "PUT" && action.starts_with("parts/") {
350 let bytes = request.bytes().await?;
351 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
352 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
353 }
354 let headers = worker::Headers::new();
355 headers.set(TOKEN_HEADER, &token)?;
356 let mut init = worker::RequestInit::new();
357 init.with_method(Method::Put)
358 .with_headers(headers)
359 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
360 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
361 let mut answered = services.repos.fetch_request(forwarded).await?;
362 return outcome_as_given(answered.json().await?);
363 }
364 let rpc = match (method, action) {
365 ("POST", "spec") => "backup_spec",
366 ("POST", "complete") => "backup_complete",
367 ("POST", "fail") => "backup_fail",
368 _ => return fail(FailureCode::NotFound, "No such endpoint."),
369 };
370 let mut body = json_body(request).await;
371 if !body.is_object() {
372 body = json!({});
373 }
374 body["job_id"] = json!(job);
375 body["token"] = json!(token);
376 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
377 outcome_as_given(answered)
378}
379
380/// An `Outcome` from a service whose keys are already the API's: the value,
381/// or the failure in the shape every endpoint uses.
382fn outcome_as_given(answered: Value) -> Result<Response> {
383 match serde_json::from_value::<Outcome<Value>>(answered)? {
384 Outcome::Ok(value) => Response::from_json(&value),
385 Outcome::Fail(refused) => failure(&refused),
386 }
387}
388
Agents as a team: lifecycle, merge queue, billing and a new shell389/// A sandbox reporting the review its agent wrote. As with checks, the
390/// run's own token is the credential.
391async fn report_review(
392 request: &mut Request,
393 services: &Services,
394 run_id: &str,
395) -> Result<Response> {
396 let body = json_body(request).await;
397 let reported: Outcome<bool> = g1t_kit::call(
398 &services.work,
399 "report_review",
400 &ReportReviewArgs {
401 run_id: run_id.to_owned(),
402 token: body["token"].as_str().unwrap_or_default().to_owned(),
403 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
404 body: body["body"].as_str().unwrap_or_default().to_owned(),
405 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
406 model: body["model"].as_str().map(str::to_owned),
407 error: body["error"].as_str().map(str::to_owned),
408 },
409 )
410 .await?;
411 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API412 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell413 Outcome::Fail(refused) => failure(&refused),
414 }
415}
416
417/// A sandbox reporting the plan its agent wrote. As with checks, the
418/// plan's own token is the credential.
419async fn report_plan(
420 request: &mut Request,
421 services: &Services,
422 plan_id: &str,
423) -> Result<Response> {
424 let body = json_body(request).await;
425 let reported: Outcome<bool> = g1t_kit::call(
426 &services.work,
427 "report_plan",
428 &ReportPlanArgs {
429 plan_id: plan_id.to_owned(),
430 token: body["token"].as_str().unwrap_or_default().to_owned(),
431 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
432 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
433 error: body["error"].as_str().map(str::to_owned),
434 },
435 )
436 .await?;
437 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API438 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell439 Outcome::Fail(refused) => failure(&refused),
440 }
441}
442
443/// A sandbox reporting what its agent's run cost, so that the workspace
444/// it worked for is charged. As with checks, the run's own token is the
445/// credential.
446async fn report_usage(
447 request: &mut Request,
448 services: &Services,
449 run_id: &str,
450) -> Result<Response> {
451 let body = json_body(request).await;
452 let charged: Outcome<bool> = g1t_kit::call(
453 &services.billing,
454 "finish_run",
455 &FinishRunArgs {
456 run_id: run_id.to_owned(),
457 token: body["token"].as_str().unwrap_or_default().to_owned(),
458 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
459 turns: body["turns"].as_u64().unwrap_or_default() as u32,
460 },
461 )
462 .await?;
463 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API464 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell465 Outcome::Fail(refused) => failure(&refused),
466 }
467}
468
API and MCP server in Rust; a public index at the API root469async fn respond(mut request: Request, env: &Env) -> Result<Response> {
470 let method = method_name(request.method());
471 if method == "OPTIONS" {
472 return Ok(Response::empty()?.with_status(204));
473 }
474 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell475 // Paths carry no version. An earlier form began with `/v1`, which is
476 // still accepted so that nothing already written against it breaks.
477 let path = match url.path().strip_prefix("/v1") {
478 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
479 _ => url.path().to_owned(),
480 };
481 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'482 // MCP is a host of its own hosted, and may be a path on this one
483 // self-hosted (addresses.rs).
484 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root485
Stripe webhooks, enterprise invoices, and sudo for both486 // Stripe reporting to billing. Signed with the secret of the endpoint
487 // billing registered; the body goes through exactly as received, since
488 // the signature covers its bytes.
489 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
490 return receive_stripe(&mut request, env).await;
491 }
492
Integrations: your own model provider, alerts that open issues, tickets agents read493 // Outside systems reporting to a connection. They sign what they send
494 // with the connection's own secret, which is not a g1t token, so this
495 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide496 if method == "POST" && !on_mcp
497 && 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 read498 return receive_hook(&mut request, &services, id).await;
499 }
500
Deployments: a preview for every pull request, production on g1t.page501 // A sandbox building a deployment, reporting with its build's token,
502 // which is not a g1t token. The body goes through as it is: it can
503 // carry a Worker's bundled code.
504 if method == "POST" && !on_mcp
505 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
506 {
507 let target = format!("https://deployments/jobs/{rest}");
508 let body = request.bytes().await?;
509 let headers = worker::Headers::new();
510 headers.set("content-type", "application/json")?;
511 let mut init = worker::RequestInit::new();
512 init.with_method(Method::Post)
513 .with_headers(headers)
514 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run515 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page516 .service("DEPLOYMENTS")?
517 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run518 .await?;
519 // A fresh response: a fetched one's headers cannot be changed, and
520 // every response gets the API's own on the way out.
521 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API522 let bytes = answer.bytes().await?;
523 let bytes = match serde_json::from_slice::<Value>(&bytes) {
524 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
525 Err(_) => bytes,
526 };
527 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run528 .with_status(status)
529 .with_headers({
530 let headers = worker::Headers::new();
531 headers.set("content-type", "application/json")?;
532 headers
533 }));
Deployments: a preview for every pull request, production on g1t.page534 }
535
A repository has its own sidebar, as settings do536 // A sandbox's artifacts and cache, with its job's token, which is not a
537 // g1t token either.
538 if !on_mcp
539 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents540 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do541 {
542 let rest = rest.to_owned();
543 return blobs::for_job(request, env, &services, method, &rest).await;
544 }
545
Fast pages, required checks on the branch, self-hosted runners, honest incidents546 // A self-hosted runner, with a registration token or its own
547 // credential, neither of which is a g1t access token.
548 if method == "POST"
549 && !on_mcp
550 && path.starts_with("/runners/")
551 && let Some(response) = runners::handle(&mut request, &services, &path).await?
552 {
553 return Ok(response);
554 }
555
API and MCP server in Rust; a public index at the API root556 let viewer = match authenticate(&request, &services).await? {
557 Ok(viewer) => viewer,
558 Err(refused) => return Ok(refused),
559 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API560 services.audit = audit::AuditContext::of(&request, on_mcp);
561 // An agent's token: what it may do comes with it, on the composite
562 // identity identity resolved it to.
563 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
564 services.scope = Some(acting.scope.clone());
565 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell566 let header = request.headers().get("authorization")?.unwrap_or_default();
567 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
568 let scope: Option<AgentScope> = g1t_kit::call(
569 &services.identity,
570 "agent_scope",
571 &TokenArgs {
572 token: token.to_owned(),
573 },
574 )
575 .await?;
576 // A scope is what lets an agent's token do anything at all.
577 let Some(scope) = scope else {
578 return fail(FailureCode::Unauthenticated, "Invalid access token.");
579 };
580 services.scope = Some(scope);
581 }
API and MCP server in Rust; a public index at the API root582 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
583 return Ok(response);
584 }
585 if on_mcp {
586 return mcp::handle(request, &services, &viewer).await;
587 }
588
589 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'590 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root591 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do592 // A run's artifacts: listed, or one downloaded.
593 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
594 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
595 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
596 return match rest {
597 [] => {
598 let seen: Outcome<Value> = g1t_kit::call(
599 &services.actions,
600 "run",
601 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
602 )
603 .await?;
604 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API605 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do606 Outcome::Fail(refused) => failure(&refused),
607 }
608 }
609 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
610 _ => fail(FailureCode::NotFound, "No such endpoint."),
611 };
612 }
613 }
Agents as a team: lifecycle, merge queue, billing and a new shell614 ("POST", "/device/code") => return device_code(&mut request, &services).await,
615 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically616 // Where a pull request lives, for a tool that knows only its fork.
617 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
618 let located: Outcome<Value> = g1t_kit::call(
619 &services.work,
620 "locate_pull",
621 &json!({ "id": &path[7..], "viewer": viewer }),
622 )
623 .await?;
624 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API625 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically626 Outcome::Fail(refused) => failure(&refused),
627 };
628 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains629 ("POST", path) if path.starts_with("/mergechecks/") => {
630 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
631 return report_mergecheck(&mut request, &services, &pull_id).await;
632 }
Merge branch 'worktree-agent-ac5b181a013e54348'633 // A sandbox making a repository's nightly backup. The job's own
634 // token, in its header, is the credential.
635 (method, path) if path.starts_with("/backups/") => {
636 return backup_job(&mut request, &services, method, path).await;
637 }
Agents as a team: lifecycle, merge queue, billing and a new shell638 ("POST", path) if path.starts_with("/queue/") => {
639 let entry_id = path.trim_start_matches("/queue/").to_owned();
640 return report_queue(&mut request, &services, &entry_id).await;
641 }
GitHub Actions on g1t, part two: running workflows642 // A sandbox running a GitHub Actions job: fetching the job, and
643 // reporting how it goes. The job's own token is the credential.
644 ("POST", path) if path.starts_with("/actions/jobs/") => {
645 let rest = path.trim_start_matches("/actions/jobs/");
646 let (job, method) = match rest.strip_suffix("/spec") {
647 Some(job) => (job.to_owned(), "job_spec"),
648 None => (rest.to_owned(), "job_report"),
649 };
650 let body = json_body(&mut request).await;
651 let answered: Outcome<Value> = g1t_kit::call(
652 &services.actions,
653 method,
654 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
655 )
656 .await?;
657 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API658 // A job's spec is the workflow and its contexts as GitHub
659 // has them; only g1t's own keys around them are converted.
660 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows661 Outcome::Fail(refused) => failure(&refused),
662 };
663 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains664 // A sandbox reporting its agent run's steps, cost and end. As with
665 // checks, the run's own token, in the body, is the credential.
666 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
667 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
668 let mut body = json_body(&mut request).await;
669 if !body.is_object() {
670 body = json!({});
671 }
672 body["runId"] = json!(run_id);
673 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
674 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API675 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains676 Outcome::Fail(refused) => failure(&refused),
677 };
678 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API679 // What a run's agent learned, as memory candidates; the same token.
680 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
681 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
682 let body = json_body(&mut request).await;
683 let learned = json!({
684 "runId": run_id,
685 "token": body["token"].as_str().unwrap_or_default(),
686 "items": body["items"].as_array().cloned().unwrap_or_default(),
687 });
688 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
689 return match captured {
690 Outcome::Ok(captured) => reply(&captured),
691 Outcome::Fail(refused) => failure(&refused),
692 };
693 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step694 // How sure a run's agent is of its change; the same token.
695 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
696 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
697 let body = json_body(&mut request).await;
698 let said = json!({
699 "runId": run_id,
700 "token": body["token"].as_str().unwrap_or_default(),
701 "confidence": body["confidence"].as_str().unwrap_or_default(),
702 "uncertainAbout": body["uncertain_about"]
703 .as_array()
704 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
705 .unwrap_or_default(),
706 });
707 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
708 return match recorded {
709 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
710 Outcome::Fail(refused) => failure(&refused),
711 };
712 }
Agents as a team: lifecycle, merge queue, billing and a new shell713 ("POST", path) if path.starts_with("/checks/") => {
714 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts715 return report_checks(&mut request, &services, &run_id).await;
716 }
Agents as a team: lifecycle, merge queue, billing and a new shell717 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
718 let run_id = path
719 .trim_start_matches("/runs/")
720 .trim_end_matches("/usage")
721 .to_owned();
722 return report_usage(&mut request, &services, &run_id).await;
723 }
724 ("POST", path) if path.starts_with("/plans/") => {
725 let plan_id = path.trim_start_matches("/plans/").to_owned();
726 return report_plan(&mut request, &services, &plan_id).await;
727 }
728 ("POST", path) if path.starts_with("/reviews/") => {
729 let run_id = path.trim_start_matches("/reviews/").to_owned();
730 return report_review(&mut request, &services, &run_id).await;
731 }
API and MCP server in Rust; a public index at the API root732 _ => {}
733 }
734
735 let query: Vec<(String, String)> = url
736 .query_pairs()
737 .map(|(name, value)| (name.into_owned(), value.into_owned()))
738 .collect();
739 let body = if method == "GET" {
740 Value::Null
741 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell742 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root743 };
744 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
745 return fail(FailureCode::NotFound, "No such endpoint.");
746 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API747 match audit::run(route.op, &services, &viewer, &input).await? {
748 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 step749 // A token without the scope a call needs is told which one.
750 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
751 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
752 "error": {
753 "code": refused.code,
754 "message": refused.message,
755 "needed_scope": scope.as_str(),
756 }
757 }))?
758 .with_status(403)),
759 _ => failure(&refused),
760 },
API and MCP server in Rust; a public index at the API root761 }
762}
763
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API764/// Request bodies take the same keys as the MCP tools, `snake_case`, as
765/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell766fn snake_case_keys(body: Value) -> Value {
767 let Value::Object(fields) = body else {
768 return body;
769 };
770 let mut out = serde_json::Map::new();
771 for (key, value) in fields {
772 let mut snake = String::with_capacity(key.len() + 4);
773 for c in key.chars() {
774 if c.is_ascii_uppercase() {
775 snake.push('_');
776 snake.push(c.to_ascii_lowercase());
777 } else {
778 snake.push(c);
779 }
780 }
781 // A key given in both spellings keeps the snake_case one.
782 if snake != key && out.contains_key(&snake) {
783 continue;
784 }
785 out.insert(snake, value);
786 }
787 Value::Object(out)
788}
789
790#[cfg(test)]
791mod tests {
792 use super::snake_case_keys;
793 use serde_json::json;
794
795 #[test]
796 fn camel_case_keys_are_accepted() {
797 assert_eq!(
798 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
799 json!({ "count_agent_approvals": false, "title": "x" })
800 );
801 }
802
803 #[test]
804 fn snake_case_wins_when_both_are_given() {
805 assert_eq!(
806 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
807 json!({ "keep_issue_open": true })
808 );
809 }
810}
811
API and MCP server in Rust; a public index at the API root812// The API is called from browsers too: the reference's explorer, and apps
813// built on g1t. It carries no cookies, so any origin may call it.
814#[event(fetch)]
815async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
816 let mut response = respond(request, &env).await?;
817 let headers = response.headers_mut();
818 headers.set("access-control-allow-origin", "*")?;
819 headers.set(
820 "access-control-allow-headers",
821 "authorization, content-type",
822 )?;
823 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
824 headers.set("access-control-expose-headers", "www-authenticate")?;
825 Ok(response)
826}

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