Skip to content

g1t/apps/api/src/lib.rs

823 lines34,383 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

API and MCP server in Rust; a public index at the API root1//! The public API: REST at api.g1t.sh and the MCP server at mcp.g1t.sh.
2//!
3//! One Worker, two hostnames. Both are thin adapters over the same
4//! operations (see [`operations::Op`]), which call the services that own
5//! the data. This Worker holds none.
6
Merge branch 'worktree-agent-aaf03bdceac799c89'7mod addresses;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily8mod alerts;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API9mod audit;
A repository has its own sidebar, as settings do10mod blobs;
API and MCP server in Rust; a public index at the API root11mod mcp;
API: notifications over REST and MCP, with notifications scopes12mod notifications;
API and MCP server in Rust; a public index at the API root13mod oauth;
14mod openapi;
15mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains16mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API17#[cfg(test)]
18mod responses;
API and MCP server in Rust; a public index at the API root19mod rest;
Fast pages, required checks on the branch, self-hosted runners, honest incidents20mod runners;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step21mod tools;
API and MCP server in Rust; a public index at the API root22
Agents as a team: lifecycle, merge queue, billing and a new shell23use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root24use g1t_contracts::identity::{
25 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
26};
Agents as a team: lifecycle, merge queue, billing and a new shell27use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains28 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
29 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell30};
31use g1t_contracts::identity::AgentScope;
32use 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 API33use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root34use serde_json::{Value, json};
35use worker::{Context, Env, Method, Request, Response, Result, event};
36
37use operations::Services;
38
39fn method_name(method: Method) -> &'static str {
40 match method {
41 Method::Get => "GET",
42 Method::Post => "POST",
43 Method::Patch => "PATCH",
44 Method::Put => "PUT",
45 Method::Delete => "DELETE",
46 Method::Options => "OPTIONS",
47 Method::Head => "HEAD",
48 _ => "OTHER",
49 }
50}
51
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API52/// A JSON response. Every body the API sends has its keys in `snake_case`;
53/// the contracts it passes through are `camelCase`, so they are converted
54/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
55/// the MCP protocol's own envelope keep the spelling their standards use.
56pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
57 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
58}
59
60/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
61/// workflow file, GitHub's contexts and event, and where to check out, all
62/// passed through as they are.
63const JOB_SPEC_AS_GIVEN: &[&str] = &[
64 "spec", "workflow", "github", "event", "contexts", "checkout",
65];
66
API and MCP server in Rust; a public index at the API root67/// An error in the shape every endpoint uses.
68fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API69 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root70}
71
72fn fail(code: FailureCode, message: &str) -> Result<Response> {
73 failure(&Failure {
74 code,
75 message: message.to_owned(),
76 })
77}
78
79/// A request body as JSON. An empty or malformed body is no input.
80async fn json_body(request: &mut Request) -> Value {
81 request.json().await.unwrap_or(Value::Null)
82}
83
84/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
85/// an anonymous viewer; a wrong one is refused, so that a typo does not
86/// silently look signed out.
87async fn authenticate(
88 request: &Request,
89 services: &Services,
90) -> Result<std::result::Result<Viewer, Response>> {
91 let header = request.headers().get("authorization")?.unwrap_or_default();
92 let token = match header.split_once(' ') {
93 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
94 token.trim()
95 }
96 _ => return Ok(Ok(None)),
97 };
98 let viewer: Viewer = g1t_kit::call(
99 &services.identity,
100 "user_for_access_token",
101 &TokenArgs {
102 token: token.to_owned(),
103 },
104 )
105 .await?;
106 if viewer.is_some() {
107 return Ok(Ok(viewer));
108 }
109 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
110 // Tells an MCP client where to sign in again.
111 response.headers_mut().set(
112 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'113 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root114 )?;
115 Ok(Err(response))
116}
117
118/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'119fn index(addresses: &addresses::Addresses) -> Value {
120 let api = &addresses.api;
121 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root122 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'123 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'124 "openapi_url": format!("{api}/openapi.json"),
125 "mcp_url": addresses.mcp,
126 "current_user_url": format!("{api}/user"),
127 "workspaces_url": format!("{api}/workspaces"),
128 "repositories_url": format!("{api}/repos{{?q}}"),
129 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root130 "repository_url": repo,
131 "repository_events_url": format!("{repo}/events{{?before}}"),
132 "labels_url": format!("{repo}/labels"),
133 "issues_url": format!("{repo}/issues{{?state,label}}"),
134 "issue_url": format!("{repo}/issues/{{number}}"),
135 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
136 "pulls_url": format!("{repo}/pulls{{?state}}"),
137 "pull_url": format!("{repo}/pulls/{{number}}"),
138 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts139 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root140 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'141 "device_code_url": format!("{api}/device/code"),
142 "device_token_url": format!("{api}/device/token"),
143 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
144 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
145 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read146 "context_url": format!("{repo}/context{{?reference}}"),
147 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'148 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root149 })
150}
151
152// Signing in from a tool. Accounts are created, and passwords typed, only
153// in a browser; a tool gets its token by having a person approve a code.
154
Integrations: your own model provider, alerts that open issues, tickets agents read155/// Passes a request from an outside system to its connection, as it came:
156/// its signature covers the exact bytes of the body.
157async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
158 let headers: std::collections::HashMap<String, String> = request
159 .headers()
160 .entries()
161 .map(|(name, value)| (name.to_lowercase(), value))
162 .collect();
163 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look164 // A push to GitHub with many commits makes a large payload.
165 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
166 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API167 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read168 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look169 // g1t's GitHub App has one webhook for every installation; it is
170 // checked against the app's own secret.
171 let (method, args) = if id == "github" {
172 ("github_receive", json!({ "headers": headers, "body": body }))
173 } else {
174 ("receive", json!({ "id": id, "headers": headers, "body": body }))
175 };
176 let received: g1t_contracts::integrations::Received =
177 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 API178 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read179}
180
Stripe webhooks, enterprise invoices, and sudo for both181async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
182 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
183 let payload = request.text().await.unwrap_or_default();
184 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 API185 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both186 }
187 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
188 &env.service("BILLING")?,
189 "stripe_webhook",
190 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
191 )
192 .await?;
193 // A refusal is a 400, so Stripe shows it as failed; anything handled,
194 // or already handled, is a 200, so Stripe stops sending it.
195 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API196 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both197 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API198 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both199 }
200 })
201}
202
API and MCP server in Rust; a public index at the API root203async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
204 let body = json_body(request).await;
205 let started: DeviceStart = g1t_kit::call(
206 &services.identity,
207 "device_start",
208 &DeviceStartArgs {
209 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
210 },
211 )
212 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API213 reply(&json!({
API and MCP server in Rust; a public index at the API root214 "device_code": started.device_code,
215 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'216 "verification_uri": format!("{}/device", services.addresses.site),
217 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root218 "expires_in": started.expires_in,
219 "interval": started.interval,
220 }))
221}
222
223async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
224 let body = json_body(request).await;
225 let claim: DeviceClaim = g1t_kit::call(
226 &services.identity,
227 "device_claim",
228 &DeviceClaimArgs {
229 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
230 },
231 )
232 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API233 reply(&match claim {
API and MCP server in Rust; a public index at the API root234 DeviceClaim::Approved { token, user } => json!({
235 "status": "approved",
236 "token": token,
237 "username": user.username,
238 "verified": user.verified,
239 }),
240 DeviceClaim::Pending => json!({ "status": "pending" }),
241 DeviceClaim::Denied => json!({ "status": "denied" }),
242 DeviceClaim::Expired => json!({ "status": "expired" }),
243 })
244}
245
Fast pages, required checks on the branch, self-hosted runners, honest incidents246/// A sandbox reporting on a run of an issue's commands, from before a pull
247/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts248/// The run's own token, in the body, is the credential: it was given to
249/// that sandbox and to nothing else.
250async fn report_checks(
251 request: &mut Request,
252 services: &Services,
253 run_id: &str,
254) -> Result<Response> {
255 let body = json_body(request).await;
256 let reported: Outcome<CheckRun> = g1t_kit::call(
257 &services.work,
258 "report_checks",
259 &ReportChecksArgs {
260 run_id: run_id.to_owned(),
261 token: body["token"].as_str().unwrap_or_default().to_owned(),
262 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
263 error: body["error"].as_str().map(str::to_owned),
264 skip: false,
265 },
266 )
267 .await?;
268 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API269 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts270 Outcome::Fail(refused) => failure(&refused),
271 }
272}
273
Agents as a team: lifecycle, merge queue, billing and a new shell274/// A sandbox reporting one tested state of a merge queue. As with checks,
275/// the entry's own token is the credential.
276async fn report_queue(
277 request: &mut Request,
278 services: &Services,
279 entry_id: &str,
280) -> Result<Response> {
281 let body = json_body(request).await;
282 let reported: Outcome<QueueState> = g1t_kit::call(
283 &services.work,
284 "report_queue",
285 &ReportQueueArgs {
286 entry_id: entry_id.to_owned(),
287 token: body["token"].as_str().unwrap_or_default().to_owned(),
288 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
289 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
290 error: body["error"].as_str().map(str::to_owned),
291 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains292 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell293 },
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(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell298 Outcome::Fail(refused) => failure(&refused),
299 }
300}
301
Agents and memory, checks and conflicts, profiles, slug renames, custom domains302/// A sandbox reporting whether a pull request merges cleanly. As with
303/// checks, the probe's own token is the credential.
304async fn report_mergecheck(
305 request: &mut Request,
306 services: &Services,
307 pull_id: &str,
308) -> Result<Response> {
309 let body = json_body(request).await;
310 let reported: Outcome<Mergeable> = g1t_kit::call(
311 &services.work,
312 "report_mergecheck",
313 &ReportMergecheckArgs {
314 pull_id: pull_id.to_owned(),
315 token: body["token"].as_str().unwrap_or_default().to_owned(),
316 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
317 error: body["error"].as_str().map(str::to_owned),
318 },
319 )
320 .await?;
321 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API322 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains323 Outcome::Fail(refused) => failure(&refused),
324 }
325}
326
Merge branch 'worktree-agent-ac5b181a013e54348'327/// A backup's sandbox, passed on to the repos service, which holds the
328/// job (services/repos/src/backups.rs; the flow is in
329/// `g1t_contracts::backups`):
330///
331/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
332/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
333/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
334/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
335///
336/// Bodies are passed through as they are: snake_case already, and a
337/// bundle's refs are keyed by ref names, which must not be converted.
338async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
339 use g1t_contracts::backups::TOKEN_HEADER;
340 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
341 let rest = path.trim_start_matches("/backups/");
342 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
343 if job.is_empty() || token.is_empty() {
344 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
345 }
346 if method == "PUT" && action.starts_with("parts/") {
347 let bytes = request.bytes().await?;
348 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
349 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
350 }
351 let headers = worker::Headers::new();
352 headers.set(TOKEN_HEADER, &token)?;
353 let mut init = worker::RequestInit::new();
354 init.with_method(Method::Put)
355 .with_headers(headers)
356 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
357 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
358 let mut answered = services.repos.fetch_request(forwarded).await?;
359 return outcome_as_given(answered.json().await?);
360 }
361 let rpc = match (method, action) {
362 ("POST", "spec") => "backup_spec",
363 ("POST", "complete") => "backup_complete",
364 ("POST", "fail") => "backup_fail",
365 _ => return fail(FailureCode::NotFound, "No such endpoint."),
366 };
367 let mut body = json_body(request).await;
368 if !body.is_object() {
369 body = json!({});
370 }
371 body["job_id"] = json!(job);
372 body["token"] = json!(token);
373 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
374 outcome_as_given(answered)
375}
376
377/// An `Outcome` from a service whose keys are already the API's: the value,
378/// or the failure in the shape every endpoint uses.
379fn outcome_as_given(answered: Value) -> Result<Response> {
380 match serde_json::from_value::<Outcome<Value>>(answered)? {
381 Outcome::Ok(value) => Response::from_json(&value),
382 Outcome::Fail(refused) => failure(&refused),
383 }
384}
385
Agents as a team: lifecycle, merge queue, billing and a new shell386/// A sandbox reporting the review its agent wrote. As with checks, the
387/// run's own token is the credential.
388async fn report_review(
389 request: &mut Request,
390 services: &Services,
391 run_id: &str,
392) -> Result<Response> {
393 let body = json_body(request).await;
394 let reported: Outcome<bool> = g1t_kit::call(
395 &services.work,
396 "report_review",
397 &ReportReviewArgs {
398 run_id: run_id.to_owned(),
399 token: body["token"].as_str().unwrap_or_default().to_owned(),
400 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
401 body: body["body"].as_str().unwrap_or_default().to_owned(),
402 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
403 model: body["model"].as_str().map(str::to_owned),
404 error: body["error"].as_str().map(str::to_owned),
405 },
406 )
407 .await?;
408 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API409 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell410 Outcome::Fail(refused) => failure(&refused),
411 }
412}
413
414/// A sandbox reporting the plan its agent wrote. As with checks, the
415/// plan's own token is the credential.
416async fn report_plan(
417 request: &mut Request,
418 services: &Services,
419 plan_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_plan",
425 &ReportPlanArgs {
426 plan_id: plan_id.to_owned(),
427 token: body["token"].as_str().unwrap_or_default().to_owned(),
428 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
429 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
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 what its agent's run cost, so that the workspace
441/// it worked for is charged. As with checks, the run's own token is the
442/// credential.
443async fn report_usage(
444 request: &mut Request,
445 services: &Services,
446 run_id: &str,
447) -> Result<Response> {
448 let body = json_body(request).await;
449 let charged: Outcome<bool> = g1t_kit::call(
450 &services.billing,
451 "finish_run",
452 &FinishRunArgs {
453 run_id: run_id.to_owned(),
454 token: body["token"].as_str().unwrap_or_default().to_owned(),
455 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
456 turns: body["turns"].as_u64().unwrap_or_default() as u32,
457 },
458 )
459 .await?;
460 match charged {
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
API and MCP server in Rust; a public index at the API root466async fn respond(mut request: Request, env: &Env) -> Result<Response> {
467 let method = method_name(request.method());
468 if method == "OPTIONS" {
469 return Ok(Response::empty()?.with_status(204));
470 }
471 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell472 // Paths carry no version. An earlier form began with `/v1`, which is
473 // still accepted so that nothing already written against it breaks.
474 let path = match url.path().strip_prefix("/v1") {
475 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
476 _ => url.path().to_owned(),
477 };
478 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'479 // MCP is a host of its own hosted, and may be a path on this one
480 // self-hosted (addresses.rs).
481 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root482
Stripe webhooks, enterprise invoices, and sudo for both483 // Stripe reporting to billing. Signed with the secret of the endpoint
484 // billing registered; the body goes through exactly as received, since
485 // the signature covers its bytes.
486 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
487 return receive_stripe(&mut request, env).await;
488 }
489
Integrations: your own model provider, alerts that open issues, tickets agents read490 // Outside systems reporting to a connection. They sign what they send
491 // with the connection's own secret, which is not a g1t token, so this
492 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide493 if method == "POST" && !on_mcp
494 && 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 read495 return receive_hook(&mut request, &services, id).await;
496 }
497
Deployments: a preview for every pull request, production on g1t.page498 // A sandbox building a deployment, reporting with its build's token,
499 // which is not a g1t token. The body goes through as it is: it can
500 // carry a Worker's bundled code.
501 if method == "POST" && !on_mcp
502 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
503 {
504 let target = format!("https://deployments/jobs/{rest}");
505 let body = request.bytes().await?;
506 let headers = worker::Headers::new();
507 headers.set("content-type", "application/json")?;
508 let mut init = worker::RequestInit::new();
509 init.with_method(Method::Post)
510 .with_headers(headers)
511 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run512 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page513 .service("DEPLOYMENTS")?
514 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run515 .await?;
516 // A fresh response: a fetched one's headers cannot be changed, and
517 // every response gets the API's own on the way out.
518 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API519 let bytes = answer.bytes().await?;
520 let bytes = match serde_json::from_slice::<Value>(&bytes) {
521 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
522 Err(_) => bytes,
523 };
524 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run525 .with_status(status)
526 .with_headers({
527 let headers = worker::Headers::new();
528 headers.set("content-type", "application/json")?;
529 headers
530 }));
Deployments: a preview for every pull request, production on g1t.page531 }
532
A repository has its own sidebar, as settings do533 // A sandbox's artifacts and cache, with its job's token, which is not a
534 // g1t token either.
535 if !on_mcp
536 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents537 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do538 {
539 let rest = rest.to_owned();
540 return blobs::for_job(request, env, &services, method, &rest).await;
541 }
542
Fast pages, required checks on the branch, self-hosted runners, honest incidents543 // A self-hosted runner, with a registration token or its own
544 // credential, neither of which is a g1t access token.
545 if method == "POST"
546 && !on_mcp
547 && path.starts_with("/runners/")
548 && let Some(response) = runners::handle(&mut request, &services, &path).await?
549 {
550 return Ok(response);
551 }
552
API and MCP server in Rust; a public index at the API root553 let viewer = match authenticate(&request, &services).await? {
554 Ok(viewer) => viewer,
555 Err(refused) => return Ok(refused),
556 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API557 services.audit = audit::AuditContext::of(&request, on_mcp);
558 // An agent's token: what it may do comes with it, on the composite
559 // identity identity resolved it to.
560 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
561 services.scope = Some(acting.scope.clone());
562 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell563 let header = request.headers().get("authorization")?.unwrap_or_default();
564 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
565 let scope: Option<AgentScope> = g1t_kit::call(
566 &services.identity,
567 "agent_scope",
568 &TokenArgs {
569 token: token.to_owned(),
570 },
571 )
572 .await?;
573 // A scope is what lets an agent's token do anything at all.
574 let Some(scope) = scope else {
575 return fail(FailureCode::Unauthenticated, "Invalid access token.");
576 };
577 services.scope = Some(scope);
578 }
API and MCP server in Rust; a public index at the API root579 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
580 return Ok(response);
581 }
582 if on_mcp {
583 return mcp::handle(request, &services, &viewer).await;
584 }
585
586 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'587 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root588 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do589 // A run's artifacts: listed, or one downloaded.
590 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
591 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
592 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
593 return match rest {
594 [] => {
595 let seen: Outcome<Value> = g1t_kit::call(
596 &services.actions,
597 "run",
598 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
599 )
600 .await?;
601 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API602 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do603 Outcome::Fail(refused) => failure(&refused),
604 }
605 }
606 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
607 _ => fail(FailureCode::NotFound, "No such endpoint."),
608 };
609 }
610 }
Agents as a team: lifecycle, merge queue, billing and a new shell611 ("POST", "/device/code") => return device_code(&mut request, &services).await,
612 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically613 // Where a pull request lives, for a tool that knows only its fork.
614 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
615 let located: Outcome<Value> = g1t_kit::call(
616 &services.work,
617 "locate_pull",
618 &json!({ "id": &path[7..], "viewer": viewer }),
619 )
620 .await?;
621 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API622 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically623 Outcome::Fail(refused) => failure(&refused),
624 };
625 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains626 ("POST", path) if path.starts_with("/mergechecks/") => {
627 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
628 return report_mergecheck(&mut request, &services, &pull_id).await;
629 }
Merge branch 'worktree-agent-ac5b181a013e54348'630 // A sandbox making a repository's nightly backup. The job's own
631 // token, in its header, is the credential.
632 (method, path) if path.starts_with("/backups/") => {
633 return backup_job(&mut request, &services, method, path).await;
634 }
Agents as a team: lifecycle, merge queue, billing and a new shell635 ("POST", path) if path.starts_with("/queue/") => {
636 let entry_id = path.trim_start_matches("/queue/").to_owned();
637 return report_queue(&mut request, &services, &entry_id).await;
638 }
GitHub Actions on g1t, part two: running workflows639 // A sandbox running a GitHub Actions job: fetching the job, and
640 // reporting how it goes. The job's own token is the credential.
641 ("POST", path) if path.starts_with("/actions/jobs/") => {
642 let rest = path.trim_start_matches("/actions/jobs/");
643 let (job, method) = match rest.strip_suffix("/spec") {
644 Some(job) => (job.to_owned(), "job_spec"),
645 None => (rest.to_owned(), "job_report"),
646 };
647 let body = json_body(&mut request).await;
648 let answered: Outcome<Value> = g1t_kit::call(
649 &services.actions,
650 method,
651 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
652 )
653 .await?;
654 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API655 // A job's spec is the workflow and its contexts as GitHub
656 // has them; only g1t's own keys around them are converted.
657 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows658 Outcome::Fail(refused) => failure(&refused),
659 };
660 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains661 // A sandbox reporting its agent run's steps, cost and end. As with
662 // checks, the run's own token, in the body, is the credential.
663 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
664 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
665 let mut body = json_body(&mut request).await;
666 if !body.is_object() {
667 body = json!({});
668 }
669 body["runId"] = json!(run_id);
670 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
671 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API672 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains673 Outcome::Fail(refused) => failure(&refused),
674 };
675 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API676 // What a run's agent learned, as memory candidates; the same token.
677 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
678 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
679 let body = json_body(&mut request).await;
680 let learned = json!({
681 "runId": run_id,
682 "token": body["token"].as_str().unwrap_or_default(),
683 "items": body["items"].as_array().cloned().unwrap_or_default(),
684 });
685 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
686 return match captured {
687 Outcome::Ok(captured) => reply(&captured),
688 Outcome::Fail(refused) => failure(&refused),
689 };
690 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step691 // How sure a run's agent is of its change; the same token.
692 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
693 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
694 let body = json_body(&mut request).await;
695 let said = json!({
696 "runId": run_id,
697 "token": body["token"].as_str().unwrap_or_default(),
698 "confidence": body["confidence"].as_str().unwrap_or_default(),
699 "uncertainAbout": body["uncertain_about"]
700 .as_array()
701 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
702 .unwrap_or_default(),
703 });
704 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
705 return match recorded {
706 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
707 Outcome::Fail(refused) => failure(&refused),
708 };
709 }
Agents as a team: lifecycle, merge queue, billing and a new shell710 ("POST", path) if path.starts_with("/checks/") => {
711 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts712 return report_checks(&mut request, &services, &run_id).await;
713 }
Agents as a team: lifecycle, merge queue, billing and a new shell714 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
715 let run_id = path
716 .trim_start_matches("/runs/")
717 .trim_end_matches("/usage")
718 .to_owned();
719 return report_usage(&mut request, &services, &run_id).await;
720 }
721 ("POST", path) if path.starts_with("/plans/") => {
722 let plan_id = path.trim_start_matches("/plans/").to_owned();
723 return report_plan(&mut request, &services, &plan_id).await;
724 }
725 ("POST", path) if path.starts_with("/reviews/") => {
726 let run_id = path.trim_start_matches("/reviews/").to_owned();
727 return report_review(&mut request, &services, &run_id).await;
728 }
API and MCP server in Rust; a public index at the API root729 _ => {}
730 }
731
732 let query: Vec<(String, String)> = url
733 .query_pairs()
734 .map(|(name, value)| (name.into_owned(), value.into_owned()))
735 .collect();
736 let body = if method == "GET" {
737 Value::Null
738 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell739 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root740 };
741 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
742 return fail(FailureCode::NotFound, "No such endpoint.");
743 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API744 match audit::run(route.op, &services, &viewer, &input).await? {
745 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 step746 // A token without the scope a call needs is told which one.
747 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
748 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
749 "error": {
750 "code": refused.code,
751 "message": refused.message,
752 "needed_scope": scope.as_str(),
753 }
754 }))?
755 .with_status(403)),
756 _ => failure(&refused),
757 },
API and MCP server in Rust; a public index at the API root758 }
759}
760
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API761/// Request bodies take the same keys as the MCP tools, `snake_case`, as
762/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell763fn snake_case_keys(body: Value) -> Value {
764 let Value::Object(fields) = body else {
765 return body;
766 };
767 let mut out = serde_json::Map::new();
768 for (key, value) in fields {
769 let mut snake = String::with_capacity(key.len() + 4);
770 for c in key.chars() {
771 if c.is_ascii_uppercase() {
772 snake.push('_');
773 snake.push(c.to_ascii_lowercase());
774 } else {
775 snake.push(c);
776 }
777 }
778 // A key given in both spellings keeps the snake_case one.
779 if snake != key && out.contains_key(&snake) {
780 continue;
781 }
782 out.insert(snake, value);
783 }
784 Value::Object(out)
785}
786
787#[cfg(test)]
788mod tests {
789 use super::snake_case_keys;
790 use serde_json::json;
791
792 #[test]
793 fn camel_case_keys_are_accepted() {
794 assert_eq!(
795 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
796 json!({ "count_agent_approvals": false, "title": "x" })
797 );
798 }
799
800 #[test]
801 fn snake_case_wins_when_both_are_given() {
802 assert_eq!(
803 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
804 json!({ "keep_issue_open": true })
805 );
806 }
807}
808
API and MCP server in Rust; a public index at the API root809// The API is called from browsers too: the reference's explorer, and apps
810// built on g1t. It carries no cookies, so any origin may call it.
811#[event(fetch)]
812async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
813 let mut response = respond(request, &env).await?;
814 let headers = response.headers_mut();
815 headers.set("access-control-allow-origin", "*")?;
816 headers.set(
817 "access-control-allow-headers",
818 "authorization, content-type",
819 )?;
820 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
821 headers.set("access-control-expose-headers", "www-authenticate")?;
822 Ok(response)
823}

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