g1t/apps/api/src/lib.rs

820 lines34,161 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
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily7mod alerts;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API8mod audit;
A repository has its own sidebar, as settings do9mod blobs;
API and MCP server in Rust; a public index at the API root10mod mcp;
11mod oauth;
12mod openapi;
13mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains14mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API15#[cfg(test)]
16mod responses;
API and MCP server in Rust; a public index at the API root17mod rest;
Fast pages, required checks on the branch, self-hosted runners, honest incidents18mod runners;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step19mod tools;
API and MCP server in Rust; a public index at the API root20
Agents as a team: lifecycle, merge queue, billing and a new shell21use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root22use g1t_contracts::identity::{
23 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
24};
Agents as a team: lifecycle, merge queue, billing and a new shell25use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains26 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
27 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell28};
29use g1t_contracts::identity::AgentScope;
30use 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 API31use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root32use serde_json::{Value, json};
33use worker::{Context, Env, Method, Request, Response, Result, event};
34
35use operations::Services;
36
37const API: &str = "https://api.g1t.sh";
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",
113 &format!("{}, error=\"invalid_token\"", oauth::MCP_CHALLENGE),
114 )?;
115 Ok(Err(response))
116}
117
118/// Where everything is, for someone or something exploring the API.
119fn index() -> Value {
Agents as a team: lifecycle, merge queue, billing and a new shell120 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/",
API and MCP server in Rust; a public index at the API root123 "openapi_url": format!("{API}/openapi.json"),
124 "mcp_url": "https://mcp.g1t.sh",
Agents as a team: lifecycle, merge queue, billing and a new shell125 "current_user_url": format!("{API}/user"),
126 "workspaces_url": format!("{API}/workspaces"),
127 "repositories_url": format!("{API}/repos{{?q}}"),
Search across all of g1t, Explore, and a command palette128 "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}}"),
Agents as a team: lifecycle, merge queue, billing and a new shell140 "device_code_url": format!("{API}/device/code"),
141 "device_token_url": format!("{API}/device/token"),
API and MCP server in Rust; a public index at the API root142 "oauth_metadata_url": format!("{API}/.well-known/oauth-authorization-server"),
143 "git_url": "https://g1t.sh/{owner}/{name}.git",
Integrations: your own model provider, alerts that open issues, tickets agents read144 "integrations_url": format!("{API}/workspaces/{{workspace}}/integrations"),
145 "context_url": format!("{repo}/context{{?reference}}"),
146 "import_issue_url": format!("{repo}/issues/import"),
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,
215 "verification_uri": "https://g1t.sh/device",
216 "verification_uri_complete": format!("https://g1t.sh/device?code={}", started.user_code),
217 "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
Backup jobs: the sandbox mode that cuts the bundle, and the API door it reports through326/// 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 };
API and MCP server in Rust; a public index at the API root477 let on_mcp = url.host_str().is_some_and(|host| host.starts_with("mcp."));
Agents as a team: lifecycle, merge queue, billing and a new shell478 let mut services = Services::new(env)?;
API and MCP server in Rust; a public index at the API root479
Stripe webhooks, enterprise invoices, and sudo for both480 // Stripe reporting to billing. Signed with the secret of the endpoint
481 // billing registered; the body goes through exactly as received, since
482 // the signature covers its bytes.
483 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
484 return receive_stripe(&mut request, env).await;
485 }
486
Integrations: your own model provider, alerts that open issues, tickets agents read487 // Outside systems reporting to a connection. They sign what they send
488 // with the connection's own secret, which is not a g1t token, so this
489 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide490 if method == "POST" && !on_mcp
491 && 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 read492 return receive_hook(&mut request, &services, id).await;
493 }
494
Deployments: a preview for every pull request, production on g1t.page495 // A sandbox building a deployment, reporting with its build's token,
496 // which is not a g1t token. The body goes through as it is: it can
497 // carry a Worker's bundled code.
498 if method == "POST" && !on_mcp
499 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
500 {
501 let target = format!("https://deployments/jobs/{rest}");
502 let body = request.bytes().await?;
503 let headers = worker::Headers::new();
504 headers.set("content-type", "application/json")?;
505 let mut init = worker::RequestInit::new();
506 init.with_method(Method::Post)
507 .with_headers(headers)
508 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run509 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page510 .service("DEPLOYMENTS")?
511 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run512 .await?;
513 // A fresh response: a fetched one's headers cannot be changed, and
514 // every response gets the API's own on the way out.
515 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API516 let bytes = answer.bytes().await?;
517 let bytes = match serde_json::from_slice::<Value>(&bytes) {
518 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
519 Err(_) => bytes,
520 };
521 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run522 .with_status(status)
523 .with_headers({
524 let headers = worker::Headers::new();
525 headers.set("content-type", "application/json")?;
526 headers
527 }));
Deployments: a preview for every pull request, production on g1t.page528 }
529
A repository has its own sidebar, as settings do530 // A sandbox's artifacts and cache, with its job's token, which is not a
531 // g1t token either.
532 if !on_mcp
533 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents534 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do535 {
536 let rest = rest.to_owned();
537 return blobs::for_job(request, env, &services, method, &rest).await;
538 }
539
Fast pages, required checks on the branch, self-hosted runners, honest incidents540 // A self-hosted runner, with a registration token or its own
541 // credential, neither of which is a g1t access token.
542 if method == "POST"
543 && !on_mcp
544 && path.starts_with("/runners/")
545 && let Some(response) = runners::handle(&mut request, &services, &path).await?
546 {
547 return Ok(response);
548 }
549
API and MCP server in Rust; a public index at the API root550 let viewer = match authenticate(&request, &services).await? {
551 Ok(viewer) => viewer,
552 Err(refused) => return Ok(refused),
553 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API554 services.audit = audit::AuditContext::of(&request, on_mcp);
555 // An agent's token: what it may do comes with it, on the composite
556 // identity identity resolved it to.
557 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
558 services.scope = Some(acting.scope.clone());
559 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell560 let header = request.headers().get("authorization")?.unwrap_or_default();
561 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
562 let scope: Option<AgentScope> = g1t_kit::call(
563 &services.identity,
564 "agent_scope",
565 &TokenArgs {
566 token: token.to_owned(),
567 },
568 )
569 .await?;
570 // A scope is what lets an agent's token do anything at all.
571 let Some(scope) = scope else {
572 return fail(FailureCode::Unauthenticated, "Invalid access token.");
573 };
574 services.scope = Some(scope);
575 }
API and MCP server in Rust; a public index at the API root576 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
577 return Ok(response);
578 }
579 if on_mcp {
580 return mcp::handle(request, &services, &viewer).await;
581 }
582
583 match (method, path.trim_end_matches('/')) {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API584 ("GET", "") => return reply(&index()),
API and MCP server in Rust; a public index at the API root585 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do586 // A run's artifacts: listed, or one downloaded.
587 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
588 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
589 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
590 return match rest {
591 [] => {
592 let seen: Outcome<Value> = g1t_kit::call(
593 &services.actions,
594 "run",
595 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
596 )
597 .await?;
598 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API599 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do600 Outcome::Fail(refused) => failure(&refused),
601 }
602 }
603 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
604 _ => fail(FailureCode::NotFound, "No such endpoint."),
605 };
606 }
607 }
Agents as a team: lifecycle, merge queue, billing and a new shell608 ("POST", "/device/code") => return device_code(&mut request, &services).await,
609 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically610 // Where a pull request lives, for a tool that knows only its fork.
611 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
612 let located: Outcome<Value> = g1t_kit::call(
613 &services.work,
614 "locate_pull",
615 &json!({ "id": &path[7..], "viewer": viewer }),
616 )
617 .await?;
618 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API619 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically620 Outcome::Fail(refused) => failure(&refused),
621 };
622 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains623 ("POST", path) if path.starts_with("/mergechecks/") => {
624 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
625 return report_mergecheck(&mut request, &services, &pull_id).await;
626 }
Backup jobs: the sandbox mode that cuts the bundle, and the API door it reports through627 // A sandbox making a repository's nightly backup. The job's own
628 // token, in its header, is the credential.
629 (method, path) if path.starts_with("/backups/") => {
630 return backup_job(&mut request, &services, method, path).await;
631 }
Agents as a team: lifecycle, merge queue, billing and a new shell632 ("POST", path) if path.starts_with("/queue/") => {
633 let entry_id = path.trim_start_matches("/queue/").to_owned();
634 return report_queue(&mut request, &services, &entry_id).await;
635 }
GitHub Actions on g1t, part two: running workflows636 // A sandbox running a GitHub Actions job: fetching the job, and
637 // reporting how it goes. The job's own token is the credential.
638 ("POST", path) if path.starts_with("/actions/jobs/") => {
639 let rest = path.trim_start_matches("/actions/jobs/");
640 let (job, method) = match rest.strip_suffix("/spec") {
641 Some(job) => (job.to_owned(), "job_spec"),
642 None => (rest.to_owned(), "job_report"),
643 };
644 let body = json_body(&mut request).await;
645 let answered: Outcome<Value> = g1t_kit::call(
646 &services.actions,
647 method,
648 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
649 )
650 .await?;
651 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API652 // A job's spec is the workflow and its contexts as GitHub
653 // has them; only g1t's own keys around them are converted.
654 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows655 Outcome::Fail(refused) => failure(&refused),
656 };
657 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains658 // A sandbox reporting its agent run's steps, cost and end. As with
659 // checks, the run's own token, in the body, is the credential.
660 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
661 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
662 let mut body = json_body(&mut request).await;
663 if !body.is_object() {
664 body = json!({});
665 }
666 body["runId"] = json!(run_id);
667 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
668 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API669 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains670 Outcome::Fail(refused) => failure(&refused),
671 };
672 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API673 // What a run's agent learned, as memory candidates; the same token.
674 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
675 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
676 let body = json_body(&mut request).await;
677 let learned = json!({
678 "runId": run_id,
679 "token": body["token"].as_str().unwrap_or_default(),
680 "items": body["items"].as_array().cloned().unwrap_or_default(),
681 });
682 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
683 return match captured {
684 Outcome::Ok(captured) => reply(&captured),
685 Outcome::Fail(refused) => failure(&refused),
686 };
687 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step688 // How sure a run's agent is of its change; the same token.
689 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
690 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
691 let body = json_body(&mut request).await;
692 let said = json!({
693 "runId": run_id,
694 "token": body["token"].as_str().unwrap_or_default(),
695 "confidence": body["confidence"].as_str().unwrap_or_default(),
696 "uncertainAbout": body["uncertain_about"]
697 .as_array()
698 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
699 .unwrap_or_default(),
700 });
701 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
702 return match recorded {
703 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
704 Outcome::Fail(refused) => failure(&refused),
705 };
706 }
Agents as a team: lifecycle, merge queue, billing and a new shell707 ("POST", path) if path.starts_with("/checks/") => {
708 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts709 return report_checks(&mut request, &services, &run_id).await;
710 }
Agents as a team: lifecycle, merge queue, billing and a new shell711 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
712 let run_id = path
713 .trim_start_matches("/runs/")
714 .trim_end_matches("/usage")
715 .to_owned();
716 return report_usage(&mut request, &services, &run_id).await;
717 }
718 ("POST", path) if path.starts_with("/plans/") => {
719 let plan_id = path.trim_start_matches("/plans/").to_owned();
720 return report_plan(&mut request, &services, &plan_id).await;
721 }
722 ("POST", path) if path.starts_with("/reviews/") => {
723 let run_id = path.trim_start_matches("/reviews/").to_owned();
724 return report_review(&mut request, &services, &run_id).await;
725 }
API and MCP server in Rust; a public index at the API root726 _ => {}
727 }
728
729 let query: Vec<(String, String)> = url
730 .query_pairs()
731 .map(|(name, value)| (name.into_owned(), value.into_owned()))
732 .collect();
733 let body = if method == "GET" {
734 Value::Null
735 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell736 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root737 };
738 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
739 return fail(FailureCode::NotFound, "No such endpoint.");
740 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API741 match audit::run(route.op, &services, &viewer, &input).await? {
742 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 step743 // A token without the scope a call needs is told which one.
744 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
745 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
746 "error": {
747 "code": refused.code,
748 "message": refused.message,
749 "needed_scope": scope.as_str(),
750 }
751 }))?
752 .with_status(403)),
753 _ => failure(&refused),
754 },
API and MCP server in Rust; a public index at the API root755 }
756}
757
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API758/// Request bodies take the same keys as the MCP tools, `snake_case`, as
759/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell760fn snake_case_keys(body: Value) -> Value {
761 let Value::Object(fields) = body else {
762 return body;
763 };
764 let mut out = serde_json::Map::new();
765 for (key, value) in fields {
766 let mut snake = String::with_capacity(key.len() + 4);
767 for c in key.chars() {
768 if c.is_ascii_uppercase() {
769 snake.push('_');
770 snake.push(c.to_ascii_lowercase());
771 } else {
772 snake.push(c);
773 }
774 }
775 // A key given in both spellings keeps the snake_case one.
776 if snake != key && out.contains_key(&snake) {
777 continue;
778 }
779 out.insert(snake, value);
780 }
781 Value::Object(out)
782}
783
784#[cfg(test)]
785mod tests {
786 use super::snake_case_keys;
787 use serde_json::json;
788
789 #[test]
790 fn camel_case_keys_are_accepted() {
791 assert_eq!(
792 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
793 json!({ "count_agent_approvals": false, "title": "x" })
794 );
795 }
796
797 #[test]
798 fn snake_case_wins_when_both_are_given() {
799 assert_eq!(
800 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
801 json!({ "keep_issue_open": true })
802 );
803 }
804}
805
API and MCP server in Rust; a public index at the API root806// The API is called from browsers too: the reference's explorer, and apps
807// built on g1t. It carries no cookies, so any origin may call it.
808#[event(fetch)]
809async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
810 let mut response = respond(request, &env).await?;
811 let headers = response.headers_mut();
812 headers.set("access-control-allow-origin", "*")?;
813 headers.set(
814 "access-control-allow-headers",
815 "authorization, content-type",
816 )?;
817 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
818 headers.set("access-control-expose-headers", "www-authenticate")?;
819 Ok(response)
820}

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