Skip to content
905 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;
Merge branch 'worktree-agent-a5a5de74d8863d554' into worktree-agent-a16631325aecf58ca16mod deploy_keys;
API and MCP server in Rust; a public index at the API root17mod mcp;
API: notifications over REST and MCP, with notifications scopes18mod notifications;
API and MCP server in Rust; a public index at the API root19mod oauth;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R220mod oidc;
API and MCP server in Rust; a public index at the API root21mod openapi;
API: pinned projects over REST and MCP22mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9723mod projects;
Merge branch 'worktree-agent-a3abfcce648e87dca'24mod protection;
API and MCP server in Rust; a public index at the API root25mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains26mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API27#[cfg(test)]
28mod responses;
API and MCP server in Rust; a public index at the API root29mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge30mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents31mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar32mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step33mod tools;
API and MCP for a workspace's personal access token rules, members' tokens and approvals34mod token_policy;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R235mod toolkit;
API and MCP server in Rust; a public index at the API root36
Merge branch 'model-routing'37use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root38use g1t_contracts::identity::{
39 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
40};
Agents as a team: lifecycle, merge queue, billing and a new shell41use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains42 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
43 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell44};
45use g1t_contracts::identity::AgentScope;
46use 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 API47use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root48use serde_json::{Value, json};
49use worker::{Context, Env, Method, Request, Response, Result, event};
50
51use operations::Services;
52
53fn method_name(method: Method) -> &'static str {
54 match method {
55 Method::Get => "GET",
56 Method::Post => "POST",
57 Method::Patch => "PATCH",
58 Method::Put => "PUT",
59 Method::Delete => "DELETE",
60 Method::Options => "OPTIONS",
61 Method::Head => "HEAD",
62 _ => "OTHER",
63 }
64}
65
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API66/// A JSON response. Every body the API sends has its keys in `snake_case`;
67/// the contracts it passes through are `camelCase`, so they are converted
68/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
69/// the MCP protocol's own envelope keep the spelling their standards use.
70pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
71 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
72}
73
74/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
75/// workflow file, GitHub's contexts and event, and where to check out, all
76/// passed through as they are.
77const JOB_SPEC_AS_GIVEN: &[&str] = &[
Merge branch 'worktree-agent-a3abfcce648e87dca'78 "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 API79];
80
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R281/// Puts the toolkit's variables in a job's spec: its runtime token, where
82/// the toolkit's services are, and where to ask for an OIDC token when the
83/// job may have one and this installation issues them. The `runtime` the
84/// actions service sent goes no further.
85fn with_runtime(spec: &mut Value, api: &str, oidc: bool) {
86 let Some(runtime) = spec.as_object_mut().and_then(|s| s.remove("runtime")) else { return };
87 let Some(token) = runtime["token"].as_str().filter(|t| !t.is_empty()) else { return };
88 let id_token = oidc && runtime["id_token"].as_bool() == Some(true);
89 let vars = toolkit::runtime_variables(api, token, id_token);
90 if let Some(variables) = spec.get_mut("variables").and_then(Value::as_object_mut) {
91 variables.extend(vars);
92 }
93}
94
API and MCP server in Rust; a public index at the API root95/// An error in the shape every endpoint uses.
96fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API97 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root98}
99
100fn fail(code: FailureCode, message: &str) -> Result<Response> {
101 failure(&Failure {
102 code,
103 message: message.to_owned(),
104 })
105}
106
107/// A request body as JSON. An empty or malformed body is no input.
108async fn json_body(request: &mut Request) -> Value {
109 request.json().await.unwrap_or(Value::Null)
110}
111
112/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
113/// an anonymous viewer; a wrong one is refused, so that a typo does not
114/// silently look signed out.
115async fn authenticate(
116 request: &Request,
117 services: &Services,
118) -> Result<std::result::Result<Viewer, Response>> {
119 let header = request.headers().get("authorization")?.unwrap_or_default();
120 let token = match header.split_once(' ') {
121 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
122 token.trim()
123 }
124 _ => return Ok(Ok(None)),
125 };
126 let viewer: Viewer = g1t_kit::call(
127 &services.identity,
128 "user_for_access_token",
129 &TokenArgs {
130 token: token.to_owned(),
131 },
132 )
133 .await?;
134 if viewer.is_some() {
135 return Ok(Ok(viewer));
136 }
137 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
138 // Tells an MCP client where to sign in again.
139 response.headers_mut().set(
140 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'141 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root142 )?;
143 Ok(Err(response))
144}
145
146/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'147fn index(addresses: &addresses::Addresses) -> Value {
148 let api = &addresses.api;
149 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root150 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'151 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'152 "openapi_url": format!("{api}/openapi.json"),
153 "mcp_url": addresses.mcp,
154 "current_user_url": format!("{api}/user"),
155 "workspaces_url": format!("{api}/workspaces"),
156 "repositories_url": format!("{api}/repos{{?q}}"),
157 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root158 "repository_url": repo,
159 "repository_events_url": format!("{repo}/events{{?before}}"),
160 "labels_url": format!("{repo}/labels"),
161 "issues_url": format!("{repo}/issues{{?state,label}}"),
162 "issue_url": format!("{repo}/issues/{{number}}"),
163 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
164 "pulls_url": format!("{repo}/pulls{{?state}}"),
165 "pull_url": format!("{repo}/pulls/{{number}}"),
166 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts167 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root168 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'169 "device_code_url": format!("{api}/device/code"),
170 "device_token_url": format!("{api}/device/token"),
171 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
172 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
173 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read174 "context_url": format!("{repo}/context{{?reference}}"),
175 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'176 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root177 })
178}
179
180// Signing in from a tool. Accounts are created, and passwords typed, only
181// in a browser; a tool gets its token by having a person approve a code.
182
Integrations: your own model provider, alerts that open issues, tickets agents read183/// Passes a request from an outside system to its connection, as it came:
184/// its signature covers the exact bytes of the body.
185async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
186 let headers: std::collections::HashMap<String, String> = request
187 .headers()
188 .entries()
189 .map(|(name, value)| (name.to_lowercase(), value))
190 .collect();
191 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look192 // A push to GitHub with many commits makes a large payload.
193 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
194 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API195 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read196 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look197 // g1t's GitHub App has one webhook for every installation; it is
198 // checked against the app's own secret.
199 let (method, args) = if id == "github" {
200 ("github_receive", json!({ "headers": headers, "body": body }))
201 } else {
202 ("receive", json!({ "id": id, "headers": headers, "body": body }))
203 };
204 let received: g1t_contracts::integrations::Received =
205 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 API206 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read207}
208
Stripe webhooks, enterprise invoices, and sudo for both209async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
210 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
211 let payload = request.text().await.unwrap_or_default();
212 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 API213 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both214 }
215 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
216 &env.service("BILLING")?,
217 "stripe_webhook",
218 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
219 )
220 .await?;
221 // A refusal is a 400, so Stripe shows it as failed; anything handled,
222 // or already handled, is a 200, so Stripe stops sending it.
223 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API224 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both225 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API226 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both227 }
228 })
229}
230
API and MCP server in Rust; a public index at the API root231async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
232 let body = json_body(request).await;
233 let started: DeviceStart = g1t_kit::call(
234 &services.identity,
235 "device_start",
236 &DeviceStartArgs {
237 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
238 },
239 )
240 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API241 reply(&json!({
API and MCP server in Rust; a public index at the API root242 "device_code": started.device_code,
243 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'244 "verification_uri": format!("{}/device", services.addresses.site),
245 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root246 "expires_in": started.expires_in,
247 "interval": started.interval,
248 }))
249}
250
251async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
252 let body = json_body(request).await;
253 let claim: DeviceClaim = g1t_kit::call(
254 &services.identity,
255 "device_claim",
256 &DeviceClaimArgs {
257 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
258 },
259 )
260 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API261 reply(&match claim {
API and MCP server in Rust; a public index at the API root262 DeviceClaim::Approved { token, user } => json!({
263 "status": "approved",
264 "token": token,
265 "username": user.username,
266 "verified": user.verified,
267 }),
268 DeviceClaim::Pending => json!({ "status": "pending" }),
269 DeviceClaim::Denied => json!({ "status": "denied" }),
270 DeviceClaim::Expired => json!({ "status": "expired" }),
271 })
272}
273
Fast pages, required checks on the branch, self-hosted runners, honest incidents274/// A sandbox reporting on a run of an issue's commands, from before a pull
275/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts276/// The run's own token, in the body, is the credential: it was given to
277/// that sandbox and to nothing else.
278async fn report_checks(
279 request: &mut Request,
280 services: &Services,
281 run_id: &str,
282) -> Result<Response> {
283 let body = json_body(request).await;
284 let reported: Outcome<CheckRun> = g1t_kit::call(
285 &services.work,
286 "report_checks",
287 &ReportChecksArgs {
288 run_id: run_id.to_owned(),
289 token: body["token"].as_str().unwrap_or_default().to_owned(),
290 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
291 error: body["error"].as_str().map(str::to_owned),
292 skip: false,
293 },
294 )
295 .await?;
296 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API297 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts298 Outcome::Fail(refused) => failure(&refused),
299 }
300}
301
Agents as a team: lifecycle, merge queue, billing and a new shell302/// A sandbox reporting one tested state of a merge queue. As with checks,
303/// the entry's own token is the credential.
304async fn report_queue(
305 request: &mut Request,
306 services: &Services,
307 entry_id: &str,
308) -> Result<Response> {
309 let body = json_body(request).await;
310 let reported: Outcome<QueueState> = g1t_kit::call(
311 &services.work,
312 "report_queue",
313 &ReportQueueArgs {
314 entry_id: entry_id.to_owned(),
315 token: body["token"].as_str().unwrap_or_default().to_owned(),
316 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
317 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
318 error: body["error"].as_str().map(str::to_owned),
319 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains320 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell321 },
322 )
323 .await?;
324 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API325 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell326 Outcome::Fail(refused) => failure(&refused),
327 }
328}
329
Agents and memory, checks and conflicts, profiles, slug renames, custom domains330/// A sandbox reporting whether a pull request merges cleanly. As with
331/// checks, the probe's own token is the credential.
332async fn report_mergecheck(
333 request: &mut Request,
334 services: &Services,
335 pull_id: &str,
336) -> Result<Response> {
337 let body = json_body(request).await;
338 let reported: Outcome<Mergeable> = g1t_kit::call(
339 &services.work,
340 "report_mergecheck",
341 &ReportMergecheckArgs {
342 pull_id: pull_id.to_owned(),
343 token: body["token"].as_str().unwrap_or_default().to_owned(),
344 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
345 error: body["error"].as_str().map(str::to_owned),
346 },
347 )
348 .await?;
349 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API350 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains351 Outcome::Fail(refused) => failure(&refused),
352 }
353}
354
Merge branch 'worktree-agent-ac5b181a013e54348'355/// A backup's sandbox, passed on to the repos service, which holds the
356/// job (services/repos/src/backups.rs; the flow is in
357/// `g1t_contracts::backups`):
358///
359/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
360/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
361/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
362/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
363///
364/// Bodies are passed through as they are: snake_case already, and a
365/// bundle's refs are keyed by ref names, which must not be converted.
366async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
367 use g1t_contracts::backups::TOKEN_HEADER;
368 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
369 let rest = path.trim_start_matches("/backups/");
370 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
371 if job.is_empty() || token.is_empty() {
372 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
373 }
374 if method == "PUT" && action.starts_with("parts/") {
375 let bytes = request.bytes().await?;
376 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
377 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
378 }
379 let headers = worker::Headers::new();
380 headers.set(TOKEN_HEADER, &token)?;
381 let mut init = worker::RequestInit::new();
382 init.with_method(Method::Put)
383 .with_headers(headers)
384 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
385 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
386 let mut answered = services.repos.fetch_request(forwarded).await?;
387 return outcome_as_given(answered.json().await?);
388 }
389 let rpc = match (method, action) {
390 ("POST", "spec") => "backup_spec",
391 ("POST", "complete") => "backup_complete",
392 ("POST", "fail") => "backup_fail",
393 _ => return fail(FailureCode::NotFound, "No such endpoint."),
394 };
395 let mut body = json_body(request).await;
396 if !body.is_object() {
397 body = json!({});
398 }
399 body["job_id"] = json!(job);
400 body["token"] = json!(token);
401 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
402 outcome_as_given(answered)
403}
404
405/// An `Outcome` from a service whose keys are already the API's: the value,
406/// or the failure in the shape every endpoint uses.
407fn outcome_as_given(answered: Value) -> Result<Response> {
408 match serde_json::from_value::<Outcome<Value>>(answered)? {
409 Outcome::Ok(value) => Response::from_json(&value),
410 Outcome::Fail(refused) => failure(&refused),
411 }
412}
413
Agents as a team: lifecycle, merge queue, billing and a new shell414/// A sandbox reporting the review its agent wrote. As with checks, the
415/// run's own token is the credential.
416async fn report_review(
417 request: &mut Request,
418 services: &Services,
419 run_id: &str,
420) -> Result<Response> {
421 let body = json_body(request).await;
422 let reported: Outcome<bool> = g1t_kit::call(
423 &services.work,
424 "report_review",
425 &ReportReviewArgs {
426 run_id: run_id.to_owned(),
427 token: body["token"].as_str().unwrap_or_default().to_owned(),
428 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
429 body: body["body"].as_str().unwrap_or_default().to_owned(),
430 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
431 model: body["model"].as_str().map(str::to_owned),
432 error: body["error"].as_str().map(str::to_owned),
433 },
434 )
435 .await?;
436 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API437 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell438 Outcome::Fail(refused) => failure(&refused),
439 }
440}
441
442/// A sandbox reporting the plan its agent wrote. As with checks, the
443/// plan's own token is the credential.
444async fn report_plan(
445 request: &mut Request,
446 services: &Services,
447 plan_id: &str,
448) -> Result<Response> {
449 let body = json_body(request).await;
450 let reported: Outcome<bool> = g1t_kit::call(
451 &services.work,
452 "report_plan",
453 &ReportPlanArgs {
454 plan_id: plan_id.to_owned(),
455 token: body["token"].as_str().unwrap_or_default().to_owned(),
456 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
457 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
458 error: body["error"].as_str().map(str::to_owned),
459 },
460 )
461 .await?;
462 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API463 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell464 Outcome::Fail(refused) => failure(&refused),
465 }
466}
467
468/// A sandbox reporting what its agent's run cost, so that the workspace
469/// it worked for is charged. As with checks, the run's own token is the
470/// credential.
471async fn report_usage(
472 request: &mut Request,
473 services: &Services,
474 run_id: &str,
475) -> Result<Response> {
476 let body = json_body(request).await;
477 let charged: Outcome<bool> = g1t_kit::call(
478 &services.billing,
479 "finish_run",
480 &FinishRunArgs {
481 run_id: run_id.to_owned(),
482 token: body["token"].as_str().unwrap_or_default().to_owned(),
483 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
484 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'485 // What the harness counted; the agent rate is charged on no
486 // fewer, on a workspace's own model key too.
487 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
488 input: t["input"].as_u64().unwrap_or_default(),
489 output: t["output"].as_u64().unwrap_or_default(),
490 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
491 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
492 }),
Agents as a team: lifecycle, merge queue, billing and a new shell493 },
494 )
495 .await?;
496 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API497 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell498 Outcome::Fail(refused) => failure(&refused),
499 }
500}
501
API and MCP server in Rust; a public index at the API root502async fn respond(mut request: Request, env: &Env) -> Result<Response> {
503 let method = method_name(request.method());
504 if method == "OPTIONS" {
505 return Ok(Response::empty()?.with_status(204));
506 }
507 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell508 // Paths carry no version. An earlier form began with `/v1`, which is
509 // still accepted so that nothing already written against it breaks.
510 let path = match url.path().strip_prefix("/v1") {
511 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
512 _ => url.path().to_owned(),
513 };
514 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'515 // MCP is a host of its own hosted, and may be a path on this one
516 // self-hosted (addresses.rs).
517 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root518
Stripe webhooks, enterprise invoices, and sudo for both519 // Stripe reporting to billing. Signed with the secret of the endpoint
520 // billing registered; the body goes through exactly as received, since
521 // the signature covers its bytes.
522 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
523 return receive_stripe(&mut request, env).await;
524 }
525
Integrations: your own model provider, alerts that open issues, tickets agents read526 // Outside systems reporting to a connection. They sign what they send
527 // with the connection's own secret, which is not a g1t token, so this
528 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide529 if method == "POST" && !on_mcp
530 && 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 read531 return receive_hook(&mut request, &services, id).await;
532 }
533
Deployments: a preview for every pull request, production on g1t.page534 // A sandbox building a deployment, reporting with its build's token,
535 // which is not a g1t token. The body goes through as it is: it can
536 // carry a Worker's bundled code.
537 if method == "POST" && !on_mcp
538 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
539 {
540 let target = format!("https://deployments/jobs/{rest}");
541 let body = request.bytes().await?;
542 let headers = worker::Headers::new();
543 headers.set("content-type", "application/json")?;
544 let mut init = worker::RequestInit::new();
545 init.with_method(Method::Post)
546 .with_headers(headers)
547 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run548 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page549 .service("DEPLOYMENTS")?
550 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run551 .await?;
552 // A fresh response: a fetched one's headers cannot be changed, and
553 // every response gets the API's own on the way out.
554 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API555 let bytes = answer.bytes().await?;
556 let bytes = match serde_json::from_slice::<Value>(&bytes) {
557 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
558 Err(_) => bytes,
559 };
560 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run561 .with_status(status)
562 .with_headers({
563 let headers = worker::Headers::new();
564 headers.set("content-type", "application/json")?;
565 headers
566 }));
Deployments: a preview for every pull request, production on g1t.page567 }
568
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2569 // The services GitHub's toolkit calls from inside a job, with its
570 // runtime token, and the links they hand out (toolkit.rs).
571 if !on_mcp && method == "POST"
572 && let Some(rest) = path.strip_prefix("/twirp/")
573 {
574 let (service, rpc) = rest.split_once('/').unwrap_or((rest, ""));
575 let (service, rpc) = (service.to_owned(), rpc.to_owned());
576 return toolkit::twirp(request, env, &services, &service, &rpc).await;
577 }
578 if !on_mcp && let Some(rest) = path.strip_prefix("/actions/toolkit/_apis/artifactcache/") {
579 let rest = rest.to_owned();
580 return toolkit::cache_v1(request, env, &services, method, &rest).await;
581 }
582 if !on_mcp && let Some(token) = path.strip_prefix("/actions/toolkit/blobs/") {
583 let token = token.to_owned();
584 return toolkit::blob(request, env, &services, method, &token).await;
585 }
586 // g1t as an OIDC issuer for workflow jobs (oidc.rs).
587 if !on_mcp && method == "GET" && path.starts_with("/actions/oidc/") {
588 return oidc::handle(&request, env, &services, &path).await;
589 }
590
A repository has its own sidebar, as settings do591 // A sandbox's artifacts and cache, with its job's token, which is not a
592 // g1t token either.
593 if !on_mcp
594 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents595 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do596 {
597 let rest = rest.to_owned();
598 return blobs::for_job(request, env, &services, method, &rest).await;
599 }
600
Fast pages, required checks on the branch, self-hosted runners, honest incidents601 // A self-hosted runner, with a registration token or its own
602 // credential, neither of which is a g1t access token.
603 if method == "POST"
604 && !on_mcp
605 && path.starts_with("/runners/")
606 && let Some(response) = runners::handle(&mut request, &services, &path).await?
607 {
608 return Ok(response);
609 }
610
API and MCP server in Rust; a public index at the API root611 let viewer = match authenticate(&request, &services).await? {
612 Ok(viewer) => viewer,
613 Err(refused) => return Ok(refused),
614 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API615 services.audit = audit::AuditContext::of(&request, on_mcp);
616 // An agent's token: what it may do comes with it, on the composite
617 // identity identity resolved it to.
618 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
619 services.scope = Some(acting.scope.clone());
620 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell621 let header = request.headers().get("authorization")?.unwrap_or_default();
622 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
623 let scope: Option<AgentScope> = g1t_kit::call(
624 &services.identity,
625 "agent_scope",
626 &TokenArgs {
627 token: token.to_owned(),
628 },
629 )
630 .await?;
631 // A scope is what lets an agent's token do anything at all.
632 let Some(scope) = scope else {
633 return fail(FailureCode::Unauthenticated, "Invalid access token.");
634 };
635 services.scope = Some(scope);
636 }
API and MCP server in Rust; a public index at the API root637 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
638 return Ok(response);
639 }
640 if on_mcp {
641 return mcp::handle(request, &services, &viewer).await;
642 }
643
644 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'645 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root646 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2647 // One of a run's artifacts downloaded by name (the run's artifacts
648 // are listed by the REST route in rest.rs).
649 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts/") => {
A repository has its own sidebar, as settings do650 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2651 if let [owner, repo, "actions", "runs", run, "artifacts", name] = parts.as_slice() {
Merge branch 'worktree-agent-a3abfcce648e87dca'652 // A workflow job's token reaches its own repository only.
653 if viewer
654 .as_ref()
655 .and_then(|user| user.token.as_deref())
656 .is_some_and(|token| !token.reaches(&format!("{owner}/{repo}")))
657 {
658 return fail(FailureCode::NotFound, "No such run.");
659 }
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2660 return blobs::download(env, &services, &viewer, owner, repo, run, name).await;
A repository has its own sidebar, as settings do661 }
662 }
Agents as a team: lifecycle, merge queue, billing and a new shell663 ("POST", "/device/code") => return device_code(&mut request, &services).await,
664 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically665 // Where a pull request lives, for a tool that knows only its fork.
666 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
667 let located: Outcome<Value> = g1t_kit::call(
668 &services.work,
669 "locate_pull",
670 &json!({ "id": &path[7..], "viewer": viewer }),
671 )
672 .await?;
673 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API674 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically675 Outcome::Fail(refused) => failure(&refused),
676 };
677 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains678 ("POST", path) if path.starts_with("/mergechecks/") => {
679 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
680 return report_mergecheck(&mut request, &services, &pull_id).await;
681 }
Merge branch 'worktree-agent-ac5b181a013e54348'682 // A sandbox making a repository's nightly backup. The job's own
683 // token, in its header, is the credential.
684 (method, path) if path.starts_with("/backups/") => {
685 return backup_job(&mut request, &services, method, path).await;
686 }
Agents as a team: lifecycle, merge queue, billing and a new shell687 ("POST", path) if path.starts_with("/queue/") => {
688 let entry_id = path.trim_start_matches("/queue/").to_owned();
689 return report_queue(&mut request, &services, &entry_id).await;
690 }
GitHub Actions on g1t, part two: running workflows691 // A sandbox running a GitHub Actions job: fetching the job, and
692 // reporting how it goes. The job's own token is the credential.
693 ("POST", path) if path.starts_with("/actions/jobs/") => {
694 let rest = path.trim_start_matches("/actions/jobs/");
695 let (job, method) = match rest.strip_suffix("/spec") {
696 Some(job) => (job.to_owned(), "job_spec"),
697 None => (rest.to_owned(), "job_report"),
698 };
699 let body = json_body(&mut request).await;
700 let answered: Outcome<Value> = g1t_kit::call(
701 &services.actions,
702 method,
703 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
704 )
705 .await?;
706 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API707 // A job's spec is the workflow and its contexts as GitHub
708 // has them; only g1t's own keys around them are converted.
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2709 Outcome::Ok(value) => {
710 let mut spec = wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN);
711 with_runtime(&mut spec, &services.addresses.api, oidc::configured(env));
712 Response::from_json(&spec)
713 }
GitHub Actions on g1t, part two: running workflows714 Outcome::Fail(refused) => failure(&refused),
715 };
716 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains717 // A sandbox reporting its agent run's steps, cost and end. As with
718 // checks, the run's own token, in the body, is the credential.
719 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
720 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
721 let mut body = json_body(&mut request).await;
722 if !body.is_object() {
723 body = json!({});
724 }
725 body["runId"] = json!(run_id);
726 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
727 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API728 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains729 Outcome::Fail(refused) => failure(&refused),
730 };
731 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API732 // What a run's agent learned, as memory candidates; the same token.
733 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
734 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
735 let body = json_body(&mut request).await;
736 let learned = json!({
737 "runId": run_id,
738 "token": body["token"].as_str().unwrap_or_default(),
739 "items": body["items"].as_array().cloned().unwrap_or_default(),
740 });
741 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
742 return match captured {
743 Outcome::Ok(captured) => reply(&captured),
744 Outcome::Fail(refused) => failure(&refused),
745 };
746 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step747 // How sure a run's agent is of its change; the same token.
748 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
749 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
750 let body = json_body(&mut request).await;
751 let said = json!({
752 "runId": run_id,
753 "token": body["token"].as_str().unwrap_or_default(),
754 "confidence": body["confidence"].as_str().unwrap_or_default(),
755 "uncertainAbout": body["uncertain_about"]
756 .as_array()
757 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
758 .unwrap_or_default(),
759 });
760 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
761 return match recorded {
762 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
763 Outcome::Fail(refused) => failure(&refused),
764 };
765 }
Agents as a team: lifecycle, merge queue, billing and a new shell766 ("POST", path) if path.starts_with("/checks/") => {
767 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts768 return report_checks(&mut request, &services, &run_id).await;
769 }
Agents as a team: lifecycle, merge queue, billing and a new shell770 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
771 let run_id = path
772 .trim_start_matches("/runs/")
773 .trim_end_matches("/usage")
774 .to_owned();
775 return report_usage(&mut request, &services, &run_id).await;
776 }
777 ("POST", path) if path.starts_with("/plans/") => {
778 let plan_id = path.trim_start_matches("/plans/").to_owned();
779 return report_plan(&mut request, &services, &plan_id).await;
780 }
781 ("POST", path) if path.starts_with("/reviews/") => {
782 let run_id = path.trim_start_matches("/reviews/").to_owned();
783 return report_review(&mut request, &services, &run_id).await;
784 }
API and MCP server in Rust; a public index at the API root785 _ => {}
786 }
787
788 let query: Vec<(String, String)> = url
789 .query_pairs()
790 .map(|(name, value)| (name.into_owned(), value.into_owned()))
791 .collect();
792 let body = if method == "GET" {
793 Value::Null
794 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell795 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root796 };
797 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
798 return fail(FailureCode::NotFound, "No such endpoint.");
799 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API800 match audit::run(route.op, &services, &viewer, &input).await? {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2801 // A download is a redirect to its signed link, as GitHub's is.
802 Outcome::Ok(value) if route.op == operations::Op::Artifacts(artifacts::ArtifactsOp::DownloadArtifact) => {
803 match value["url"].as_str().and_then(|url| worker::Url::parse(url).ok()) {
804 Some(url) => Response::redirect_with_status(url, 302),
805 None => reply(&value),
806 }
807 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API808 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 step809 // A token without the scope a call needs is told which one.
810 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
811 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
812 "error": {
813 "code": refused.code,
814 "message": refused.message,
815 "needed_scope": scope.as_str(),
816 }
817 }))?
818 .with_status(403)),
819 _ => failure(&refused),
820 },
API and MCP server in Rust; a public index at the API root821 }
822}
823
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API824/// Request bodies take the same keys as the MCP tools, `snake_case`, as
825/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell826fn snake_case_keys(body: Value) -> Value {
827 let Value::Object(fields) = body else {
828 return body;
829 };
830 let mut out = serde_json::Map::new();
831 for (key, value) in fields {
832 let mut snake = String::with_capacity(key.len() + 4);
833 for c in key.chars() {
834 if c.is_ascii_uppercase() {
835 snake.push('_');
836 snake.push(c.to_ascii_lowercase());
837 } else {
838 snake.push(c);
839 }
840 }
841 // A key given in both spellings keeps the snake_case one.
842 if snake != key && out.contains_key(&snake) {
843 continue;
844 }
845 out.insert(snake, value);
846 }
847 Value::Object(out)
848}
849
850#[cfg(test)]
851mod tests {
852 use super::snake_case_keys;
853 use serde_json::json;
854
855 #[test]
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2856 fn a_job_spec_gets_the_toolkits_variables() {
857 // As the actions service sends it, converted as the API does.
858 let sent = json!({ "variables": { "GITHUB_SHA": "abc" }, "runtime": { "token": "h.p.s", "idToken": true } });
859 let mut spec = g1t_kit::wire::snake_case_keeping(sent.clone(), super::JOB_SPEC_AS_GIVEN);
860 super::with_runtime(&mut spec, "https://api.g1t.sh", true);
861 assert!(spec.get("runtime").is_none(), "the runner never sees it");
862 let vars = &spec["variables"];
863 assert_eq!(vars["GITHUB_SHA"], "abc");
864 assert_eq!(vars["ACTIONS_RUNTIME_TOKEN"], "h.p.s");
865 assert_eq!(vars["ACTIONS_CACHE_URL"], "https://api.g1t.sh/actions/toolkit/");
866 assert_eq!(vars["ACTIONS_ID_TOKEN_REQUEST_TOKEN"], "h.p.s");
867 // No OIDC key here: no OIDC variables, whatever the job may do.
868 let mut spec = g1t_kit::wire::snake_case_keeping(sent, super::JOB_SPEC_AS_GIVEN);
869 super::with_runtime(&mut spec, "https://api.g1t.sh", false);
870 assert!(spec["variables"].get("ACTIONS_ID_TOKEN_REQUEST_URL").is_none());
871 assert_eq!(spec["variables"]["ACTIONS_RESULTS_URL"], "https://api.g1t.sh/");
872 }
873
874 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell875 fn camel_case_keys_are_accepted() {
876 assert_eq!(
877 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
878 json!({ "count_agent_approvals": false, "title": "x" })
879 );
880 }
881
882 #[test]
883 fn snake_case_wins_when_both_are_given() {
884 assert_eq!(
885 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
886 json!({ "keep_issue_open": true })
887 );
888 }
889}
890
API and MCP server in Rust; a public index at the API root891// The API is called from browsers too: the reference's explorer, and apps
892// built on g1t. It carries no cookies, so any origin may call it.
893#[event(fetch)]
894async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
895 let mut response = respond(request, &env).await?;
896 let headers = response.headers_mut();
897 headers.set("access-control-allow-origin", "*")?;
898 headers.set(
899 "access-control-allow-headers",
900 "authorization, content-type",
901 )?;
902 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
903 headers.set("access-control-expose-headers", "www-authenticate")?;
904 Ok(response)
905}

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