g1t/apps/api/src/lib.rs

822 lines34,364 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;
12mod oauth;
13mod openapi;
14mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains15mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API16#[cfg(test)]
17mod responses;
API and MCP server in Rust; a public index at the API root18mod rest;
Fast pages, required checks on the branch, self-hosted runners, honest incidents19mod runners;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step20mod tools;
API and MCP server in Rust; a public index at the API root21
Agents as a team: lifecycle, merge queue, billing and a new shell22use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root23use g1t_contracts::identity::{
24 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
25};
Agents as a team: lifecycle, merge queue, billing and a new shell26use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains27 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
28 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell29};
30use g1t_contracts::identity::AgentScope;
31use 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 API32use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root33use serde_json::{Value, json};
34use worker::{Context, Env, Method, Request, Response, Result, event};
35
36use operations::Services;
37
38fn method_name(method: Method) -> &'static str {
39 match method {
40 Method::Get => "GET",
41 Method::Post => "POST",
42 Method::Patch => "PATCH",
43 Method::Put => "PUT",
44 Method::Delete => "DELETE",
45 Method::Options => "OPTIONS",
46 Method::Head => "HEAD",
47 _ => "OTHER",
48 }
49}
50
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API51/// A JSON response. Every body the API sends has its keys in `snake_case`;
52/// the contracts it passes through are `camelCase`, so they are converted
53/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
54/// the MCP protocol's own envelope keep the spelling their standards use.
55pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
56 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
57}
58
59/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
60/// workflow file, GitHub's contexts and event, and where to check out, all
61/// passed through as they are.
62const JOB_SPEC_AS_GIVEN: &[&str] = &[
63 "spec", "workflow", "github", "event", "contexts", "checkout",
64];
65
API and MCP server in Rust; a public index at the API root66/// An error in the shape every endpoint uses.
67fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API68 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root69}
70
71fn fail(code: FailureCode, message: &str) -> Result<Response> {
72 failure(&Failure {
73 code,
74 message: message.to_owned(),
75 })
76}
77
78/// A request body as JSON. An empty or malformed body is no input.
79async fn json_body(request: &mut Request) -> Value {
80 request.json().await.unwrap_or(Value::Null)
81}
82
83/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
84/// an anonymous viewer; a wrong one is refused, so that a typo does not
85/// silently look signed out.
86async fn authenticate(
87 request: &Request,
88 services: &Services,
89) -> Result<std::result::Result<Viewer, Response>> {
90 let header = request.headers().get("authorization")?.unwrap_or_default();
91 let token = match header.split_once(' ') {
92 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
93 token.trim()
94 }
95 _ => return Ok(Ok(None)),
96 };
97 let viewer: Viewer = g1t_kit::call(
98 &services.identity,
99 "user_for_access_token",
100 &TokenArgs {
101 token: token.to_owned(),
102 },
103 )
104 .await?;
105 if viewer.is_some() {
106 return Ok(Ok(viewer));
107 }
108 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
109 // Tells an MCP client where to sign in again.
110 response.headers_mut().set(
111 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'112 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root113 )?;
114 Ok(Err(response))
115}
116
117/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'118fn index(addresses: &addresses::Addresses) -> Value {
119 let api = &addresses.api;
120 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root121 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'122 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'123 "openapi_url": format!("{api}/openapi.json"),
124 "mcp_url": addresses.mcp,
125 "current_user_url": format!("{api}/user"),
126 "workspaces_url": format!("{api}/workspaces"),
127 "repositories_url": format!("{api}/repos{{?q}}"),
128 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root129 "repository_url": repo,
130 "repository_events_url": format!("{repo}/events{{?before}}"),
131 "labels_url": format!("{repo}/labels"),
132 "issues_url": format!("{repo}/issues{{?state,label}}"),
133 "issue_url": format!("{repo}/issues/{{number}}"),
134 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
135 "pulls_url": format!("{repo}/pulls{{?state}}"),
136 "pull_url": format!("{repo}/pulls/{{number}}"),
137 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts138 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root139 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'140 "device_code_url": format!("{api}/device/code"),
141 "device_token_url": format!("{api}/device/token"),
142 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
143 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
144 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read145 "context_url": format!("{repo}/context{{?reference}}"),
146 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'147 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root148 })
149}
150
151// Signing in from a tool. Accounts are created, and passwords typed, only
152// in a browser; a tool gets its token by having a person approve a code.
153
Integrations: your own model provider, alerts that open issues, tickets agents read154/// Passes a request from an outside system to its connection, as it came:
155/// its signature covers the exact bytes of the body.
156async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
157 let headers: std::collections::HashMap<String, String> = request
158 .headers()
159 .entries()
160 .map(|(name, value)| (name.to_lowercase(), value))
161 .collect();
162 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look163 // A push to GitHub with many commits makes a large payload.
164 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
165 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API166 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read167 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look168 // g1t's GitHub App has one webhook for every installation; it is
169 // checked against the app's own secret.
170 let (method, args) = if id == "github" {
171 ("github_receive", json!({ "headers": headers, "body": body }))
172 } else {
173 ("receive", json!({ "id": id, "headers": headers, "body": body }))
174 };
175 let received: g1t_contracts::integrations::Received =
176 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 API177 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read178}
179
Stripe webhooks, enterprise invoices, and sudo for both180async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
181 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
182 let payload = request.text().await.unwrap_or_default();
183 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 API184 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both185 }
186 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
187 &env.service("BILLING")?,
188 "stripe_webhook",
189 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
190 )
191 .await?;
192 // A refusal is a 400, so Stripe shows it as failed; anything handled,
193 // or already handled, is a 200, so Stripe stops sending it.
194 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API195 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both196 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API197 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both198 }
199 })
200}
201
API and MCP server in Rust; a public index at the API root202async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
203 let body = json_body(request).await;
204 let started: DeviceStart = g1t_kit::call(
205 &services.identity,
206 "device_start",
207 &DeviceStartArgs {
208 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
209 },
210 )
211 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API212 reply(&json!({
API and MCP server in Rust; a public index at the API root213 "device_code": started.device_code,
214 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'215 "verification_uri": format!("{}/device", services.addresses.site),
216 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root217 "expires_in": started.expires_in,
218 "interval": started.interval,
219 }))
220}
221
222async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
223 let body = json_body(request).await;
224 let claim: DeviceClaim = g1t_kit::call(
225 &services.identity,
226 "device_claim",
227 &DeviceClaimArgs {
228 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
229 },
230 )
231 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API232 reply(&match claim {
API and MCP server in Rust; a public index at the API root233 DeviceClaim::Approved { token, user } => json!({
234 "status": "approved",
235 "token": token,
236 "username": user.username,
237 "verified": user.verified,
238 }),
239 DeviceClaim::Pending => json!({ "status": "pending" }),
240 DeviceClaim::Denied => json!({ "status": "denied" }),
241 DeviceClaim::Expired => json!({ "status": "expired" }),
242 })
243}
244
Fast pages, required checks on the branch, self-hosted runners, honest incidents245/// A sandbox reporting on a run of an issue's commands, from before a pull
246/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts247/// The run's own token, in the body, is the credential: it was given to
248/// that sandbox and to nothing else.
249async fn report_checks(
250 request: &mut Request,
251 services: &Services,
252 run_id: &str,
253) -> Result<Response> {
254 let body = json_body(request).await;
255 let reported: Outcome<CheckRun> = g1t_kit::call(
256 &services.work,
257 "report_checks",
258 &ReportChecksArgs {
259 run_id: run_id.to_owned(),
260 token: body["token"].as_str().unwrap_or_default().to_owned(),
261 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
262 error: body["error"].as_str().map(str::to_owned),
263 skip: false,
264 },
265 )
266 .await?;
267 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API268 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts269 Outcome::Fail(refused) => failure(&refused),
270 }
271}
272
Agents as a team: lifecycle, merge queue, billing and a new shell273/// A sandbox reporting one tested state of a merge queue. As with checks,
274/// the entry's own token is the credential.
275async fn report_queue(
276 request: &mut Request,
277 services: &Services,
278 entry_id: &str,
279) -> Result<Response> {
280 let body = json_body(request).await;
281 let reported: Outcome<QueueState> = g1t_kit::call(
282 &services.work,
283 "report_queue",
284 &ReportQueueArgs {
285 entry_id: entry_id.to_owned(),
286 token: body["token"].as_str().unwrap_or_default().to_owned(),
287 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
288 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
289 error: body["error"].as_str().map(str::to_owned),
290 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains291 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell292 },
293 )
294 .await?;
295 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API296 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell297 Outcome::Fail(refused) => failure(&refused),
298 }
299}
300
Agents and memory, checks and conflicts, profiles, slug renames, custom domains301/// A sandbox reporting whether a pull request merges cleanly. As with
302/// checks, the probe's own token is the credential.
303async fn report_mergecheck(
304 request: &mut Request,
305 services: &Services,
306 pull_id: &str,
307) -> Result<Response> {
308 let body = json_body(request).await;
309 let reported: Outcome<Mergeable> = g1t_kit::call(
310 &services.work,
311 "report_mergecheck",
312 &ReportMergecheckArgs {
313 pull_id: pull_id.to_owned(),
314 token: body["token"].as_str().unwrap_or_default().to_owned(),
315 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
316 error: body["error"].as_str().map(str::to_owned),
317 },
318 )
319 .await?;
320 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API321 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains322 Outcome::Fail(refused) => failure(&refused),
323 }
324}
325
Merge branch 'worktree-agent-ac5b181a013e54348'326/// A backup's sandbox, passed on to the repos service, which holds the
327/// job (services/repos/src/backups.rs; the flow is in
328/// `g1t_contracts::backups`):
329///
330/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
331/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
332/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
333/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
334///
335/// Bodies are passed through as they are: snake_case already, and a
336/// bundle's refs are keyed by ref names, which must not be converted.
337async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
338 use g1t_contracts::backups::TOKEN_HEADER;
339 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
340 let rest = path.trim_start_matches("/backups/");
341 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
342 if job.is_empty() || token.is_empty() {
343 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
344 }
345 if method == "PUT" && action.starts_with("parts/") {
346 let bytes = request.bytes().await?;
347 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
348 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
349 }
350 let headers = worker::Headers::new();
351 headers.set(TOKEN_HEADER, &token)?;
352 let mut init = worker::RequestInit::new();
353 init.with_method(Method::Put)
354 .with_headers(headers)
355 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
356 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
357 let mut answered = services.repos.fetch_request(forwarded).await?;
358 return outcome_as_given(answered.json().await?);
359 }
360 let rpc = match (method, action) {
361 ("POST", "spec") => "backup_spec",
362 ("POST", "complete") => "backup_complete",
363 ("POST", "fail") => "backup_fail",
364 _ => return fail(FailureCode::NotFound, "No such endpoint."),
365 };
366 let mut body = json_body(request).await;
367 if !body.is_object() {
368 body = json!({});
369 }
370 body["job_id"] = json!(job);
371 body["token"] = json!(token);
372 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
373 outcome_as_given(answered)
374}
375
376/// An `Outcome` from a service whose keys are already the API's: the value,
377/// or the failure in the shape every endpoint uses.
378fn outcome_as_given(answered: Value) -> Result<Response> {
379 match serde_json::from_value::<Outcome<Value>>(answered)? {
380 Outcome::Ok(value) => Response::from_json(&value),
381 Outcome::Fail(refused) => failure(&refused),
382 }
383}
384
Agents as a team: lifecycle, merge queue, billing and a new shell385/// A sandbox reporting the review its agent wrote. As with checks, the
386/// run's own token is the credential.
387async fn report_review(
388 request: &mut Request,
389 services: &Services,
390 run_id: &str,
391) -> Result<Response> {
392 let body = json_body(request).await;
393 let reported: Outcome<bool> = g1t_kit::call(
394 &services.work,
395 "report_review",
396 &ReportReviewArgs {
397 run_id: run_id.to_owned(),
398 token: body["token"].as_str().unwrap_or_default().to_owned(),
399 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
400 body: body["body"].as_str().unwrap_or_default().to_owned(),
401 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
402 model: body["model"].as_str().map(str::to_owned),
403 error: body["error"].as_str().map(str::to_owned),
404 },
405 )
406 .await?;
407 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API408 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell409 Outcome::Fail(refused) => failure(&refused),
410 }
411}
412
413/// A sandbox reporting the plan its agent wrote. As with checks, the
414/// plan's own token is the credential.
415async fn report_plan(
416 request: &mut Request,
417 services: &Services,
418 plan_id: &str,
419) -> Result<Response> {
420 let body = json_body(request).await;
421 let reported: Outcome<bool> = g1t_kit::call(
422 &services.work,
423 "report_plan",
424 &ReportPlanArgs {
425 plan_id: plan_id.to_owned(),
426 token: body["token"].as_str().unwrap_or_default().to_owned(),
427 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
428 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
429 error: body["error"].as_str().map(str::to_owned),
430 },
431 )
432 .await?;
433 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API434 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell435 Outcome::Fail(refused) => failure(&refused),
436 }
437}
438
439/// A sandbox reporting what its agent's run cost, so that the workspace
440/// it worked for is charged. As with checks, the run's own token is the
441/// credential.
442async fn report_usage(
443 request: &mut Request,
444 services: &Services,
445 run_id: &str,
446) -> Result<Response> {
447 let body = json_body(request).await;
448 let charged: Outcome<bool> = g1t_kit::call(
449 &services.billing,
450 "finish_run",
451 &FinishRunArgs {
452 run_id: run_id.to_owned(),
453 token: body["token"].as_str().unwrap_or_default().to_owned(),
454 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
455 turns: body["turns"].as_u64().unwrap_or_default() as u32,
456 },
457 )
458 .await?;
459 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API460 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell461 Outcome::Fail(refused) => failure(&refused),
462 }
463}
464
API and MCP server in Rust; a public index at the API root465async fn respond(mut request: Request, env: &Env) -> Result<Response> {
466 let method = method_name(request.method());
467 if method == "OPTIONS" {
468 return Ok(Response::empty()?.with_status(204));
469 }
470 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell471 // Paths carry no version. An earlier form began with `/v1`, which is
472 // still accepted so that nothing already written against it breaks.
473 let path = match url.path().strip_prefix("/v1") {
474 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
475 _ => url.path().to_owned(),
476 };
477 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'478 // MCP is a host of its own hosted, and may be a path on this one
479 // self-hosted (addresses.rs).
480 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root481
Stripe webhooks, enterprise invoices, and sudo for both482 // Stripe reporting to billing. Signed with the secret of the endpoint
483 // billing registered; the body goes through exactly as received, since
484 // the signature covers its bytes.
485 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
486 return receive_stripe(&mut request, env).await;
487 }
488
Integrations: your own model provider, alerts that open issues, tickets agents read489 // Outside systems reporting to a connection. They sign what they send
490 // with the connection's own secret, which is not a g1t token, so this
491 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide492 if method == "POST" && !on_mcp
493 && 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 read494 return receive_hook(&mut request, &services, id).await;
495 }
496
Deployments: a preview for every pull request, production on g1t.page497 // A sandbox building a deployment, reporting with its build's token,
498 // which is not a g1t token. The body goes through as it is: it can
499 // carry a Worker's bundled code.
500 if method == "POST" && !on_mcp
501 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
502 {
503 let target = format!("https://deployments/jobs/{rest}");
504 let body = request.bytes().await?;
505 let headers = worker::Headers::new();
506 headers.set("content-type", "application/json")?;
507 let mut init = worker::RequestInit::new();
508 init.with_method(Method::Post)
509 .with_headers(headers)
510 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run511 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page512 .service("DEPLOYMENTS")?
513 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run514 .await?;
515 // A fresh response: a fetched one's headers cannot be changed, and
516 // every response gets the API's own on the way out.
517 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API518 let bytes = answer.bytes().await?;
519 let bytes = match serde_json::from_slice::<Value>(&bytes) {
520 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
521 Err(_) => bytes,
522 };
523 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run524 .with_status(status)
525 .with_headers({
526 let headers = worker::Headers::new();
527 headers.set("content-type", "application/json")?;
528 headers
529 }));
Deployments: a preview for every pull request, production on g1t.page530 }
531
A repository has its own sidebar, as settings do532 // A sandbox's artifacts and cache, with its job's token, which is not a
533 // g1t token either.
534 if !on_mcp
535 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents536 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do537 {
538 let rest = rest.to_owned();
539 return blobs::for_job(request, env, &services, method, &rest).await;
540 }
541
Fast pages, required checks on the branch, self-hosted runners, honest incidents542 // A self-hosted runner, with a registration token or its own
543 // credential, neither of which is a g1t access token.
544 if method == "POST"
545 && !on_mcp
546 && path.starts_with("/runners/")
547 && let Some(response) = runners::handle(&mut request, &services, &path).await?
548 {
549 return Ok(response);
550 }
551
API and MCP server in Rust; a public index at the API root552 let viewer = match authenticate(&request, &services).await? {
553 Ok(viewer) => viewer,
554 Err(refused) => return Ok(refused),
555 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API556 services.audit = audit::AuditContext::of(&request, on_mcp);
557 // An agent's token: what it may do comes with it, on the composite
558 // identity identity resolved it to.
559 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
560 services.scope = Some(acting.scope.clone());
561 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell562 let header = request.headers().get("authorization")?.unwrap_or_default();
563 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
564 let scope: Option<AgentScope> = g1t_kit::call(
565 &services.identity,
566 "agent_scope",
567 &TokenArgs {
568 token: token.to_owned(),
569 },
570 )
571 .await?;
572 // A scope is what lets an agent's token do anything at all.
573 let Some(scope) = scope else {
574 return fail(FailureCode::Unauthenticated, "Invalid access token.");
575 };
576 services.scope = Some(scope);
577 }
API and MCP server in Rust; a public index at the API root578 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
579 return Ok(response);
580 }
581 if on_mcp {
582 return mcp::handle(request, &services, &viewer).await;
583 }
584
585 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'586 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root587 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do588 // A run's artifacts: listed, or one downloaded.
589 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
590 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
591 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
592 return match rest {
593 [] => {
594 let seen: Outcome<Value> = g1t_kit::call(
595 &services.actions,
596 "run",
597 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
598 )
599 .await?;
600 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API601 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do602 Outcome::Fail(refused) => failure(&refused),
603 }
604 }
605 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
606 _ => fail(FailureCode::NotFound, "No such endpoint."),
607 };
608 }
609 }
Agents as a team: lifecycle, merge queue, billing and a new shell610 ("POST", "/device/code") => return device_code(&mut request, &services).await,
611 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically612 // Where a pull request lives, for a tool that knows only its fork.
613 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
614 let located: Outcome<Value> = g1t_kit::call(
615 &services.work,
616 "locate_pull",
617 &json!({ "id": &path[7..], "viewer": viewer }),
618 )
619 .await?;
620 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API621 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically622 Outcome::Fail(refused) => failure(&refused),
623 };
624 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains625 ("POST", path) if path.starts_with("/mergechecks/") => {
626 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
627 return report_mergecheck(&mut request, &services, &pull_id).await;
628 }
Merge branch 'worktree-agent-ac5b181a013e54348'629 // A sandbox making a repository's nightly backup. The job's own
630 // token, in its header, is the credential.
631 (method, path) if path.starts_with("/backups/") => {
632 return backup_job(&mut request, &services, method, path).await;
633 }
Agents as a team: lifecycle, merge queue, billing and a new shell634 ("POST", path) if path.starts_with("/queue/") => {
635 let entry_id = path.trim_start_matches("/queue/").to_owned();
636 return report_queue(&mut request, &services, &entry_id).await;
637 }
GitHub Actions on g1t, part two: running workflows638 // A sandbox running a GitHub Actions job: fetching the job, and
639 // reporting how it goes. The job's own token is the credential.
640 ("POST", path) if path.starts_with("/actions/jobs/") => {
641 let rest = path.trim_start_matches("/actions/jobs/");
642 let (job, method) = match rest.strip_suffix("/spec") {
643 Some(job) => (job.to_owned(), "job_spec"),
644 None => (rest.to_owned(), "job_report"),
645 };
646 let body = json_body(&mut request).await;
647 let answered: Outcome<Value> = g1t_kit::call(
648 &services.actions,
649 method,
650 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
651 )
652 .await?;
653 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API654 // A job's spec is the workflow and its contexts as GitHub
655 // has them; only g1t's own keys around them are converted.
656 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows657 Outcome::Fail(refused) => failure(&refused),
658 };
659 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains660 // A sandbox reporting its agent run's steps, cost and end. As with
661 // checks, the run's own token, in the body, is the credential.
662 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
663 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
664 let mut body = json_body(&mut request).await;
665 if !body.is_object() {
666 body = json!({});
667 }
668 body["runId"] = json!(run_id);
669 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
670 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API671 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains672 Outcome::Fail(refused) => failure(&refused),
673 };
674 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API675 // What a run's agent learned, as memory candidates; the same token.
676 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
677 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
678 let body = json_body(&mut request).await;
679 let learned = json!({
680 "runId": run_id,
681 "token": body["token"].as_str().unwrap_or_default(),
682 "items": body["items"].as_array().cloned().unwrap_or_default(),
683 });
684 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
685 return match captured {
686 Outcome::Ok(captured) => reply(&captured),
687 Outcome::Fail(refused) => failure(&refused),
688 };
689 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step690 // How sure a run's agent is of its change; the same token.
691 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
692 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
693 let body = json_body(&mut request).await;
694 let said = json!({
695 "runId": run_id,
696 "token": body["token"].as_str().unwrap_or_default(),
697 "confidence": body["confidence"].as_str().unwrap_or_default(),
698 "uncertainAbout": body["uncertain_about"]
699 .as_array()
700 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
701 .unwrap_or_default(),
702 });
703 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
704 return match recorded {
705 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
706 Outcome::Fail(refused) => failure(&refused),
707 };
708 }
Agents as a team: lifecycle, merge queue, billing and a new shell709 ("POST", path) if path.starts_with("/checks/") => {
710 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts711 return report_checks(&mut request, &services, &run_id).await;
712 }
Agents as a team: lifecycle, merge queue, billing and a new shell713 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
714 let run_id = path
715 .trim_start_matches("/runs/")
716 .trim_end_matches("/usage")
717 .to_owned();
718 return report_usage(&mut request, &services, &run_id).await;
719 }
720 ("POST", path) if path.starts_with("/plans/") => {
721 let plan_id = path.trim_start_matches("/plans/").to_owned();
722 return report_plan(&mut request, &services, &plan_id).await;
723 }
724 ("POST", path) if path.starts_with("/reviews/") => {
725 let run_id = path.trim_start_matches("/reviews/").to_owned();
726 return report_review(&mut request, &services, &run_id).await;
727 }
API and MCP server in Rust; a public index at the API root728 _ => {}
729 }
730
731 let query: Vec<(String, String)> = url
732 .query_pairs()
733 .map(|(name, value)| (name.into_owned(), value.into_owned()))
734 .collect();
735 let body = if method == "GET" {
736 Value::Null
737 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell738 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root739 };
740 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
741 return fail(FailureCode::NotFound, "No such endpoint.");
742 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API743 match audit::run(route.op, &services, &viewer, &input).await? {
744 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 step745 // A token without the scope a call needs is told which one.
746 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
747 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
748 "error": {
749 "code": refused.code,
750 "message": refused.message,
751 "needed_scope": scope.as_str(),
752 }
753 }))?
754 .with_status(403)),
755 _ => failure(&refused),
756 },
API and MCP server in Rust; a public index at the API root757 }
758}
759
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API760/// Request bodies take the same keys as the MCP tools, `snake_case`, as
761/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell762fn snake_case_keys(body: Value) -> Value {
763 let Value::Object(fields) = body else {
764 return body;
765 };
766 let mut out = serde_json::Map::new();
767 for (key, value) in fields {
768 let mut snake = String::with_capacity(key.len() + 4);
769 for c in key.chars() {
770 if c.is_ascii_uppercase() {
771 snake.push('_');
772 snake.push(c.to_ascii_lowercase());
773 } else {
774 snake.push(c);
775 }
776 }
777 // A key given in both spellings keeps the snake_case one.
778 if snake != key && out.contains_key(&snake) {
779 continue;
780 }
781 out.insert(snake, value);
782 }
783 Value::Object(out)
784}
785
786#[cfg(test)]
787mod tests {
788 use super::snake_case_keys;
789 use serde_json::json;
790
791 #[test]
792 fn camel_case_keys_are_accepted() {
793 assert_eq!(
794 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
795 json!({ "count_agent_approvals": false, "title": "x" })
796 );
797 }
798
799 #[test]
800 fn snake_case_wins_when_both_are_given() {
801 assert_eq!(
802 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
803 json!({ "keep_issue_open": true })
804 );
805 }
806}
807
API and MCP server in Rust; a public index at the API root808// The API is called from browsers too: the reference's explorer, and apps
809// built on g1t. It carries no cookies, so any origin may call it.
810#[event(fetch)]
811async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
812 let mut response = respond(request, &env).await?;
813 let headers = response.headers_mut();
814 headers.set("access-control-allow-origin", "*")?;
815 headers.set(
816 "access-control-allow-headers",
817 "authorization, content-type",
818 )?;
819 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
820 headers.set("access-control-expose-headers", "www-authenticate")?;
821 Ok(response)
822}

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