Skip to content
825 linesCodeBlameRaw

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;
A repository has its own sidebar, as settings do10mod blobs;
API and MCP server in Rust; a public index at the API root11mod mcp;
API: notifications over REST and MCP, with notifications scopes12mod notifications;
API and MCP server in Rust; a public index at the API root13mod oauth;
14mod openapi;
API: pinned projects over REST and MCP15mod pins;
API and MCP server in Rust; a public index at the API root16mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains17mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API18#[cfg(test)]
19mod responses;
API and MCP server in Rust; a public index at the API root20mod rest;
Fast pages, required checks on the branch, self-hosted runners, honest incidents21mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar22mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step23mod tools;
API and MCP server in Rust; a public index at the API root24
Agents as a team: lifecycle, merge queue, billing and a new shell25use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root26use g1t_contracts::identity::{
27 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
28};
Agents as a team: lifecycle, merge queue, billing and a new shell29use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains30 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
31 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell32};
33use g1t_contracts::identity::AgentScope;
34use 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 API35use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root36use serde_json::{Value, json};
37use worker::{Context, Env, Method, Request, Response, Result, event};
38
39use operations::Services;
40
41fn method_name(method: Method) -> &'static str {
42 match method {
43 Method::Get => "GET",
44 Method::Post => "POST",
45 Method::Patch => "PATCH",
46 Method::Put => "PUT",
47 Method::Delete => "DELETE",
48 Method::Options => "OPTIONS",
49 Method::Head => "HEAD",
50 _ => "OTHER",
51 }
52}
53
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API54/// A JSON response. Every body the API sends has its keys in `snake_case`;
55/// the contracts it passes through are `camelCase`, so they are converted
56/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
57/// the MCP protocol's own envelope keep the spelling their standards use.
58pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
59 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
60}
61
62/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
63/// workflow file, GitHub's contexts and event, and where to check out, all
64/// passed through as they are.
65const JOB_SPEC_AS_GIVEN: &[&str] = &[
66 "spec", "workflow", "github", "event", "contexts", "checkout",
67];
68
API and MCP server in Rust; a public index at the API root69/// An error in the shape every endpoint uses.
70fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API71 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root72}
73
74fn fail(code: FailureCode, message: &str) -> Result<Response> {
75 failure(&Failure {
76 code,
77 message: message.to_owned(),
78 })
79}
80
81/// A request body as JSON. An empty or malformed body is no input.
82async fn json_body(request: &mut Request) -> Value {
83 request.json().await.unwrap_or(Value::Null)
84}
85
86/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
87/// an anonymous viewer; a wrong one is refused, so that a typo does not
88/// silently look signed out.
89async fn authenticate(
90 request: &Request,
91 services: &Services,
92) -> Result<std::result::Result<Viewer, Response>> {
93 let header = request.headers().get("authorization")?.unwrap_or_default();
94 let token = match header.split_once(' ') {
95 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
96 token.trim()
97 }
98 _ => return Ok(Ok(None)),
99 };
100 let viewer: Viewer = g1t_kit::call(
101 &services.identity,
102 "user_for_access_token",
103 &TokenArgs {
104 token: token.to_owned(),
105 },
106 )
107 .await?;
108 if viewer.is_some() {
109 return Ok(Ok(viewer));
110 }
111 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
112 // Tells an MCP client where to sign in again.
113 response.headers_mut().set(
114 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'115 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root116 )?;
117 Ok(Err(response))
118}
119
120/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'121fn index(addresses: &addresses::Addresses) -> Value {
122 let api = &addresses.api;
123 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root124 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'125 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'126 "openapi_url": format!("{api}/openapi.json"),
127 "mcp_url": addresses.mcp,
128 "current_user_url": format!("{api}/user"),
129 "workspaces_url": format!("{api}/workspaces"),
130 "repositories_url": format!("{api}/repos{{?q}}"),
131 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root132 "repository_url": repo,
133 "repository_events_url": format!("{repo}/events{{?before}}"),
134 "labels_url": format!("{repo}/labels"),
135 "issues_url": format!("{repo}/issues{{?state,label}}"),
136 "issue_url": format!("{repo}/issues/{{number}}"),
137 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
138 "pulls_url": format!("{repo}/pulls{{?state}}"),
139 "pull_url": format!("{repo}/pulls/{{number}}"),
140 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts141 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root142 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'143 "device_code_url": format!("{api}/device/code"),
144 "device_token_url": format!("{api}/device/token"),
145 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
146 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
147 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read148 "context_url": format!("{repo}/context{{?reference}}"),
149 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'150 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root151 })
152}
153
154// Signing in from a tool. Accounts are created, and passwords typed, only
155// in a browser; a tool gets its token by having a person approve a code.
156
Integrations: your own model provider, alerts that open issues, tickets agents read157/// Passes a request from an outside system to its connection, as it came:
158/// its signature covers the exact bytes of the body.
159async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
160 let headers: std::collections::HashMap<String, String> = request
161 .headers()
162 .entries()
163 .map(|(name, value)| (name.to_lowercase(), value))
164 .collect();
165 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look166 // A push to GitHub with many commits makes a large payload.
167 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
168 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API169 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read170 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look171 // g1t's GitHub App has one webhook for every installation; it is
172 // checked against the app's own secret.
173 let (method, args) = if id == "github" {
174 ("github_receive", json!({ "headers": headers, "body": body }))
175 } else {
176 ("receive", json!({ "id": id, "headers": headers, "body": body }))
177 };
178 let received: g1t_contracts::integrations::Received =
179 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 API180 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read181}
182
Stripe webhooks, enterprise invoices, and sudo for both183async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
184 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
185 let payload = request.text().await.unwrap_or_default();
186 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 API187 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both188 }
189 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
190 &env.service("BILLING")?,
191 "stripe_webhook",
192 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
193 )
194 .await?;
195 // A refusal is a 400, so Stripe shows it as failed; anything handled,
196 // or already handled, is a 200, so Stripe stops sending it.
197 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API198 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both199 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API200 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both201 }
202 })
203}
204
API and MCP server in Rust; a public index at the API root205async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
206 let body = json_body(request).await;
207 let started: DeviceStart = g1t_kit::call(
208 &services.identity,
209 "device_start",
210 &DeviceStartArgs {
211 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
212 },
213 )
214 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API215 reply(&json!({
API and MCP server in Rust; a public index at the API root216 "device_code": started.device_code,
217 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'218 "verification_uri": format!("{}/device", services.addresses.site),
219 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root220 "expires_in": started.expires_in,
221 "interval": started.interval,
222 }))
223}
224
225async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
226 let body = json_body(request).await;
227 let claim: DeviceClaim = g1t_kit::call(
228 &services.identity,
229 "device_claim",
230 &DeviceClaimArgs {
231 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
232 },
233 )
234 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API235 reply(&match claim {
API and MCP server in Rust; a public index at the API root236 DeviceClaim::Approved { token, user } => json!({
237 "status": "approved",
238 "token": token,
239 "username": user.username,
240 "verified": user.verified,
241 }),
242 DeviceClaim::Pending => json!({ "status": "pending" }),
243 DeviceClaim::Denied => json!({ "status": "denied" }),
244 DeviceClaim::Expired => json!({ "status": "expired" }),
245 })
246}
247
Fast pages, required checks on the branch, self-hosted runners, honest incidents248/// A sandbox reporting on a run of an issue's commands, from before a pull
249/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts250/// The run's own token, in the body, is the credential: it was given to
251/// that sandbox and to nothing else.
252async fn report_checks(
253 request: &mut Request,
254 services: &Services,
255 run_id: &str,
256) -> Result<Response> {
257 let body = json_body(request).await;
258 let reported: Outcome<CheckRun> = g1t_kit::call(
259 &services.work,
260 "report_checks",
261 &ReportChecksArgs {
262 run_id: run_id.to_owned(),
263 token: body["token"].as_str().unwrap_or_default().to_owned(),
264 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
265 error: body["error"].as_str().map(str::to_owned),
266 skip: false,
267 },
268 )
269 .await?;
270 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API271 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts272 Outcome::Fail(refused) => failure(&refused),
273 }
274}
275
Agents as a team: lifecycle, merge queue, billing and a new shell276/// A sandbox reporting one tested state of a merge queue. As with checks,
277/// the entry's own token is the credential.
278async fn report_queue(
279 request: &mut Request,
280 services: &Services,
281 entry_id: &str,
282) -> Result<Response> {
283 let body = json_body(request).await;
284 let reported: Outcome<QueueState> = g1t_kit::call(
285 &services.work,
286 "report_queue",
287 &ReportQueueArgs {
288 entry_id: entry_id.to_owned(),
289 token: body["token"].as_str().unwrap_or_default().to_owned(),
290 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
291 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
292 error: body["error"].as_str().map(str::to_owned),
293 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains294 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell295 },
296 )
297 .await?;
298 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API299 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell300 Outcome::Fail(refused) => failure(&refused),
301 }
302}
303
Agents and memory, checks and conflicts, profiles, slug renames, custom domains304/// A sandbox reporting whether a pull request merges cleanly. As with
305/// checks, the probe's own token is the credential.
306async fn report_mergecheck(
307 request: &mut Request,
308 services: &Services,
309 pull_id: &str,
310) -> Result<Response> {
311 let body = json_body(request).await;
312 let reported: Outcome<Mergeable> = g1t_kit::call(
313 &services.work,
314 "report_mergecheck",
315 &ReportMergecheckArgs {
316 pull_id: pull_id.to_owned(),
317 token: body["token"].as_str().unwrap_or_default().to_owned(),
318 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
319 error: body["error"].as_str().map(str::to_owned),
320 },
321 )
322 .await?;
323 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API324 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains325 Outcome::Fail(refused) => failure(&refused),
326 }
327}
328
Merge branch 'worktree-agent-ac5b181a013e54348'329/// A backup's sandbox, passed on to the repos service, which holds the
330/// job (services/repos/src/backups.rs; the flow is in
331/// `g1t_contracts::backups`):
332///
333/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
334/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
335/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
336/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
337///
338/// Bodies are passed through as they are: snake_case already, and a
339/// bundle's refs are keyed by ref names, which must not be converted.
340async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
341 use g1t_contracts::backups::TOKEN_HEADER;
342 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
343 let rest = path.trim_start_matches("/backups/");
344 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
345 if job.is_empty() || token.is_empty() {
346 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
347 }
348 if method == "PUT" && action.starts_with("parts/") {
349 let bytes = request.bytes().await?;
350 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
351 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
352 }
353 let headers = worker::Headers::new();
354 headers.set(TOKEN_HEADER, &token)?;
355 let mut init = worker::RequestInit::new();
356 init.with_method(Method::Put)
357 .with_headers(headers)
358 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
359 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
360 let mut answered = services.repos.fetch_request(forwarded).await?;
361 return outcome_as_given(answered.json().await?);
362 }
363 let rpc = match (method, action) {
364 ("POST", "spec") => "backup_spec",
365 ("POST", "complete") => "backup_complete",
366 ("POST", "fail") => "backup_fail",
367 _ => return fail(FailureCode::NotFound, "No such endpoint."),
368 };
369 let mut body = json_body(request).await;
370 if !body.is_object() {
371 body = json!({});
372 }
373 body["job_id"] = json!(job);
374 body["token"] = json!(token);
375 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
376 outcome_as_given(answered)
377}
378
379/// An `Outcome` from a service whose keys are already the API's: the value,
380/// or the failure in the shape every endpoint uses.
381fn outcome_as_given(answered: Value) -> Result<Response> {
382 match serde_json::from_value::<Outcome<Value>>(answered)? {
383 Outcome::Ok(value) => Response::from_json(&value),
384 Outcome::Fail(refused) => failure(&refused),
385 }
386}
387
Agents as a team: lifecycle, merge queue, billing and a new shell388/// A sandbox reporting the review its agent wrote. As with checks, the
389/// run's own token is the credential.
390async fn report_review(
391 request: &mut Request,
392 services: &Services,
393 run_id: &str,
394) -> Result<Response> {
395 let body = json_body(request).await;
396 let reported: Outcome<bool> = g1t_kit::call(
397 &services.work,
398 "report_review",
399 &ReportReviewArgs {
400 run_id: run_id.to_owned(),
401 token: body["token"].as_str().unwrap_or_default().to_owned(),
402 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
403 body: body["body"].as_str().unwrap_or_default().to_owned(),
404 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
405 model: body["model"].as_str().map(str::to_owned),
406 error: body["error"].as_str().map(str::to_owned),
407 },
408 )
409 .await?;
410 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API411 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell412 Outcome::Fail(refused) => failure(&refused),
413 }
414}
415
416/// A sandbox reporting the plan its agent wrote. As with checks, the
417/// plan's own token is the credential.
418async fn report_plan(
419 request: &mut Request,
420 services: &Services,
421 plan_id: &str,
422) -> Result<Response> {
423 let body = json_body(request).await;
424 let reported: Outcome<bool> = g1t_kit::call(
425 &services.work,
426 "report_plan",
427 &ReportPlanArgs {
428 plan_id: plan_id.to_owned(),
429 token: body["token"].as_str().unwrap_or_default().to_owned(),
430 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
431 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
432 error: body["error"].as_str().map(str::to_owned),
433 },
434 )
435 .await?;
436 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API437 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell438 Outcome::Fail(refused) => failure(&refused),
439 }
440}
441
442/// A sandbox reporting what its agent's run cost, so that the workspace
443/// it worked for is charged. As with checks, the run's own token is the
444/// credential.
445async fn report_usage(
446 request: &mut Request,
447 services: &Services,
448 run_id: &str,
449) -> Result<Response> {
450 let body = json_body(request).await;
451 let charged: Outcome<bool> = g1t_kit::call(
452 &services.billing,
453 "finish_run",
454 &FinishRunArgs {
455 run_id: run_id.to_owned(),
456 token: body["token"].as_str().unwrap_or_default().to_owned(),
457 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
458 turns: body["turns"].as_u64().unwrap_or_default() as u32,
459 },
460 )
461 .await?;
462 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API463 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell464 Outcome::Fail(refused) => failure(&refused),
465 }
466}
467
API and MCP server in Rust; a public index at the API root468async fn respond(mut request: Request, env: &Env) -> Result<Response> {
469 let method = method_name(request.method());
470 if method == "OPTIONS" {
471 return Ok(Response::empty()?.with_status(204));
472 }
473 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell474 // Paths carry no version. An earlier form began with `/v1`, which is
475 // still accepted so that nothing already written against it breaks.
476 let path = match url.path().strip_prefix("/v1") {
477 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
478 _ => url.path().to_owned(),
479 };
480 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'481 // MCP is a host of its own hosted, and may be a path on this one
482 // self-hosted (addresses.rs).
483 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root484
Stripe webhooks, enterprise invoices, and sudo for both485 // Stripe reporting to billing. Signed with the secret of the endpoint
486 // billing registered; the body goes through exactly as received, since
487 // the signature covers its bytes.
488 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
489 return receive_stripe(&mut request, env).await;
490 }
491
Integrations: your own model provider, alerts that open issues, tickets agents read492 // Outside systems reporting to a connection. They sign what they send
493 // with the connection's own secret, which is not a g1t token, so this
494 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide495 if method == "POST" && !on_mcp
496 && 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 read497 return receive_hook(&mut request, &services, id).await;
498 }
499
Deployments: a preview for every pull request, production on g1t.page500 // A sandbox building a deployment, reporting with its build's token,
501 // which is not a g1t token. The body goes through as it is: it can
502 // carry a Worker's bundled code.
503 if method == "POST" && !on_mcp
504 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
505 {
506 let target = format!("https://deployments/jobs/{rest}");
507 let body = request.bytes().await?;
508 let headers = worker::Headers::new();
509 headers.set("content-type", "application/json")?;
510 let mut init = worker::RequestInit::new();
511 init.with_method(Method::Post)
512 .with_headers(headers)
513 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run514 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page515 .service("DEPLOYMENTS")?
516 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run517 .await?;
518 // A fresh response: a fetched one's headers cannot be changed, and
519 // every response gets the API's own on the way out.
520 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API521 let bytes = answer.bytes().await?;
522 let bytes = match serde_json::from_slice::<Value>(&bytes) {
523 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
524 Err(_) => bytes,
525 };
526 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run527 .with_status(status)
528 .with_headers({
529 let headers = worker::Headers::new();
530 headers.set("content-type", "application/json")?;
531 headers
532 }));
Deployments: a preview for every pull request, production on g1t.page533 }
534
A repository has its own sidebar, as settings do535 // A sandbox's artifacts and cache, with its job's token, which is not a
536 // g1t token either.
537 if !on_mcp
538 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents539 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do540 {
541 let rest = rest.to_owned();
542 return blobs::for_job(request, env, &services, method, &rest).await;
543 }
544
Fast pages, required checks on the branch, self-hosted runners, honest incidents545 // A self-hosted runner, with a registration token or its own
546 // credential, neither of which is a g1t access token.
547 if method == "POST"
548 && !on_mcp
549 && path.starts_with("/runners/")
550 && let Some(response) = runners::handle(&mut request, &services, &path).await?
551 {
552 return Ok(response);
553 }
554
API and MCP server in Rust; a public index at the API root555 let viewer = match authenticate(&request, &services).await? {
556 Ok(viewer) => viewer,
557 Err(refused) => return Ok(refused),
558 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API559 services.audit = audit::AuditContext::of(&request, on_mcp);
560 // An agent's token: what it may do comes with it, on the composite
561 // identity identity resolved it to.
562 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
563 services.scope = Some(acting.scope.clone());
564 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell565 let header = request.headers().get("authorization")?.unwrap_or_default();
566 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
567 let scope: Option<AgentScope> = g1t_kit::call(
568 &services.identity,
569 "agent_scope",
570 &TokenArgs {
571 token: token.to_owned(),
572 },
573 )
574 .await?;
575 // A scope is what lets an agent's token do anything at all.
576 let Some(scope) = scope else {
577 return fail(FailureCode::Unauthenticated, "Invalid access token.");
578 };
579 services.scope = Some(scope);
580 }
API and MCP server in Rust; a public index at the API root581 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
582 return Ok(response);
583 }
584 if on_mcp {
585 return mcp::handle(request, &services, &viewer).await;
586 }
587
588 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'589 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root590 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do591 // A run's artifacts: listed, or one downloaded.
592 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
593 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
594 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
595 return match rest {
596 [] => {
597 let seen: Outcome<Value> = g1t_kit::call(
598 &services.actions,
599 "run",
600 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
601 )
602 .await?;
603 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API604 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do605 Outcome::Fail(refused) => failure(&refused),
606 }
607 }
608 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
609 _ => fail(FailureCode::NotFound, "No such endpoint."),
610 };
611 }
612 }
Agents as a team: lifecycle, merge queue, billing and a new shell613 ("POST", "/device/code") => return device_code(&mut request, &services).await,
614 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically615 // Where a pull request lives, for a tool that knows only its fork.
616 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
617 let located: Outcome<Value> = g1t_kit::call(
618 &services.work,
619 "locate_pull",
620 &json!({ "id": &path[7..], "viewer": viewer }),
621 )
622 .await?;
623 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API624 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically625 Outcome::Fail(refused) => failure(&refused),
626 };
627 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains628 ("POST", path) if path.starts_with("/mergechecks/") => {
629 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
630 return report_mergecheck(&mut request, &services, &pull_id).await;
631 }
Merge branch 'worktree-agent-ac5b181a013e54348'632 // A sandbox making a repository's nightly backup. The job's own
633 // token, in its header, is the credential.
634 (method, path) if path.starts_with("/backups/") => {
635 return backup_job(&mut request, &services, method, path).await;
636 }
Agents as a team: lifecycle, merge queue, billing and a new shell637 ("POST", path) if path.starts_with("/queue/") => {
638 let entry_id = path.trim_start_matches("/queue/").to_owned();
639 return report_queue(&mut request, &services, &entry_id).await;
640 }
GitHub Actions on g1t, part two: running workflows641 // A sandbox running a GitHub Actions job: fetching the job, and
642 // reporting how it goes. The job's own token is the credential.
643 ("POST", path) if path.starts_with("/actions/jobs/") => {
644 let rest = path.trim_start_matches("/actions/jobs/");
645 let (job, method) = match rest.strip_suffix("/spec") {
646 Some(job) => (job.to_owned(), "job_spec"),
647 None => (rest.to_owned(), "job_report"),
648 };
649 let body = json_body(&mut request).await;
650 let answered: Outcome<Value> = g1t_kit::call(
651 &services.actions,
652 method,
653 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
654 )
655 .await?;
656 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API657 // A job's spec is the workflow and its contexts as GitHub
658 // has them; only g1t's own keys around them are converted.
659 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows660 Outcome::Fail(refused) => failure(&refused),
661 };
662 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains663 // A sandbox reporting its agent run's steps, cost and end. As with
664 // checks, the run's own token, in the body, is the credential.
665 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
666 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
667 let mut body = json_body(&mut request).await;
668 if !body.is_object() {
669 body = json!({});
670 }
671 body["runId"] = json!(run_id);
672 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
673 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API674 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains675 Outcome::Fail(refused) => failure(&refused),
676 };
677 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API678 // What a run's agent learned, as memory candidates; the same token.
679 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
680 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
681 let body = json_body(&mut request).await;
682 let learned = json!({
683 "runId": run_id,
684 "token": body["token"].as_str().unwrap_or_default(),
685 "items": body["items"].as_array().cloned().unwrap_or_default(),
686 });
687 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
688 return match captured {
689 Outcome::Ok(captured) => reply(&captured),
690 Outcome::Fail(refused) => failure(&refused),
691 };
692 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step693 // How sure a run's agent is of its change; the same token.
694 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
695 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
696 let body = json_body(&mut request).await;
697 let said = json!({
698 "runId": run_id,
699 "token": body["token"].as_str().unwrap_or_default(),
700 "confidence": body["confidence"].as_str().unwrap_or_default(),
701 "uncertainAbout": body["uncertain_about"]
702 .as_array()
703 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
704 .unwrap_or_default(),
705 });
706 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
707 return match recorded {
708 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
709 Outcome::Fail(refused) => failure(&refused),
710 };
711 }
Agents as a team: lifecycle, merge queue, billing and a new shell712 ("POST", path) if path.starts_with("/checks/") => {
713 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts714 return report_checks(&mut request, &services, &run_id).await;
715 }
Agents as a team: lifecycle, merge queue, billing and a new shell716 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
717 let run_id = path
718 .trim_start_matches("/runs/")
719 .trim_end_matches("/usage")
720 .to_owned();
721 return report_usage(&mut request, &services, &run_id).await;
722 }
723 ("POST", path) if path.starts_with("/plans/") => {
724 let plan_id = path.trim_start_matches("/plans/").to_owned();
725 return report_plan(&mut request, &services, &plan_id).await;
726 }
727 ("POST", path) if path.starts_with("/reviews/") => {
728 let run_id = path.trim_start_matches("/reviews/").to_owned();
729 return report_review(&mut request, &services, &run_id).await;
730 }
API and MCP server in Rust; a public index at the API root731 _ => {}
732 }
733
734 let query: Vec<(String, String)> = url
735 .query_pairs()
736 .map(|(name, value)| (name.into_owned(), value.into_owned()))
737 .collect();
738 let body = if method == "GET" {
739 Value::Null
740 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell741 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root742 };
743 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
744 return fail(FailureCode::NotFound, "No such endpoint.");
745 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API746 match audit::run(route.op, &services, &viewer, &input).await? {
747 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 step748 // A token without the scope a call needs is told which one.
749 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
750 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
751 "error": {
752 "code": refused.code,
753 "message": refused.message,
754 "needed_scope": scope.as_str(),
755 }
756 }))?
757 .with_status(403)),
758 _ => failure(&refused),
759 },
API and MCP server in Rust; a public index at the API root760 }
761}
762
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API763/// Request bodies take the same keys as the MCP tools, `snake_case`, as
764/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell765fn snake_case_keys(body: Value) -> Value {
766 let Value::Object(fields) = body else {
767 return body;
768 };
769 let mut out = serde_json::Map::new();
770 for (key, value) in fields {
771 let mut snake = String::with_capacity(key.len() + 4);
772 for c in key.chars() {
773 if c.is_ascii_uppercase() {
774 snake.push('_');
775 snake.push(c.to_ascii_lowercase());
776 } else {
777 snake.push(c);
778 }
779 }
780 // A key given in both spellings keeps the snake_case one.
781 if snake != key && out.contains_key(&snake) {
782 continue;
783 }
784 out.insert(snake, value);
785 }
786 Value::Object(out)
787}
788
789#[cfg(test)]
790mod tests {
791 use super::snake_case_keys;
792 use serde_json::json;
793
794 #[test]
795 fn camel_case_keys_are_accepted() {
796 assert_eq!(
797 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
798 json!({ "count_agent_approvals": false, "title": "x" })
799 );
800 }
801
802 #[test]
803 fn snake_case_wins_when_both_are_given() {
804 assert_eq!(
805 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
806 json!({ "keep_issue_open": true })
807 );
808 }
809}
810
API and MCP server in Rust; a public index at the API root811// The API is called from browsers too: the reference's explorer, and apps
812// built on g1t. It carries no cookies, so any origin may call it.
813#[event(fetch)]
814async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
815 let mut response = respond(request, &env).await?;
816 let headers = response.headers_mut();
817 headers.set("access-control-allow-origin", "*")?;
818 headers.set(
819 "access-control-allow-headers",
820 "authorization, content-type",
821 )?;
822 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
823 headers.set("access-control-expose-headers", "www-authenticate")?;
824 Ok(response)
825}

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