Skip to content
837 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;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit10mod billing;
A repository has its own sidebar, as settings do11mod blobs;
Deployments wherever they run: API, g1t Actions environments, and a Deployments section12mod deployments;
API and MCP server in Rust; a public index at the API root13mod mcp;
API: notifications over REST and MCP, with notifications scopes14mod notifications;
API and MCP server in Rust; a public index at the API root15mod oauth;
16mod openapi;
API: pinned projects over REST and MCP17mod pins;
Merge branch 'main' into worktree-agent-a7dbe21737f9ad26a18mod projects;
API and MCP server in Rust; a public index at the API root19mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains20mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API21#[cfg(test)]
22mod responses;
API and MCP server in Rust; a public index at the API root23mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge24mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents25mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar26mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step27mod tools;
API and MCP server in Rust; a public index at the API root28
Merge branch 'model-routing'29use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root30use g1t_contracts::identity::{
31 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
32};
Agents as a team: lifecycle, merge queue, billing and a new shell33use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains34 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
35 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell36};
37use g1t_contracts::identity::AgentScope;
38use 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 API39use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root40use serde_json::{Value, json};
41use worker::{Context, Env, Method, Request, Response, Result, event};
42
43use operations::Services;
44
45fn method_name(method: Method) -> &'static str {
46 match method {
47 Method::Get => "GET",
48 Method::Post => "POST",
49 Method::Patch => "PATCH",
50 Method::Put => "PUT",
51 Method::Delete => "DELETE",
52 Method::Options => "OPTIONS",
53 Method::Head => "HEAD",
54 _ => "OTHER",
55 }
56}
57
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API58/// A JSON response. Every body the API sends has its keys in `snake_case`;
59/// the contracts it passes through are `camelCase`, so they are converted
60/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
61/// the MCP protocol's own envelope keep the spelling their standards use.
62pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
63 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
64}
65
66/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
67/// workflow file, GitHub's contexts and event, and where to check out, all
68/// passed through as they are.
69const JOB_SPEC_AS_GIVEN: &[&str] = &[
70 "spec", "workflow", "github", "event", "contexts", "checkout",
71];
72
API and MCP server in Rust; a public index at the API root73/// An error in the shape every endpoint uses.
74fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API75 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root76}
77
78fn fail(code: FailureCode, message: &str) -> Result<Response> {
79 failure(&Failure {
80 code,
81 message: message.to_owned(),
82 })
83}
84
85/// A request body as JSON. An empty or malformed body is no input.
86async fn json_body(request: &mut Request) -> Value {
87 request.json().await.unwrap_or(Value::Null)
88}
89
90/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
91/// an anonymous viewer; a wrong one is refused, so that a typo does not
92/// silently look signed out.
93async fn authenticate(
94 request: &Request,
95 services: &Services,
96) -> Result<std::result::Result<Viewer, Response>> {
97 let header = request.headers().get("authorization")?.unwrap_or_default();
98 let token = match header.split_once(' ') {
99 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
100 token.trim()
101 }
102 _ => return Ok(Ok(None)),
103 };
104 let viewer: Viewer = g1t_kit::call(
105 &services.identity,
106 "user_for_access_token",
107 &TokenArgs {
108 token: token.to_owned(),
109 },
110 )
111 .await?;
112 if viewer.is_some() {
113 return Ok(Ok(viewer));
114 }
115 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
116 // Tells an MCP client where to sign in again.
117 response.headers_mut().set(
118 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'119 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root120 )?;
121 Ok(Err(response))
122}
123
124/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'125fn index(addresses: &addresses::Addresses) -> Value {
126 let api = &addresses.api;
127 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root128 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'129 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'130 "openapi_url": format!("{api}/openapi.json"),
131 "mcp_url": addresses.mcp,
132 "current_user_url": format!("{api}/user"),
133 "workspaces_url": format!("{api}/workspaces"),
134 "repositories_url": format!("{api}/repos{{?q}}"),
135 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root136 "repository_url": repo,
137 "repository_events_url": format!("{repo}/events{{?before}}"),
138 "labels_url": format!("{repo}/labels"),
139 "issues_url": format!("{repo}/issues{{?state,label}}"),
140 "issue_url": format!("{repo}/issues/{{number}}"),
141 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
142 "pulls_url": format!("{repo}/pulls{{?state}}"),
143 "pull_url": format!("{repo}/pulls/{{number}}"),
144 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts145 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root146 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'147 "device_code_url": format!("{api}/device/code"),
148 "device_token_url": format!("{api}/device/token"),
149 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
150 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
151 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read152 "context_url": format!("{repo}/context{{?reference}}"),
153 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'154 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root155 })
156}
157
158// Signing in from a tool. Accounts are created, and passwords typed, only
159// in a browser; a tool gets its token by having a person approve a code.
160
Integrations: your own model provider, alerts that open issues, tickets agents read161/// Passes a request from an outside system to its connection, as it came:
162/// its signature covers the exact bytes of the body.
163async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
164 let headers: std::collections::HashMap<String, String> = request
165 .headers()
166 .entries()
167 .map(|(name, value)| (name.to_lowercase(), value))
168 .collect();
169 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look170 // A push to GitHub with many commits makes a large payload.
171 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
172 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API173 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read174 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look175 // g1t's GitHub App has one webhook for every installation; it is
176 // checked against the app's own secret.
177 let (method, args) = if id == "github" {
178 ("github_receive", json!({ "headers": headers, "body": body }))
179 } else {
180 ("receive", json!({ "id": id, "headers": headers, "body": body }))
181 };
182 let received: g1t_contracts::integrations::Received =
183 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 API184 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read185}
186
Stripe webhooks, enterprise invoices, and sudo for both187async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
188 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
189 let payload = request.text().await.unwrap_or_default();
190 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 API191 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both192 }
193 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
194 &env.service("BILLING")?,
195 "stripe_webhook",
196 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
197 )
198 .await?;
199 // A refusal is a 400, so Stripe shows it as failed; anything handled,
200 // or already handled, is a 200, so Stripe stops sending it.
201 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API202 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both203 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API204 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both205 }
206 })
207}
208
API and MCP server in Rust; a public index at the API root209async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
210 let body = json_body(request).await;
211 let started: DeviceStart = g1t_kit::call(
212 &services.identity,
213 "device_start",
214 &DeviceStartArgs {
215 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
216 },
217 )
218 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API219 reply(&json!({
API and MCP server in Rust; a public index at the API root220 "device_code": started.device_code,
221 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'222 "verification_uri": format!("{}/device", services.addresses.site),
223 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root224 "expires_in": started.expires_in,
225 "interval": started.interval,
226 }))
227}
228
229async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
230 let body = json_body(request).await;
231 let claim: DeviceClaim = g1t_kit::call(
232 &services.identity,
233 "device_claim",
234 &DeviceClaimArgs {
235 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
236 },
237 )
238 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API239 reply(&match claim {
API and MCP server in Rust; a public index at the API root240 DeviceClaim::Approved { token, user } => json!({
241 "status": "approved",
242 "token": token,
243 "username": user.username,
244 "verified": user.verified,
245 }),
246 DeviceClaim::Pending => json!({ "status": "pending" }),
247 DeviceClaim::Denied => json!({ "status": "denied" }),
248 DeviceClaim::Expired => json!({ "status": "expired" }),
249 })
250}
251
Fast pages, required checks on the branch, self-hosted runners, honest incidents252/// A sandbox reporting on a run of an issue's commands, from before a pull
253/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts254/// The run's own token, in the body, is the credential: it was given to
255/// that sandbox and to nothing else.
256async fn report_checks(
257 request: &mut Request,
258 services: &Services,
259 run_id: &str,
260) -> Result<Response> {
261 let body = json_body(request).await;
262 let reported: Outcome<CheckRun> = g1t_kit::call(
263 &services.work,
264 "report_checks",
265 &ReportChecksArgs {
266 run_id: run_id.to_owned(),
267 token: body["token"].as_str().unwrap_or_default().to_owned(),
268 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
269 error: body["error"].as_str().map(str::to_owned),
270 skip: false,
271 },
272 )
273 .await?;
274 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API275 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts276 Outcome::Fail(refused) => failure(&refused),
277 }
278}
279
Agents as a team: lifecycle, merge queue, billing and a new shell280/// A sandbox reporting one tested state of a merge queue. As with checks,
281/// the entry's own token is the credential.
282async fn report_queue(
283 request: &mut Request,
284 services: &Services,
285 entry_id: &str,
286) -> Result<Response> {
287 let body = json_body(request).await;
288 let reported: Outcome<QueueState> = g1t_kit::call(
289 &services.work,
290 "report_queue",
291 &ReportQueueArgs {
292 entry_id: entry_id.to_owned(),
293 token: body["token"].as_str().unwrap_or_default().to_owned(),
294 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
295 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
296 error: body["error"].as_str().map(str::to_owned),
297 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains298 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell299 },
300 )
301 .await?;
302 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API303 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell304 Outcome::Fail(refused) => failure(&refused),
305 }
306}
307
Agents and memory, checks and conflicts, profiles, slug renames, custom domains308/// A sandbox reporting whether a pull request merges cleanly. As with
309/// checks, the probe's own token is the credential.
310async fn report_mergecheck(
311 request: &mut Request,
312 services: &Services,
313 pull_id: &str,
314) -> Result<Response> {
315 let body = json_body(request).await;
316 let reported: Outcome<Mergeable> = g1t_kit::call(
317 &services.work,
318 "report_mergecheck",
319 &ReportMergecheckArgs {
320 pull_id: pull_id.to_owned(),
321 token: body["token"].as_str().unwrap_or_default().to_owned(),
322 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
323 error: body["error"].as_str().map(str::to_owned),
324 },
325 )
326 .await?;
327 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API328 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains329 Outcome::Fail(refused) => failure(&refused),
330 }
331}
332
Merge branch 'worktree-agent-ac5b181a013e54348'333/// A backup's sandbox, passed on to the repos service, which holds the
334/// job (services/repos/src/backups.rs; the flow is in
335/// `g1t_contracts::backups`):
336///
337/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
338/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
339/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
340/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
341///
342/// Bodies are passed through as they are: snake_case already, and a
343/// bundle's refs are keyed by ref names, which must not be converted.
344async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
345 use g1t_contracts::backups::TOKEN_HEADER;
346 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
347 let rest = path.trim_start_matches("/backups/");
348 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
349 if job.is_empty() || token.is_empty() {
350 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
351 }
352 if method == "PUT" && action.starts_with("parts/") {
353 let bytes = request.bytes().await?;
354 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
355 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
356 }
357 let headers = worker::Headers::new();
358 headers.set(TOKEN_HEADER, &token)?;
359 let mut init = worker::RequestInit::new();
360 init.with_method(Method::Put)
361 .with_headers(headers)
362 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
363 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
364 let mut answered = services.repos.fetch_request(forwarded).await?;
365 return outcome_as_given(answered.json().await?);
366 }
367 let rpc = match (method, action) {
368 ("POST", "spec") => "backup_spec",
369 ("POST", "complete") => "backup_complete",
370 ("POST", "fail") => "backup_fail",
371 _ => return fail(FailureCode::NotFound, "No such endpoint."),
372 };
373 let mut body = json_body(request).await;
374 if !body.is_object() {
375 body = json!({});
376 }
377 body["job_id"] = json!(job);
378 body["token"] = json!(token);
379 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
380 outcome_as_given(answered)
381}
382
383/// An `Outcome` from a service whose keys are already the API's: the value,
384/// or the failure in the shape every endpoint uses.
385fn outcome_as_given(answered: Value) -> Result<Response> {
386 match serde_json::from_value::<Outcome<Value>>(answered)? {
387 Outcome::Ok(value) => Response::from_json(&value),
388 Outcome::Fail(refused) => failure(&refused),
389 }
390}
391
Agents as a team: lifecycle, merge queue, billing and a new shell392/// A sandbox reporting the review its agent wrote. As with checks, the
393/// run's own token is the credential.
394async fn report_review(
395 request: &mut Request,
396 services: &Services,
397 run_id: &str,
398) -> Result<Response> {
399 let body = json_body(request).await;
400 let reported: Outcome<bool> = g1t_kit::call(
401 &services.work,
402 "report_review",
403 &ReportReviewArgs {
404 run_id: run_id.to_owned(),
405 token: body["token"].as_str().unwrap_or_default().to_owned(),
406 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
407 body: body["body"].as_str().unwrap_or_default().to_owned(),
408 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
409 model: body["model"].as_str().map(str::to_owned),
410 error: body["error"].as_str().map(str::to_owned),
411 },
412 )
413 .await?;
414 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API415 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell416 Outcome::Fail(refused) => failure(&refused),
417 }
418}
419
420/// A sandbox reporting the plan its agent wrote. As with checks, the
421/// plan's own token is the credential.
422async fn report_plan(
423 request: &mut Request,
424 services: &Services,
425 plan_id: &str,
426) -> Result<Response> {
427 let body = json_body(request).await;
428 let reported: Outcome<bool> = g1t_kit::call(
429 &services.work,
430 "report_plan",
431 &ReportPlanArgs {
432 plan_id: plan_id.to_owned(),
433 token: body["token"].as_str().unwrap_or_default().to_owned(),
434 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
435 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
436 error: body["error"].as_str().map(str::to_owned),
437 },
438 )
439 .await?;
440 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API441 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell442 Outcome::Fail(refused) => failure(&refused),
443 }
444}
445
446/// A sandbox reporting what its agent's run cost, so that the workspace
447/// it worked for is charged. As with checks, the run's own token is the
448/// credential.
449async fn report_usage(
450 request: &mut Request,
451 services: &Services,
452 run_id: &str,
453) -> Result<Response> {
454 let body = json_body(request).await;
455 let charged: Outcome<bool> = g1t_kit::call(
456 &services.billing,
457 "finish_run",
458 &FinishRunArgs {
459 run_id: run_id.to_owned(),
460 token: body["token"].as_str().unwrap_or_default().to_owned(),
461 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
462 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'463 // What the harness counted; the agent rate is charged on no
464 // fewer, on a workspace's own model key too.
465 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
466 input: t["input"].as_u64().unwrap_or_default(),
467 output: t["output"].as_u64().unwrap_or_default(),
468 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
469 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
470 }),
Agents as a team: lifecycle, merge queue, billing and a new shell471 },
472 )
473 .await?;
474 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API475 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell476 Outcome::Fail(refused) => failure(&refused),
477 }
478}
479
API and MCP server in Rust; a public index at the API root480async fn respond(mut request: Request, env: &Env) -> Result<Response> {
481 let method = method_name(request.method());
482 if method == "OPTIONS" {
483 return Ok(Response::empty()?.with_status(204));
484 }
485 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell486 // Paths carry no version. An earlier form began with `/v1`, which is
487 // still accepted so that nothing already written against it breaks.
488 let path = match url.path().strip_prefix("/v1") {
489 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
490 _ => url.path().to_owned(),
491 };
492 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'493 // MCP is a host of its own hosted, and may be a path on this one
494 // self-hosted (addresses.rs).
495 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root496
Stripe webhooks, enterprise invoices, and sudo for both497 // Stripe reporting to billing. Signed with the secret of the endpoint
498 // billing registered; the body goes through exactly as received, since
499 // the signature covers its bytes.
500 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
501 return receive_stripe(&mut request, env).await;
502 }
503
Integrations: your own model provider, alerts that open issues, tickets agents read504 // Outside systems reporting to a connection. They sign what they send
505 // with the connection's own secret, which is not a g1t token, so this
506 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide507 if method == "POST" && !on_mcp
508 && 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 read509 return receive_hook(&mut request, &services, id).await;
510 }
511
Deployments: a preview for every pull request, production on g1t.page512 // A sandbox building a deployment, reporting with its build's token,
513 // which is not a g1t token. The body goes through as it is: it can
514 // carry a Worker's bundled code.
515 if method == "POST" && !on_mcp
516 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
517 {
518 let target = format!("https://deployments/jobs/{rest}");
519 let body = request.bytes().await?;
520 let headers = worker::Headers::new();
521 headers.set("content-type", "application/json")?;
522 let mut init = worker::RequestInit::new();
523 init.with_method(Method::Post)
524 .with_headers(headers)
525 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run526 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page527 .service("DEPLOYMENTS")?
528 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run529 .await?;
530 // A fresh response: a fetched one's headers cannot be changed, and
531 // every response gets the API's own on the way out.
532 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API533 let bytes = answer.bytes().await?;
534 let bytes = match serde_json::from_slice::<Value>(&bytes) {
535 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
536 Err(_) => bytes,
537 };
538 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run539 .with_status(status)
540 .with_headers({
541 let headers = worker::Headers::new();
542 headers.set("content-type", "application/json")?;
543 headers
544 }));
Deployments: a preview for every pull request, production on g1t.page545 }
546
A repository has its own sidebar, as settings do547 // A sandbox's artifacts and cache, with its job's token, which is not a
548 // g1t token either.
549 if !on_mcp
550 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents551 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do552 {
553 let rest = rest.to_owned();
554 return blobs::for_job(request, env, &services, method, &rest).await;
555 }
556
Fast pages, required checks on the branch, self-hosted runners, honest incidents557 // A self-hosted runner, with a registration token or its own
558 // credential, neither of which is a g1t access token.
559 if method == "POST"
560 && !on_mcp
561 && path.starts_with("/runners/")
562 && let Some(response) = runners::handle(&mut request, &services, &path).await?
563 {
564 return Ok(response);
565 }
566
API and MCP server in Rust; a public index at the API root567 let viewer = match authenticate(&request, &services).await? {
568 Ok(viewer) => viewer,
569 Err(refused) => return Ok(refused),
570 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API571 services.audit = audit::AuditContext::of(&request, on_mcp);
572 // An agent's token: what it may do comes with it, on the composite
573 // identity identity resolved it to.
574 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
575 services.scope = Some(acting.scope.clone());
576 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell577 let header = request.headers().get("authorization")?.unwrap_or_default();
578 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
579 let scope: Option<AgentScope> = g1t_kit::call(
580 &services.identity,
581 "agent_scope",
582 &TokenArgs {
583 token: token.to_owned(),
584 },
585 )
586 .await?;
587 // A scope is what lets an agent's token do anything at all.
588 let Some(scope) = scope else {
589 return fail(FailureCode::Unauthenticated, "Invalid access token.");
590 };
591 services.scope = Some(scope);
592 }
API and MCP server in Rust; a public index at the API root593 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
594 return Ok(response);
595 }
596 if on_mcp {
597 return mcp::handle(request, &services, &viewer).await;
598 }
599
600 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'601 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root602 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do603 // A run's artifacts: listed, or one downloaded.
604 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
605 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
606 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
607 return match rest {
608 [] => {
609 let seen: Outcome<Value> = g1t_kit::call(
610 &services.actions,
611 "run",
612 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
613 )
614 .await?;
615 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API616 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do617 Outcome::Fail(refused) => failure(&refused),
618 }
619 }
620 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
621 _ => fail(FailureCode::NotFound, "No such endpoint."),
622 };
623 }
624 }
Agents as a team: lifecycle, merge queue, billing and a new shell625 ("POST", "/device/code") => return device_code(&mut request, &services).await,
626 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically627 // Where a pull request lives, for a tool that knows only its fork.
628 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
629 let located: Outcome<Value> = g1t_kit::call(
630 &services.work,
631 "locate_pull",
632 &json!({ "id": &path[7..], "viewer": viewer }),
633 )
634 .await?;
635 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API636 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically637 Outcome::Fail(refused) => failure(&refused),
638 };
639 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains640 ("POST", path) if path.starts_with("/mergechecks/") => {
641 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
642 return report_mergecheck(&mut request, &services, &pull_id).await;
643 }
Merge branch 'worktree-agent-ac5b181a013e54348'644 // A sandbox making a repository's nightly backup. The job's own
645 // token, in its header, is the credential.
646 (method, path) if path.starts_with("/backups/") => {
647 return backup_job(&mut request, &services, method, path).await;
648 }
Agents as a team: lifecycle, merge queue, billing and a new shell649 ("POST", path) if path.starts_with("/queue/") => {
650 let entry_id = path.trim_start_matches("/queue/").to_owned();
651 return report_queue(&mut request, &services, &entry_id).await;
652 }
GitHub Actions on g1t, part two: running workflows653 // A sandbox running a GitHub Actions job: fetching the job, and
654 // reporting how it goes. The job's own token is the credential.
655 ("POST", path) if path.starts_with("/actions/jobs/") => {
656 let rest = path.trim_start_matches("/actions/jobs/");
657 let (job, method) = match rest.strip_suffix("/spec") {
658 Some(job) => (job.to_owned(), "job_spec"),
659 None => (rest.to_owned(), "job_report"),
660 };
661 let body = json_body(&mut request).await;
662 let answered: Outcome<Value> = g1t_kit::call(
663 &services.actions,
664 method,
665 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
666 )
667 .await?;
668 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API669 // A job's spec is the workflow and its contexts as GitHub
670 // has them; only g1t's own keys around them are converted.
671 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows672 Outcome::Fail(refused) => failure(&refused),
673 };
674 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains675 // A sandbox reporting its agent run's steps, cost and end. As with
676 // checks, the run's own token, in the body, is the credential.
677 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
678 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
679 let mut body = json_body(&mut request).await;
680 if !body.is_object() {
681 body = json!({});
682 }
683 body["runId"] = json!(run_id);
684 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
685 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API686 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains687 Outcome::Fail(refused) => failure(&refused),
688 };
689 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API690 // What a run's agent learned, as memory candidates; the same token.
691 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
692 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
693 let body = json_body(&mut request).await;
694 let learned = json!({
695 "runId": run_id,
696 "token": body["token"].as_str().unwrap_or_default(),
697 "items": body["items"].as_array().cloned().unwrap_or_default(),
698 });
699 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
700 return match captured {
701 Outcome::Ok(captured) => reply(&captured),
702 Outcome::Fail(refused) => failure(&refused),
703 };
704 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step705 // How sure a run's agent is of its change; the same token.
706 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
707 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
708 let body = json_body(&mut request).await;
709 let said = json!({
710 "runId": run_id,
711 "token": body["token"].as_str().unwrap_or_default(),
712 "confidence": body["confidence"].as_str().unwrap_or_default(),
713 "uncertainAbout": body["uncertain_about"]
714 .as_array()
715 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
716 .unwrap_or_default(),
717 });
718 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
719 return match recorded {
720 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
721 Outcome::Fail(refused) => failure(&refused),
722 };
723 }
Agents as a team: lifecycle, merge queue, billing and a new shell724 ("POST", path) if path.starts_with("/checks/") => {
725 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts726 return report_checks(&mut request, &services, &run_id).await;
727 }
Agents as a team: lifecycle, merge queue, billing and a new shell728 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
729 let run_id = path
730 .trim_start_matches("/runs/")
731 .trim_end_matches("/usage")
732 .to_owned();
733 return report_usage(&mut request, &services, &run_id).await;
734 }
735 ("POST", path) if path.starts_with("/plans/") => {
736 let plan_id = path.trim_start_matches("/plans/").to_owned();
737 return report_plan(&mut request, &services, &plan_id).await;
738 }
739 ("POST", path) if path.starts_with("/reviews/") => {
740 let run_id = path.trim_start_matches("/reviews/").to_owned();
741 return report_review(&mut request, &services, &run_id).await;
742 }
API and MCP server in Rust; a public index at the API root743 _ => {}
744 }
745
746 let query: Vec<(String, String)> = url
747 .query_pairs()
748 .map(|(name, value)| (name.into_owned(), value.into_owned()))
749 .collect();
750 let body = if method == "GET" {
751 Value::Null
752 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell753 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root754 };
755 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
756 return fail(FailureCode::NotFound, "No such endpoint.");
757 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API758 match audit::run(route.op, &services, &viewer, &input).await? {
759 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 step760 // A token without the scope a call needs is told which one.
761 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
762 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
763 "error": {
764 "code": refused.code,
765 "message": refused.message,
766 "needed_scope": scope.as_str(),
767 }
768 }))?
769 .with_status(403)),
770 _ => failure(&refused),
771 },
API and MCP server in Rust; a public index at the API root772 }
773}
774
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API775/// Request bodies take the same keys as the MCP tools, `snake_case`, as
776/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell777fn snake_case_keys(body: Value) -> Value {
778 let Value::Object(fields) = body else {
779 return body;
780 };
781 let mut out = serde_json::Map::new();
782 for (key, value) in fields {
783 let mut snake = String::with_capacity(key.len() + 4);
784 for c in key.chars() {
785 if c.is_ascii_uppercase() {
786 snake.push('_');
787 snake.push(c.to_ascii_lowercase());
788 } else {
789 snake.push(c);
790 }
791 }
792 // A key given in both spellings keeps the snake_case one.
793 if snake != key && out.contains_key(&snake) {
794 continue;
795 }
796 out.insert(snake, value);
797 }
798 Value::Object(out)
799}
800
801#[cfg(test)]
802mod tests {
803 use super::snake_case_keys;
804 use serde_json::json;
805
806 #[test]
807 fn camel_case_keys_are_accepted() {
808 assert_eq!(
809 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
810 json!({ "count_agent_approvals": false, "title": "x" })
811 );
812 }
813
814 #[test]
815 fn snake_case_wins_when_both_are_given() {
816 assert_eq!(
817 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
818 json!({ "keep_issue_open": true })
819 );
820 }
821}
822
API and MCP server in Rust; a public index at the API root823// The API is called from browsers too: the reference's explorer, and apps
824// built on g1t. It carries no cookies, so any origin may call it.
825#[event(fetch)]
826async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
827 let mut response = respond(request, &env).await?;
828 let headers = response.headers_mut();
829 headers.set("access-control-allow-origin", "*")?;
830 headers.set(
831 "access-control-allow-headers",
832 "authorization, content-type",
833 )?;
834 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
835 headers.set("access-control-expose-headers", "www-authenticate")?;
836 Ok(response)
837}

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