Skip to content
903 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 'main' into worktree-agent-a69aeabc4b0deeb977mod about;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R28mod artifacts;
Merge branch 'worktree-agent-aaf03bdceac799c89'9mod addresses;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily10mod alerts;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API11mod audit;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit12mod billing;
A repository has its own sidebar, as settings do13mod blobs;
Merge checks: statuses and check runs on every commit14mod checks;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9715mod deployments;
API and MCP server in Rust; a public index at the API root16mod mcp;
API: notifications over REST and MCP, with notifications scopes17mod notifications;
API and MCP server in Rust; a public index at the API root18mod oauth;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R219mod oidc;
API and MCP server in Rust; a public index at the API root20mod openapi;
API: pinned projects over REST and MCP21mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9722mod projects;
Merge branch 'worktree-agent-a3abfcce648e87dca'23mod protection;
API and MCP server in Rust; a public index at the API root24mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains25mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API26#[cfg(test)]
27mod responses;
API and MCP server in Rust; a public index at the API root28mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge29mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents30mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar31mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step32mod tools;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R233mod toolkit;
API and MCP server in Rust; a public index at the API root34
Merge branch 'model-routing'35use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root36use g1t_contracts::identity::{
37 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
38};
Agents as a team: lifecycle, merge queue, billing and a new shell39use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains40 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
41 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell42};
43use g1t_contracts::identity::AgentScope;
44use 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 API45use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root46use serde_json::{Value, json};
47use worker::{Context, Env, Method, Request, Response, Result, event};
48
49use operations::Services;
50
51fn method_name(method: Method) -> &'static str {
52 match method {
53 Method::Get => "GET",
54 Method::Post => "POST",
55 Method::Patch => "PATCH",
56 Method::Put => "PUT",
57 Method::Delete => "DELETE",
58 Method::Options => "OPTIONS",
59 Method::Head => "HEAD",
60 _ => "OTHER",
61 }
62}
63
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API64/// A JSON response. Every body the API sends has its keys in `snake_case`;
65/// the contracts it passes through are `camelCase`, so they are converted
66/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
67/// the MCP protocol's own envelope keep the spelling their standards use.
68pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
69 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
70}
71
72/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
73/// workflow file, GitHub's contexts and event, and where to check out, all
74/// passed through as they are.
75const JOB_SPEC_AS_GIVEN: &[&str] = &[
Merge branch 'worktree-agent-a3abfcce648e87dca'76 "spec", "workflow", "github", "event", "contexts", "checkout", "permissions",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API77];
78
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R279/// Puts the toolkit's variables in a job's spec: its runtime token, where
80/// the toolkit's services are, and where to ask for an OIDC token when the
81/// job may have one and this installation issues them. The `runtime` the
82/// actions service sent goes no further.
83fn with_runtime(spec: &mut Value, api: &str, oidc: bool) {
84 let Some(runtime) = spec.as_object_mut().and_then(|s| s.remove("runtime")) else { return };
85 let Some(token) = runtime["token"].as_str().filter(|t| !t.is_empty()) else { return };
86 let id_token = oidc && runtime["id_token"].as_bool() == Some(true);
87 let vars = toolkit::runtime_variables(api, token, id_token);
88 if let Some(variables) = spec.get_mut("variables").and_then(Value::as_object_mut) {
89 variables.extend(vars);
90 }
91}
92
API and MCP server in Rust; a public index at the API root93/// An error in the shape every endpoint uses.
94fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API95 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root96}
97
98fn fail(code: FailureCode, message: &str) -> Result<Response> {
99 failure(&Failure {
100 code,
101 message: message.to_owned(),
102 })
103}
104
105/// A request body as JSON. An empty or malformed body is no input.
106async fn json_body(request: &mut Request) -> Value {
107 request.json().await.unwrap_or(Value::Null)
108}
109
110/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
111/// an anonymous viewer; a wrong one is refused, so that a typo does not
112/// silently look signed out.
113async fn authenticate(
114 request: &Request,
115 services: &Services,
116) -> Result<std::result::Result<Viewer, Response>> {
117 let header = request.headers().get("authorization")?.unwrap_or_default();
118 let token = match header.split_once(' ') {
119 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
120 token.trim()
121 }
122 _ => return Ok(Ok(None)),
123 };
124 let viewer: Viewer = g1t_kit::call(
125 &services.identity,
126 "user_for_access_token",
127 &TokenArgs {
128 token: token.to_owned(),
129 },
130 )
131 .await?;
132 if viewer.is_some() {
133 return Ok(Ok(viewer));
134 }
135 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
136 // Tells an MCP client where to sign in again.
137 response.headers_mut().set(
138 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'139 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root140 )?;
141 Ok(Err(response))
142}
143
144/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'145fn index(addresses: &addresses::Addresses) -> Value {
146 let api = &addresses.api;
147 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root148 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'149 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'150 "openapi_url": format!("{api}/openapi.json"),
151 "mcp_url": addresses.mcp,
152 "current_user_url": format!("{api}/user"),
153 "workspaces_url": format!("{api}/workspaces"),
154 "repositories_url": format!("{api}/repos{{?q}}"),
155 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root156 "repository_url": repo,
157 "repository_events_url": format!("{repo}/events{{?before}}"),
158 "labels_url": format!("{repo}/labels"),
159 "issues_url": format!("{repo}/issues{{?state,label}}"),
160 "issue_url": format!("{repo}/issues/{{number}}"),
161 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
162 "pulls_url": format!("{repo}/pulls{{?state}}"),
163 "pull_url": format!("{repo}/pulls/{{number}}"),
164 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts165 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root166 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'167 "device_code_url": format!("{api}/device/code"),
168 "device_token_url": format!("{api}/device/token"),
169 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
170 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
171 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read172 "context_url": format!("{repo}/context{{?reference}}"),
173 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'174 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root175 })
176}
177
178// Signing in from a tool. Accounts are created, and passwords typed, only
179// in a browser; a tool gets its token by having a person approve a code.
180
Integrations: your own model provider, alerts that open issues, tickets agents read181/// Passes a request from an outside system to its connection, as it came:
182/// its signature covers the exact bytes of the body.
183async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
184 let headers: std::collections::HashMap<String, String> = request
185 .headers()
186 .entries()
187 .map(|(name, value)| (name.to_lowercase(), value))
188 .collect();
189 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look190 // A push to GitHub with many commits makes a large payload.
191 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
192 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API193 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read194 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look195 // g1t's GitHub App has one webhook for every installation; it is
196 // checked against the app's own secret.
197 let (method, args) = if id == "github" {
198 ("github_receive", json!({ "headers": headers, "body": body }))
199 } else {
200 ("receive", json!({ "id": id, "headers": headers, "body": body }))
201 };
202 let received: g1t_contracts::integrations::Received =
203 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 API204 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read205}
206
Stripe webhooks, enterprise invoices, and sudo for both207async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
208 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
209 let payload = request.text().await.unwrap_or_default();
210 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 API211 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both212 }
213 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
214 &env.service("BILLING")?,
215 "stripe_webhook",
216 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
217 )
218 .await?;
219 // A refusal is a 400, so Stripe shows it as failed; anything handled,
220 // or already handled, is a 200, so Stripe stops sending it.
221 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API222 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both223 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API224 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both225 }
226 })
227}
228
API and MCP server in Rust; a public index at the API root229async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
230 let body = json_body(request).await;
231 let started: DeviceStart = g1t_kit::call(
232 &services.identity,
233 "device_start",
234 &DeviceStartArgs {
235 client_name: body["client_name"].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(&json!({
API and MCP server in Rust; a public index at the API root240 "device_code": started.device_code,
241 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'242 "verification_uri": format!("{}/device", services.addresses.site),
243 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root244 "expires_in": started.expires_in,
245 "interval": started.interval,
246 }))
247}
248
249async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
250 let body = json_body(request).await;
251 let claim: DeviceClaim = g1t_kit::call(
252 &services.identity,
253 "device_claim",
254 &DeviceClaimArgs {
255 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
256 },
257 )
258 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API259 reply(&match claim {
API and MCP server in Rust; a public index at the API root260 DeviceClaim::Approved { token, user } => json!({
261 "status": "approved",
262 "token": token,
263 "username": user.username,
264 "verified": user.verified,
265 }),
266 DeviceClaim::Pending => json!({ "status": "pending" }),
267 DeviceClaim::Denied => json!({ "status": "denied" }),
268 DeviceClaim::Expired => json!({ "status": "expired" }),
269 })
270}
271
Fast pages, required checks on the branch, self-hosted runners, honest incidents272/// A sandbox reporting on a run of an issue's commands, from before a pull
273/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts274/// The run's own token, in the body, is the credential: it was given to
275/// that sandbox and to nothing else.
276async fn report_checks(
277 request: &mut Request,
278 services: &Services,
279 run_id: &str,
280) -> Result<Response> {
281 let body = json_body(request).await;
282 let reported: Outcome<CheckRun> = g1t_kit::call(
283 &services.work,
284 "report_checks",
285 &ReportChecksArgs {
286 run_id: run_id.to_owned(),
287 token: body["token"].as_str().unwrap_or_default().to_owned(),
288 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
289 error: body["error"].as_str().map(str::to_owned),
290 skip: false,
291 },
292 )
293 .await?;
294 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API295 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts296 Outcome::Fail(refused) => failure(&refused),
297 }
298}
299
Agents as a team: lifecycle, merge queue, billing and a new shell300/// A sandbox reporting one tested state of a merge queue. As with checks,
301/// the entry's own token is the credential.
302async fn report_queue(
303 request: &mut Request,
304 services: &Services,
305 entry_id: &str,
306) -> Result<Response> {
307 let body = json_body(request).await;
308 let reported: Outcome<QueueState> = g1t_kit::call(
309 &services.work,
310 "report_queue",
311 &ReportQueueArgs {
312 entry_id: entry_id.to_owned(),
313 token: body["token"].as_str().unwrap_or_default().to_owned(),
314 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
315 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
316 error: body["error"].as_str().map(str::to_owned),
317 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains318 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell319 },
320 )
321 .await?;
322 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API323 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell324 Outcome::Fail(refused) => failure(&refused),
325 }
326}
327
Agents and memory, checks and conflicts, profiles, slug renames, custom domains328/// A sandbox reporting whether a pull request merges cleanly. As with
329/// checks, the probe's own token is the credential.
330async fn report_mergecheck(
331 request: &mut Request,
332 services: &Services,
333 pull_id: &str,
334) -> Result<Response> {
335 let body = json_body(request).await;
336 let reported: Outcome<Mergeable> = g1t_kit::call(
337 &services.work,
338 "report_mergecheck",
339 &ReportMergecheckArgs {
340 pull_id: pull_id.to_owned(),
341 token: body["token"].as_str().unwrap_or_default().to_owned(),
342 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
343 error: body["error"].as_str().map(str::to_owned),
344 },
345 )
346 .await?;
347 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API348 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains349 Outcome::Fail(refused) => failure(&refused),
350 }
351}
352
Merge branch 'worktree-agent-ac5b181a013e54348'353/// A backup's sandbox, passed on to the repos service, which holds the
354/// job (services/repos/src/backups.rs; the flow is in
355/// `g1t_contracts::backups`):
356///
357/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
358/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
359/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
360/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
361///
362/// Bodies are passed through as they are: snake_case already, and a
363/// bundle's refs are keyed by ref names, which must not be converted.
364async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
365 use g1t_contracts::backups::TOKEN_HEADER;
366 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
367 let rest = path.trim_start_matches("/backups/");
368 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
369 if job.is_empty() || token.is_empty() {
370 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
371 }
372 if method == "PUT" && action.starts_with("parts/") {
373 let bytes = request.bytes().await?;
374 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
375 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
376 }
377 let headers = worker::Headers::new();
378 headers.set(TOKEN_HEADER, &token)?;
379 let mut init = worker::RequestInit::new();
380 init.with_method(Method::Put)
381 .with_headers(headers)
382 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
383 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
384 let mut answered = services.repos.fetch_request(forwarded).await?;
385 return outcome_as_given(answered.json().await?);
386 }
387 let rpc = match (method, action) {
388 ("POST", "spec") => "backup_spec",
389 ("POST", "complete") => "backup_complete",
390 ("POST", "fail") => "backup_fail",
391 _ => return fail(FailureCode::NotFound, "No such endpoint."),
392 };
393 let mut body = json_body(request).await;
394 if !body.is_object() {
395 body = json!({});
396 }
397 body["job_id"] = json!(job);
398 body["token"] = json!(token);
399 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
400 outcome_as_given(answered)
401}
402
403/// An `Outcome` from a service whose keys are already the API's: the value,
404/// or the failure in the shape every endpoint uses.
405fn outcome_as_given(answered: Value) -> Result<Response> {
406 match serde_json::from_value::<Outcome<Value>>(answered)? {
407 Outcome::Ok(value) => Response::from_json(&value),
408 Outcome::Fail(refused) => failure(&refused),
409 }
410}
411
Agents as a team: lifecycle, merge queue, billing and a new shell412/// A sandbox reporting the review its agent wrote. As with checks, the
413/// run's own token is the credential.
414async fn report_review(
415 request: &mut Request,
416 services: &Services,
417 run_id: &str,
418) -> Result<Response> {
419 let body = json_body(request).await;
420 let reported: Outcome<bool> = g1t_kit::call(
421 &services.work,
422 "report_review",
423 &ReportReviewArgs {
424 run_id: run_id.to_owned(),
425 token: body["token"].as_str().unwrap_or_default().to_owned(),
426 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
427 body: body["body"].as_str().unwrap_or_default().to_owned(),
428 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
429 model: body["model"].as_str().map(str::to_owned),
430 error: body["error"].as_str().map(str::to_owned),
431 },
432 )
433 .await?;
434 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API435 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell436 Outcome::Fail(refused) => failure(&refused),
437 }
438}
439
440/// A sandbox reporting the plan its agent wrote. As with checks, the
441/// plan's own token is the credential.
442async fn report_plan(
443 request: &mut Request,
444 services: &Services,
445 plan_id: &str,
446) -> Result<Response> {
447 let body = json_body(request).await;
448 let reported: Outcome<bool> = g1t_kit::call(
449 &services.work,
450 "report_plan",
451 &ReportPlanArgs {
452 plan_id: plan_id.to_owned(),
453 token: body["token"].as_str().unwrap_or_default().to_owned(),
454 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
455 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
456 error: body["error"].as_str().map(str::to_owned),
457 },
458 )
459 .await?;
460 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API461 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell462 Outcome::Fail(refused) => failure(&refused),
463 }
464}
465
466/// A sandbox reporting what its agent's run cost, so that the workspace
467/// it worked for is charged. As with checks, the run's own token is the
468/// credential.
469async fn report_usage(
470 request: &mut Request,
471 services: &Services,
472 run_id: &str,
473) -> Result<Response> {
474 let body = json_body(request).await;
475 let charged: Outcome<bool> = g1t_kit::call(
476 &services.billing,
477 "finish_run",
478 &FinishRunArgs {
479 run_id: run_id.to_owned(),
480 token: body["token"].as_str().unwrap_or_default().to_owned(),
481 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
482 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'483 // What the harness counted; the agent rate is charged on no
484 // fewer, on a workspace's own model key too.
485 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
486 input: t["input"].as_u64().unwrap_or_default(),
487 output: t["output"].as_u64().unwrap_or_default(),
488 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
489 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
490 }),
Agents as a team: lifecycle, merge queue, billing and a new shell491 },
492 )
493 .await?;
494 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API495 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell496 Outcome::Fail(refused) => failure(&refused),
497 }
498}
499
API and MCP server in Rust; a public index at the API root500async fn respond(mut request: Request, env: &Env) -> Result<Response> {
501 let method = method_name(request.method());
502 if method == "OPTIONS" {
503 return Ok(Response::empty()?.with_status(204));
504 }
505 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell506 // Paths carry no version. An earlier form began with `/v1`, which is
507 // still accepted so that nothing already written against it breaks.
508 let path = match url.path().strip_prefix("/v1") {
509 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
510 _ => url.path().to_owned(),
511 };
512 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'513 // MCP is a host of its own hosted, and may be a path on this one
514 // self-hosted (addresses.rs).
515 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root516
Stripe webhooks, enterprise invoices, and sudo for both517 // Stripe reporting to billing. Signed with the secret of the endpoint
518 // billing registered; the body goes through exactly as received, since
519 // the signature covers its bytes.
520 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
521 return receive_stripe(&mut request, env).await;
522 }
523
Integrations: your own model provider, alerts that open issues, tickets agents read524 // Outside systems reporting to a connection. They sign what they send
525 // with the connection's own secret, which is not a g1t token, so this
526 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide527 if method == "POST" && !on_mcp
528 && 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 read529 return receive_hook(&mut request, &services, id).await;
530 }
531
Deployments: a preview for every pull request, production on g1t.page532 // A sandbox building a deployment, reporting with its build's token,
533 // which is not a g1t token. The body goes through as it is: it can
534 // carry a Worker's bundled code.
535 if method == "POST" && !on_mcp
536 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
537 {
538 let target = format!("https://deployments/jobs/{rest}");
539 let body = request.bytes().await?;
540 let headers = worker::Headers::new();
541 headers.set("content-type", "application/json")?;
542 let mut init = worker::RequestInit::new();
543 init.with_method(Method::Post)
544 .with_headers(headers)
545 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run546 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page547 .service("DEPLOYMENTS")?
548 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run549 .await?;
550 // A fresh response: a fetched one's headers cannot be changed, and
551 // every response gets the API's own on the way out.
552 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API553 let bytes = answer.bytes().await?;
554 let bytes = match serde_json::from_slice::<Value>(&bytes) {
555 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
556 Err(_) => bytes,
557 };
558 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run559 .with_status(status)
560 .with_headers({
561 let headers = worker::Headers::new();
562 headers.set("content-type", "application/json")?;
563 headers
564 }));
Deployments: a preview for every pull request, production on g1t.page565 }
566
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2567 // The services GitHub's toolkit calls from inside a job, with its
568 // runtime token, and the links they hand out (toolkit.rs).
569 if !on_mcp && method == "POST"
570 && let Some(rest) = path.strip_prefix("/twirp/")
571 {
572 let (service, rpc) = rest.split_once('/').unwrap_or((rest, ""));
573 let (service, rpc) = (service.to_owned(), rpc.to_owned());
574 return toolkit::twirp(request, env, &services, &service, &rpc).await;
575 }
576 if !on_mcp && let Some(rest) = path.strip_prefix("/actions/toolkit/_apis/artifactcache/") {
577 let rest = rest.to_owned();
578 return toolkit::cache_v1(request, env, &services, method, &rest).await;
579 }
580 if !on_mcp && let Some(token) = path.strip_prefix("/actions/toolkit/blobs/") {
581 let token = token.to_owned();
582 return toolkit::blob(request, env, &services, method, &token).await;
583 }
584 // g1t as an OIDC issuer for workflow jobs (oidc.rs).
585 if !on_mcp && method == "GET" && path.starts_with("/actions/oidc/") {
586 return oidc::handle(&request, env, &services, &path).await;
587 }
588
A repository has its own sidebar, as settings do589 // A sandbox's artifacts and cache, with its job's token, which is not a
590 // g1t token either.
591 if !on_mcp
592 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents593 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do594 {
595 let rest = rest.to_owned();
596 return blobs::for_job(request, env, &services, method, &rest).await;
597 }
598
Fast pages, required checks on the branch, self-hosted runners, honest incidents599 // A self-hosted runner, with a registration token or its own
600 // credential, neither of which is a g1t access token.
601 if method == "POST"
602 && !on_mcp
603 && path.starts_with("/runners/")
604 && let Some(response) = runners::handle(&mut request, &services, &path).await?
605 {
606 return Ok(response);
607 }
608
API and MCP server in Rust; a public index at the API root609 let viewer = match authenticate(&request, &services).await? {
610 Ok(viewer) => viewer,
611 Err(refused) => return Ok(refused),
612 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API613 services.audit = audit::AuditContext::of(&request, on_mcp);
614 // An agent's token: what it may do comes with it, on the composite
615 // identity identity resolved it to.
616 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
617 services.scope = Some(acting.scope.clone());
618 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell619 let header = request.headers().get("authorization")?.unwrap_or_default();
620 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
621 let scope: Option<AgentScope> = g1t_kit::call(
622 &services.identity,
623 "agent_scope",
624 &TokenArgs {
625 token: token.to_owned(),
626 },
627 )
628 .await?;
629 // A scope is what lets an agent's token do anything at all.
630 let Some(scope) = scope else {
631 return fail(FailureCode::Unauthenticated, "Invalid access token.");
632 };
633 services.scope = Some(scope);
634 }
API and MCP server in Rust; a public index at the API root635 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
636 return Ok(response);
637 }
638 if on_mcp {
639 return mcp::handle(request, &services, &viewer).await;
640 }
641
642 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'643 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root644 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2645 // One of a run's artifacts downloaded by name (the run's artifacts
646 // are listed by the REST route in rest.rs).
647 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts/") => {
A repository has its own sidebar, as settings do648 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2649 if let [owner, repo, "actions", "runs", run, "artifacts", name] = parts.as_slice() {
Merge branch 'worktree-agent-a3abfcce648e87dca'650 // A workflow job's token reaches its own repository only.
651 if viewer
652 .as_ref()
653 .and_then(|user| user.token.as_deref())
654 .is_some_and(|token| !token.reaches(&format!("{owner}/{repo}")))
655 {
656 return fail(FailureCode::NotFound, "No such run.");
657 }
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2658 return blobs::download(env, &services, &viewer, owner, repo, run, name).await;
A repository has its own sidebar, as settings do659 }
660 }
Agents as a team: lifecycle, merge queue, billing and a new shell661 ("POST", "/device/code") => return device_code(&mut request, &services).await,
662 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically663 // Where a pull request lives, for a tool that knows only its fork.
664 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
665 let located: Outcome<Value> = g1t_kit::call(
666 &services.work,
667 "locate_pull",
668 &json!({ "id": &path[7..], "viewer": viewer }),
669 )
670 .await?;
671 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API672 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically673 Outcome::Fail(refused) => failure(&refused),
674 };
675 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains676 ("POST", path) if path.starts_with("/mergechecks/") => {
677 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
678 return report_mergecheck(&mut request, &services, &pull_id).await;
679 }
Merge branch 'worktree-agent-ac5b181a013e54348'680 // A sandbox making a repository's nightly backup. The job's own
681 // token, in its header, is the credential.
682 (method, path) if path.starts_with("/backups/") => {
683 return backup_job(&mut request, &services, method, path).await;
684 }
Agents as a team: lifecycle, merge queue, billing and a new shell685 ("POST", path) if path.starts_with("/queue/") => {
686 let entry_id = path.trim_start_matches("/queue/").to_owned();
687 return report_queue(&mut request, &services, &entry_id).await;
688 }
GitHub Actions on g1t, part two: running workflows689 // A sandbox running a GitHub Actions job: fetching the job, and
690 // reporting how it goes. The job's own token is the credential.
691 ("POST", path) if path.starts_with("/actions/jobs/") => {
692 let rest = path.trim_start_matches("/actions/jobs/");
693 let (job, method) = match rest.strip_suffix("/spec") {
694 Some(job) => (job.to_owned(), "job_spec"),
695 None => (rest.to_owned(), "job_report"),
696 };
697 let body = json_body(&mut request).await;
698 let answered: Outcome<Value> = g1t_kit::call(
699 &services.actions,
700 method,
701 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
702 )
703 .await?;
704 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API705 // A job's spec is the workflow and its contexts as GitHub
706 // has them; only g1t's own keys around them are converted.
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2707 Outcome::Ok(value) => {
708 let mut spec = wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN);
709 with_runtime(&mut spec, &services.addresses.api, oidc::configured(env));
710 Response::from_json(&spec)
711 }
GitHub Actions on g1t, part two: running workflows712 Outcome::Fail(refused) => failure(&refused),
713 };
714 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains715 // A sandbox reporting its agent run's steps, cost and end. As with
716 // checks, the run's own token, in the body, is the credential.
717 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
718 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
719 let mut body = json_body(&mut request).await;
720 if !body.is_object() {
721 body = json!({});
722 }
723 body["runId"] = json!(run_id);
724 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
725 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API726 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains727 Outcome::Fail(refused) => failure(&refused),
728 };
729 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API730 // What a run's agent learned, as memory candidates; the same token.
731 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
732 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
733 let body = json_body(&mut request).await;
734 let learned = json!({
735 "runId": run_id,
736 "token": body["token"].as_str().unwrap_or_default(),
737 "items": body["items"].as_array().cloned().unwrap_or_default(),
738 });
739 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
740 return match captured {
741 Outcome::Ok(captured) => reply(&captured),
742 Outcome::Fail(refused) => failure(&refused),
743 };
744 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step745 // How sure a run's agent is of its change; the same token.
746 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
747 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
748 let body = json_body(&mut request).await;
749 let said = json!({
750 "runId": run_id,
751 "token": body["token"].as_str().unwrap_or_default(),
752 "confidence": body["confidence"].as_str().unwrap_or_default(),
753 "uncertainAbout": body["uncertain_about"]
754 .as_array()
755 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
756 .unwrap_or_default(),
757 });
758 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
759 return match recorded {
760 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
761 Outcome::Fail(refused) => failure(&refused),
762 };
763 }
Agents as a team: lifecycle, merge queue, billing and a new shell764 ("POST", path) if path.starts_with("/checks/") => {
765 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts766 return report_checks(&mut request, &services, &run_id).await;
767 }
Agents as a team: lifecycle, merge queue, billing and a new shell768 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
769 let run_id = path
770 .trim_start_matches("/runs/")
771 .trim_end_matches("/usage")
772 .to_owned();
773 return report_usage(&mut request, &services, &run_id).await;
774 }
775 ("POST", path) if path.starts_with("/plans/") => {
776 let plan_id = path.trim_start_matches("/plans/").to_owned();
777 return report_plan(&mut request, &services, &plan_id).await;
778 }
779 ("POST", path) if path.starts_with("/reviews/") => {
780 let run_id = path.trim_start_matches("/reviews/").to_owned();
781 return report_review(&mut request, &services, &run_id).await;
782 }
API and MCP server in Rust; a public index at the API root783 _ => {}
784 }
785
786 let query: Vec<(String, String)> = url
787 .query_pairs()
788 .map(|(name, value)| (name.into_owned(), value.into_owned()))
789 .collect();
790 let body = if method == "GET" {
791 Value::Null
792 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell793 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root794 };
795 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
796 return fail(FailureCode::NotFound, "No such endpoint.");
797 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API798 match audit::run(route.op, &services, &viewer, &input).await? {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2799 // A download is a redirect to its signed link, as GitHub's is.
800 Outcome::Ok(value) if route.op == operations::Op::Artifacts(artifacts::ArtifactsOp::DownloadArtifact) => {
801 match value["url"].as_str().and_then(|url| worker::Url::parse(url).ok()) {
802 Some(url) => Response::redirect_with_status(url, 302),
803 None => reply(&value),
804 }
805 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API806 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 step807 // A token without the scope a call needs is told which one.
808 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
809 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
810 "error": {
811 "code": refused.code,
812 "message": refused.message,
813 "needed_scope": scope.as_str(),
814 }
815 }))?
816 .with_status(403)),
817 _ => failure(&refused),
818 },
API and MCP server in Rust; a public index at the API root819 }
820}
821
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API822/// Request bodies take the same keys as the MCP tools, `snake_case`, as
823/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell824fn snake_case_keys(body: Value) -> Value {
825 let Value::Object(fields) = body else {
826 return body;
827 };
828 let mut out = serde_json::Map::new();
829 for (key, value) in fields {
830 let mut snake = String::with_capacity(key.len() + 4);
831 for c in key.chars() {
832 if c.is_ascii_uppercase() {
833 snake.push('_');
834 snake.push(c.to_ascii_lowercase());
835 } else {
836 snake.push(c);
837 }
838 }
839 // A key given in both spellings keeps the snake_case one.
840 if snake != key && out.contains_key(&snake) {
841 continue;
842 }
843 out.insert(snake, value);
844 }
845 Value::Object(out)
846}
847
848#[cfg(test)]
849mod tests {
850 use super::snake_case_keys;
851 use serde_json::json;
852
853 #[test]
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2854 fn a_job_spec_gets_the_toolkits_variables() {
855 // As the actions service sends it, converted as the API does.
856 let sent = json!({ "variables": { "GITHUB_SHA": "abc" }, "runtime": { "token": "h.p.s", "idToken": true } });
857 let mut spec = g1t_kit::wire::snake_case_keeping(sent.clone(), super::JOB_SPEC_AS_GIVEN);
858 super::with_runtime(&mut spec, "https://api.g1t.sh", true);
859 assert!(spec.get("runtime").is_none(), "the runner never sees it");
860 let vars = &spec["variables"];
861 assert_eq!(vars["GITHUB_SHA"], "abc");
862 assert_eq!(vars["ACTIONS_RUNTIME_TOKEN"], "h.p.s");
863 assert_eq!(vars["ACTIONS_CACHE_URL"], "https://api.g1t.sh/actions/toolkit/");
864 assert_eq!(vars["ACTIONS_ID_TOKEN_REQUEST_TOKEN"], "h.p.s");
865 // No OIDC key here: no OIDC variables, whatever the job may do.
866 let mut spec = g1t_kit::wire::snake_case_keeping(sent, super::JOB_SPEC_AS_GIVEN);
867 super::with_runtime(&mut spec, "https://api.g1t.sh", false);
868 assert!(spec["variables"].get("ACTIONS_ID_TOKEN_REQUEST_URL").is_none());
869 assert_eq!(spec["variables"]["ACTIONS_RESULTS_URL"], "https://api.g1t.sh/");
870 }
871
872 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell873 fn camel_case_keys_are_accepted() {
874 assert_eq!(
875 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
876 json!({ "count_agent_approvals": false, "title": "x" })
877 );
878 }
879
880 #[test]
881 fn snake_case_wins_when_both_are_given() {
882 assert_eq!(
883 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
884 json!({ "keep_issue_open": true })
885 );
886 }
887}
888
API and MCP server in Rust; a public index at the API root889// The API is called from browsers too: the reference's explorer, and apps
890// built on g1t. It carries no cookies, so any origin may call it.
891#[event(fetch)]
892async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
893 let mut response = respond(request, &env).await?;
894 let headers = response.headers_mut();
895 headers.set("access-control-allow-origin", "*")?;
896 headers.set(
897 "access-control-allow-headers",
898 "authorization, content-type",
899 )?;
900 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
901 headers.set("access-control-expose-headers", "www-authenticate")?;
902 Ok(response)
903}

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