Skip to content

g1t/apps/api/src/lib.rs

824 lines34,393 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;
API: pinned projects over REST and MCP15mod pins;
API and MCP server in Rust; a public index at the API root16mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains17mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API18#[cfg(test)]
19mod responses;
API and MCP server in Rust; a public index at the API root20mod rest;
Fast pages, required checks on the branch, self-hosted runners, honest incidents21mod runners;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step22mod tools;
API and MCP server in Rust; a public index at the API root23
Agents as a team: lifecycle, merge queue, billing and a new shell24use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root25use g1t_contracts::identity::{
26 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
27};
Agents as a team: lifecycle, merge queue, billing and a new shell28use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains29 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
30 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell31};
32use g1t_contracts::identity::AgentScope;
33use 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 API34use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root35use serde_json::{Value, json};
36use worker::{Context, Env, Method, Request, Response, Result, event};
37
38use operations::Services;
39
40fn method_name(method: Method) -> &'static str {
41 match method {
42 Method::Get => "GET",
43 Method::Post => "POST",
44 Method::Patch => "PATCH",
45 Method::Put => "PUT",
46 Method::Delete => "DELETE",
47 Method::Options => "OPTIONS",
48 Method::Head => "HEAD",
49 _ => "OTHER",
50 }
51}
52
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API53/// A JSON response. Every body the API sends has its keys in `snake_case`;
54/// the contracts it passes through are `camelCase`, so they are converted
55/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
56/// the MCP protocol's own envelope keep the spelling their standards use.
57pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
58 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
59}
60
61/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
62/// workflow file, GitHub's contexts and event, and where to check out, all
63/// passed through as they are.
64const JOB_SPEC_AS_GIVEN: &[&str] = &[
65 "spec", "workflow", "github", "event", "contexts", "checkout",
66];
67
API and MCP server in Rust; a public index at the API root68/// An error in the shape every endpoint uses.
69fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API70 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root71}
72
73fn fail(code: FailureCode, message: &str) -> Result<Response> {
74 failure(&Failure {
75 code,
76 message: message.to_owned(),
77 })
78}
79
80/// A request body as JSON. An empty or malformed body is no input.
81async fn json_body(request: &mut Request) -> Value {
82 request.json().await.unwrap_or(Value::Null)
83}
84
85/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
86/// an anonymous viewer; a wrong one is refused, so that a typo does not
87/// silently look signed out.
88async fn authenticate(
89 request: &Request,
90 services: &Services,
91) -> Result<std::result::Result<Viewer, Response>> {
92 let header = request.headers().get("authorization")?.unwrap_or_default();
93 let token = match header.split_once(' ') {
94 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
95 token.trim()
96 }
97 _ => return Ok(Ok(None)),
98 };
99 let viewer: Viewer = g1t_kit::call(
100 &services.identity,
101 "user_for_access_token",
102 &TokenArgs {
103 token: token.to_owned(),
104 },
105 )
106 .await?;
107 if viewer.is_some() {
108 return Ok(Ok(viewer));
109 }
110 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
111 // Tells an MCP client where to sign in again.
112 response.headers_mut().set(
113 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'114 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root115 )?;
116 Ok(Err(response))
117}
118
119/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'120fn index(addresses: &addresses::Addresses) -> Value {
121 let api = &addresses.api;
122 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root123 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'124 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'125 "openapi_url": format!("{api}/openapi.json"),
126 "mcp_url": addresses.mcp,
127 "current_user_url": format!("{api}/user"),
128 "workspaces_url": format!("{api}/workspaces"),
129 "repositories_url": format!("{api}/repos{{?q}}"),
130 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root131 "repository_url": repo,
132 "repository_events_url": format!("{repo}/events{{?before}}"),
133 "labels_url": format!("{repo}/labels"),
134 "issues_url": format!("{repo}/issues{{?state,label}}"),
135 "issue_url": format!("{repo}/issues/{{number}}"),
136 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
137 "pulls_url": format!("{repo}/pulls{{?state}}"),
138 "pull_url": format!("{repo}/pulls/{{number}}"),
139 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts140 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root141 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'142 "device_code_url": format!("{api}/device/code"),
143 "device_token_url": format!("{api}/device/token"),
144 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
145 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
146 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read147 "context_url": format!("{repo}/context{{?reference}}"),
148 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'149 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root150 })
151}
152
153// Signing in from a tool. Accounts are created, and passwords typed, only
154// in a browser; a tool gets its token by having a person approve a code.
155
Integrations: your own model provider, alerts that open issues, tickets agents read156/// Passes a request from an outside system to its connection, as it came:
157/// its signature covers the exact bytes of the body.
158async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
159 let headers: std::collections::HashMap<String, String> = request
160 .headers()
161 .entries()
162 .map(|(name, value)| (name.to_lowercase(), value))
163 .collect();
164 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look165 // A push to GitHub with many commits makes a large payload.
166 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
167 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API168 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read169 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look170 // g1t's GitHub App has one webhook for every installation; it is
171 // checked against the app's own secret.
172 let (method, args) = if id == "github" {
173 ("github_receive", json!({ "headers": headers, "body": body }))
174 } else {
175 ("receive", json!({ "id": id, "headers": headers, "body": body }))
176 };
177 let received: g1t_contracts::integrations::Received =
178 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 API179 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read180}
181
Stripe webhooks, enterprise invoices, and sudo for both182async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
183 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
184 let payload = request.text().await.unwrap_or_default();
185 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 API186 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both187 }
188 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
189 &env.service("BILLING")?,
190 "stripe_webhook",
191 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
192 )
193 .await?;
194 // A refusal is a 400, so Stripe shows it as failed; anything handled,
195 // or already handled, is a 200, so Stripe stops sending it.
196 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API197 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both198 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API199 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both200 }
201 })
202}
203
API and MCP server in Rust; a public index at the API root204async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
205 let body = json_body(request).await;
206 let started: DeviceStart = g1t_kit::call(
207 &services.identity,
208 "device_start",
209 &DeviceStartArgs {
210 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
211 },
212 )
213 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API214 reply(&json!({
API and MCP server in Rust; a public index at the API root215 "device_code": started.device_code,
216 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'217 "verification_uri": format!("{}/device", services.addresses.site),
218 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root219 "expires_in": started.expires_in,
220 "interval": started.interval,
221 }))
222}
223
224async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
225 let body = json_body(request).await;
226 let claim: DeviceClaim = g1t_kit::call(
227 &services.identity,
228 "device_claim",
229 &DeviceClaimArgs {
230 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
231 },
232 )
233 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API234 reply(&match claim {
API and MCP server in Rust; a public index at the API root235 DeviceClaim::Approved { token, user } => json!({
236 "status": "approved",
237 "token": token,
238 "username": user.username,
239 "verified": user.verified,
240 }),
241 DeviceClaim::Pending => json!({ "status": "pending" }),
242 DeviceClaim::Denied => json!({ "status": "denied" }),
243 DeviceClaim::Expired => json!({ "status": "expired" }),
244 })
245}
246
Fast pages, required checks on the branch, self-hosted runners, honest incidents247/// A sandbox reporting on a run of an issue's commands, from before a pull
248/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts249/// The run's own token, in the body, is the credential: it was given to
250/// that sandbox and to nothing else.
251async fn report_checks(
252 request: &mut Request,
253 services: &Services,
254 run_id: &str,
255) -> Result<Response> {
256 let body = json_body(request).await;
257 let reported: Outcome<CheckRun> = g1t_kit::call(
258 &services.work,
259 "report_checks",
260 &ReportChecksArgs {
261 run_id: run_id.to_owned(),
262 token: body["token"].as_str().unwrap_or_default().to_owned(),
263 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
264 error: body["error"].as_str().map(str::to_owned),
265 skip: false,
266 },
267 )
268 .await?;
269 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API270 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts271 Outcome::Fail(refused) => failure(&refused),
272 }
273}
274
Agents as a team: lifecycle, merge queue, billing and a new shell275/// A sandbox reporting one tested state of a merge queue. As with checks,
276/// the entry's own token is the credential.
277async fn report_queue(
278 request: &mut Request,
279 services: &Services,
280 entry_id: &str,
281) -> Result<Response> {
282 let body = json_body(request).await;
283 let reported: Outcome<QueueState> = g1t_kit::call(
284 &services.work,
285 "report_queue",
286 &ReportQueueArgs {
287 entry_id: entry_id.to_owned(),
288 token: body["token"].as_str().unwrap_or_default().to_owned(),
289 combined_commit: body["combinedCommit"].as_str().map(str::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 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains293 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell294 },
295 )
296 .await?;
297 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API298 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell299 Outcome::Fail(refused) => failure(&refused),
300 }
301}
302
Agents and memory, checks and conflicts, profiles, slug renames, custom domains303/// A sandbox reporting whether a pull request merges cleanly. As with
304/// checks, the probe's own token is the credential.
305async fn report_mergecheck(
306 request: &mut Request,
307 services: &Services,
308 pull_id: &str,
309) -> Result<Response> {
310 let body = json_body(request).await;
311 let reported: Outcome<Mergeable> = g1t_kit::call(
312 &services.work,
313 "report_mergecheck",
314 &ReportMergecheckArgs {
315 pull_id: pull_id.to_owned(),
316 token: body["token"].as_str().unwrap_or_default().to_owned(),
317 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
318 error: body["error"].as_str().map(str::to_owned),
319 },
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!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains324 Outcome::Fail(refused) => failure(&refused),
325 }
326}
327
Merge branch 'worktree-agent-ac5b181a013e54348'328/// A backup's sandbox, passed on to the repos service, which holds the
329/// job (services/repos/src/backups.rs; the flow is in
330/// `g1t_contracts::backups`):
331///
332/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
333/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
334/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
335/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
336///
337/// Bodies are passed through as they are: snake_case already, and a
338/// bundle's refs are keyed by ref names, which must not be converted.
339async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
340 use g1t_contracts::backups::TOKEN_HEADER;
341 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
342 let rest = path.trim_start_matches("/backups/");
343 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
344 if job.is_empty() || token.is_empty() {
345 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
346 }
347 if method == "PUT" && action.starts_with("parts/") {
348 let bytes = request.bytes().await?;
349 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
350 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
351 }
352 let headers = worker::Headers::new();
353 headers.set(TOKEN_HEADER, &token)?;
354 let mut init = worker::RequestInit::new();
355 init.with_method(Method::Put)
356 .with_headers(headers)
357 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
358 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
359 let mut answered = services.repos.fetch_request(forwarded).await?;
360 return outcome_as_given(answered.json().await?);
361 }
362 let rpc = match (method, action) {
363 ("POST", "spec") => "backup_spec",
364 ("POST", "complete") => "backup_complete",
365 ("POST", "fail") => "backup_fail",
366 _ => return fail(FailureCode::NotFound, "No such endpoint."),
367 };
368 let mut body = json_body(request).await;
369 if !body.is_object() {
370 body = json!({});
371 }
372 body["job_id"] = json!(job);
373 body["token"] = json!(token);
374 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
375 outcome_as_given(answered)
376}
377
378/// An `Outcome` from a service whose keys are already the API's: the value,
379/// or the failure in the shape every endpoint uses.
380fn outcome_as_given(answered: Value) -> Result<Response> {
381 match serde_json::from_value::<Outcome<Value>>(answered)? {
382 Outcome::Ok(value) => Response::from_json(&value),
383 Outcome::Fail(refused) => failure(&refused),
384 }
385}
386
Agents as a team: lifecycle, merge queue, billing and a new shell387/// A sandbox reporting the review its agent wrote. As with checks, the
388/// run's own token is the credential.
389async fn report_review(
390 request: &mut Request,
391 services: &Services,
392 run_id: &str,
393) -> Result<Response> {
394 let body = json_body(request).await;
395 let reported: Outcome<bool> = g1t_kit::call(
396 &services.work,
397 "report_review",
398 &ReportReviewArgs {
399 run_id: run_id.to_owned(),
400 token: body["token"].as_str().unwrap_or_default().to_owned(),
401 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
402 body: body["body"].as_str().unwrap_or_default().to_owned(),
403 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
404 model: body["model"].as_str().map(str::to_owned),
405 error: body["error"].as_str().map(str::to_owned),
406 },
407 )
408 .await?;
409 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API410 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell411 Outcome::Fail(refused) => failure(&refused),
412 }
413}
414
415/// A sandbox reporting the plan its agent wrote. As with checks, the
416/// plan's own token is the credential.
417async fn report_plan(
418 request: &mut Request,
419 services: &Services,
420 plan_id: &str,
421) -> Result<Response> {
422 let body = json_body(request).await;
423 let reported: Outcome<bool> = g1t_kit::call(
424 &services.work,
425 "report_plan",
426 &ReportPlanArgs {
427 plan_id: plan_id.to_owned(),
428 token: body["token"].as_str().unwrap_or_default().to_owned(),
429 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
430 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
431 error: body["error"].as_str().map(str::to_owned),
432 },
433 )
434 .await?;
435 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API436 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell437 Outcome::Fail(refused) => failure(&refused),
438 }
439}
440
441/// A sandbox reporting what its agent's run cost, so that the workspace
442/// it worked for is charged. As with checks, the run's own token is the
443/// credential.
444async fn report_usage(
445 request: &mut Request,
446 services: &Services,
447 run_id: &str,
448) -> Result<Response> {
449 let body = json_body(request).await;
450 let charged: Outcome<bool> = g1t_kit::call(
451 &services.billing,
452 "finish_run",
453 &FinishRunArgs {
454 run_id: run_id.to_owned(),
455 token: body["token"].as_str().unwrap_or_default().to_owned(),
456 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
457 turns: body["turns"].as_u64().unwrap_or_default() as u32,
458 },
459 )
460 .await?;
461 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API462 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell463 Outcome::Fail(refused) => failure(&refused),
464 }
465}
466
API and MCP server in Rust; a public index at the API root467async fn respond(mut request: Request, env: &Env) -> Result<Response> {
468 let method = method_name(request.method());
469 if method == "OPTIONS" {
470 return Ok(Response::empty()?.with_status(204));
471 }
472 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell473 // Paths carry no version. An earlier form began with `/v1`, which is
474 // still accepted so that nothing already written against it breaks.
475 let path = match url.path().strip_prefix("/v1") {
476 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
477 _ => url.path().to_owned(),
478 };
479 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'480 // MCP is a host of its own hosted, and may be a path on this one
481 // self-hosted (addresses.rs).
482 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root483
Stripe webhooks, enterprise invoices, and sudo for both484 // Stripe reporting to billing. Signed with the secret of the endpoint
485 // billing registered; the body goes through exactly as received, since
486 // the signature covers its bytes.
487 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
488 return receive_stripe(&mut request, env).await;
489 }
490
Integrations: your own model provider, alerts that open issues, tickets agents read491 // Outside systems reporting to a connection. They sign what they send
492 // with the connection's own secret, which is not a g1t token, so this
493 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide494 if method == "POST" && !on_mcp
495 && 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 read496 return receive_hook(&mut request, &services, id).await;
497 }
498
Deployments: a preview for every pull request, production on g1t.page499 // A sandbox building a deployment, reporting with its build's token,
500 // which is not a g1t token. The body goes through as it is: it can
501 // carry a Worker's bundled code.
502 if method == "POST" && !on_mcp
503 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
504 {
505 let target = format!("https://deployments/jobs/{rest}");
506 let body = request.bytes().await?;
507 let headers = worker::Headers::new();
508 headers.set("content-type", "application/json")?;
509 let mut init = worker::RequestInit::new();
510 init.with_method(Method::Post)
511 .with_headers(headers)
512 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run513 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page514 .service("DEPLOYMENTS")?
515 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run516 .await?;
517 // A fresh response: a fetched one's headers cannot be changed, and
518 // every response gets the API's own on the way out.
519 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API520 let bytes = answer.bytes().await?;
521 let bytes = match serde_json::from_slice::<Value>(&bytes) {
522 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
523 Err(_) => bytes,
524 };
525 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run526 .with_status(status)
527 .with_headers({
528 let headers = worker::Headers::new();
529 headers.set("content-type", "application/json")?;
530 headers
531 }));
Deployments: a preview for every pull request, production on g1t.page532 }
533
A repository has its own sidebar, as settings do534 // A sandbox's artifacts and cache, with its job's token, which is not a
535 // g1t token either.
536 if !on_mcp
537 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents538 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do539 {
540 let rest = rest.to_owned();
541 return blobs::for_job(request, env, &services, method, &rest).await;
542 }
543
Fast pages, required checks on the branch, self-hosted runners, honest incidents544 // A self-hosted runner, with a registration token or its own
545 // credential, neither of which is a g1t access token.
546 if method == "POST"
547 && !on_mcp
548 && path.starts_with("/runners/")
549 && let Some(response) = runners::handle(&mut request, &services, &path).await?
550 {
551 return Ok(response);
552 }
553
API and MCP server in Rust; a public index at the API root554 let viewer = match authenticate(&request, &services).await? {
555 Ok(viewer) => viewer,
556 Err(refused) => return Ok(refused),
557 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API558 services.audit = audit::AuditContext::of(&request, on_mcp);
559 // An agent's token: what it may do comes with it, on the composite
560 // identity identity resolved it to.
561 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
562 services.scope = Some(acting.scope.clone());
563 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell564 let header = request.headers().get("authorization")?.unwrap_or_default();
565 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
566 let scope: Option<AgentScope> = g1t_kit::call(
567 &services.identity,
568 "agent_scope",
569 &TokenArgs {
570 token: token.to_owned(),
571 },
572 )
573 .await?;
574 // A scope is what lets an agent's token do anything at all.
575 let Some(scope) = scope else {
576 return fail(FailureCode::Unauthenticated, "Invalid access token.");
577 };
578 services.scope = Some(scope);
579 }
API and MCP server in Rust; a public index at the API root580 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
581 return Ok(response);
582 }
583 if on_mcp {
584 return mcp::handle(request, &services, &viewer).await;
585 }
586
587 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'588 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root589 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do590 // A run's artifacts: listed, or one downloaded.
591 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
592 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
593 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
594 return match rest {
595 [] => {
596 let seen: Outcome<Value> = g1t_kit::call(
597 &services.actions,
598 "run",
599 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
600 )
601 .await?;
602 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API603 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do604 Outcome::Fail(refused) => failure(&refused),
605 }
606 }
607 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
608 _ => fail(FailureCode::NotFound, "No such endpoint."),
609 };
610 }
611 }
Agents as a team: lifecycle, merge queue, billing and a new shell612 ("POST", "/device/code") => return device_code(&mut request, &services).await,
613 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically614 // Where a pull request lives, for a tool that knows only its fork.
615 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
616 let located: Outcome<Value> = g1t_kit::call(
617 &services.work,
618 "locate_pull",
619 &json!({ "id": &path[7..], "viewer": viewer }),
620 )
621 .await?;
622 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API623 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically624 Outcome::Fail(refused) => failure(&refused),
625 };
626 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains627 ("POST", path) if path.starts_with("/mergechecks/") => {
628 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
629 return report_mergecheck(&mut request, &services, &pull_id).await;
630 }
Merge branch 'worktree-agent-ac5b181a013e54348'631 // A sandbox making a repository's nightly backup. The job's own
632 // token, in its header, is the credential.
633 (method, path) if path.starts_with("/backups/") => {
634 return backup_job(&mut request, &services, method, path).await;
635 }
Agents as a team: lifecycle, merge queue, billing and a new shell636 ("POST", path) if path.starts_with("/queue/") => {
637 let entry_id = path.trim_start_matches("/queue/").to_owned();
638 return report_queue(&mut request, &services, &entry_id).await;
639 }
GitHub Actions on g1t, part two: running workflows640 // A sandbox running a GitHub Actions job: fetching the job, and
641 // reporting how it goes. The job's own token is the credential.
642 ("POST", path) if path.starts_with("/actions/jobs/") => {
643 let rest = path.trim_start_matches("/actions/jobs/");
644 let (job, method) = match rest.strip_suffix("/spec") {
645 Some(job) => (job.to_owned(), "job_spec"),
646 None => (rest.to_owned(), "job_report"),
647 };
648 let body = json_body(&mut request).await;
649 let answered: Outcome<Value> = g1t_kit::call(
650 &services.actions,
651 method,
652 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
653 )
654 .await?;
655 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API656 // A job's spec is the workflow and its contexts as GitHub
657 // has them; only g1t's own keys around them are converted.
658 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows659 Outcome::Fail(refused) => failure(&refused),
660 };
661 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains662 // A sandbox reporting its agent run's steps, cost and end. As with
663 // checks, the run's own token, in the body, is the credential.
664 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
665 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
666 let mut body = json_body(&mut request).await;
667 if !body.is_object() {
668 body = json!({});
669 }
670 body["runId"] = json!(run_id);
671 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
672 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API673 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains674 Outcome::Fail(refused) => failure(&refused),
675 };
676 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API677 // What a run's agent learned, as memory candidates; the same token.
678 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
679 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
680 let body = json_body(&mut request).await;
681 let learned = json!({
682 "runId": run_id,
683 "token": body["token"].as_str().unwrap_or_default(),
684 "items": body["items"].as_array().cloned().unwrap_or_default(),
685 });
686 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
687 return match captured {
688 Outcome::Ok(captured) => reply(&captured),
689 Outcome::Fail(refused) => failure(&refused),
690 };
691 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step692 // How sure a run's agent is of its change; the same token.
693 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
694 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
695 let body = json_body(&mut request).await;
696 let said = json!({
697 "runId": run_id,
698 "token": body["token"].as_str().unwrap_or_default(),
699 "confidence": body["confidence"].as_str().unwrap_or_default(),
700 "uncertainAbout": body["uncertain_about"]
701 .as_array()
702 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
703 .unwrap_or_default(),
704 });
705 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
706 return match recorded {
707 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
708 Outcome::Fail(refused) => failure(&refused),
709 };
710 }
Agents as a team: lifecycle, merge queue, billing and a new shell711 ("POST", path) if path.starts_with("/checks/") => {
712 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts713 return report_checks(&mut request, &services, &run_id).await;
714 }
Agents as a team: lifecycle, merge queue, billing and a new shell715 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
716 let run_id = path
717 .trim_start_matches("/runs/")
718 .trim_end_matches("/usage")
719 .to_owned();
720 return report_usage(&mut request, &services, &run_id).await;
721 }
722 ("POST", path) if path.starts_with("/plans/") => {
723 let plan_id = path.trim_start_matches("/plans/").to_owned();
724 return report_plan(&mut request, &services, &plan_id).await;
725 }
726 ("POST", path) if path.starts_with("/reviews/") => {
727 let run_id = path.trim_start_matches("/reviews/").to_owned();
728 return report_review(&mut request, &services, &run_id).await;
729 }
API and MCP server in Rust; a public index at the API root730 _ => {}
731 }
732
733 let query: Vec<(String, String)> = url
734 .query_pairs()
735 .map(|(name, value)| (name.into_owned(), value.into_owned()))
736 .collect();
737 let body = if method == "GET" {
738 Value::Null
739 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell740 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root741 };
742 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
743 return fail(FailureCode::NotFound, "No such endpoint.");
744 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API745 match audit::run(route.op, &services, &viewer, &input).await? {
746 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 step747 // A token without the scope a call needs is told which one.
748 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
749 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
750 "error": {
751 "code": refused.code,
752 "message": refused.message,
753 "needed_scope": scope.as_str(),
754 }
755 }))?
756 .with_status(403)),
757 _ => failure(&refused),
758 },
API and MCP server in Rust; a public index at the API root759 }
760}
761
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API762/// Request bodies take the same keys as the MCP tools, `snake_case`, as
763/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell764fn snake_case_keys(body: Value) -> Value {
765 let Value::Object(fields) = body else {
766 return body;
767 };
768 let mut out = serde_json::Map::new();
769 for (key, value) in fields {
770 let mut snake = String::with_capacity(key.len() + 4);
771 for c in key.chars() {
772 if c.is_ascii_uppercase() {
773 snake.push('_');
774 snake.push(c.to_ascii_lowercase());
775 } else {
776 snake.push(c);
777 }
778 }
779 // A key given in both spellings keeps the snake_case one.
780 if snake != key && out.contains_key(&snake) {
781 continue;
782 }
783 out.insert(snake, value);
784 }
785 Value::Object(out)
786}
787
788#[cfg(test)]
789mod tests {
790 use super::snake_case_keys;
791 use serde_json::json;
792
793 #[test]
794 fn camel_case_keys_are_accepted() {
795 assert_eq!(
796 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
797 json!({ "count_agent_approvals": false, "title": "x" })
798 );
799 }
800
801 #[test]
802 fn snake_case_wins_when_both_are_given() {
803 assert_eq!(
804 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
805 json!({ "keep_issue_open": true })
806 );
807 }
808}
809
API and MCP server in Rust; a public index at the API root810// The API is called from browsers too: the reference's explorer, and apps
811// built on g1t. It carries no cookies, so any origin may call it.
812#[event(fetch)]
813async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
814 let mut response = respond(request, &env).await?;
815 let headers = response.headers_mut();
816 headers.set("access-control-allow-origin", "*")?;
817 headers.set(
818 "access-control-allow-headers",
819 "authorization, content-type",
820 )?;
821 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
822 headers.set("access-control-expose-headers", "www-authenticate")?;
823 Ok(response)
824}

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