g1t/apps/api/src/lib.rs

743 lines30,623 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
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API7mod audit;
A repository has its own sidebar, as settings do8mod blobs;
API and MCP server in Rust; a public index at the API root9mod mcp;
10mod oauth;
11mod openapi;
12mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains13mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API14#[cfg(test)]
15mod responses;
API and MCP server in Rust; a public index at the API root16mod rest;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step17mod tools;
API and MCP server in Rust; a public index at the API root18
Agents as a team: lifecycle, merge queue, billing and a new shell19use g1t_contracts::billing::FinishRunArgs;
API and MCP server in Rust; a public index at the API root20use g1t_contracts::identity::{
21 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
22};
Agents as a team: lifecycle, merge queue, billing and a new shell23use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains24 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
25 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell26};
27use g1t_contracts::identity::AgentScope;
28use 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 API29use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root30use serde_json::{Value, json};
31use worker::{Context, Env, Method, Request, Response, Result, event};
32
33use operations::Services;
34
35const API: &str = "https://api.g1t.sh";
36
37fn method_name(method: Method) -> &'static str {
38 match method {
39 Method::Get => "GET",
40 Method::Post => "POST",
41 Method::Patch => "PATCH",
42 Method::Put => "PUT",
43 Method::Delete => "DELETE",
44 Method::Options => "OPTIONS",
45 Method::Head => "HEAD",
46 _ => "OTHER",
47 }
48}
49
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API50/// A JSON response. Every body the API sends has its keys in `snake_case`;
51/// the contracts it passes through are `camelCase`, so they are converted
52/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
53/// the MCP protocol's own envelope keep the spelling their standards use.
54pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
55 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
56}
57
58/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
59/// workflow file, GitHub's contexts and event, and where to check out, all
60/// passed through as they are.
61const JOB_SPEC_AS_GIVEN: &[&str] = &[
62 "spec", "workflow", "github", "event", "contexts", "checkout",
63];
64
API and MCP server in Rust; a public index at the API root65/// An error in the shape every endpoint uses.
66fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API67 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root68}
69
70fn fail(code: FailureCode, message: &str) -> Result<Response> {
71 failure(&Failure {
72 code,
73 message: message.to_owned(),
74 })
75}
76
77/// A request body as JSON. An empty or malformed body is no input.
78async fn json_body(request: &mut Request) -> Value {
79 request.json().await.unwrap_or(Value::Null)
80}
81
82/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
83/// an anonymous viewer; a wrong one is refused, so that a typo does not
84/// silently look signed out.
85async fn authenticate(
86 request: &Request,
87 services: &Services,
88) -> Result<std::result::Result<Viewer, Response>> {
89 let header = request.headers().get("authorization")?.unwrap_or_default();
90 let token = match header.split_once(' ') {
91 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
92 token.trim()
93 }
94 _ => return Ok(Ok(None)),
95 };
96 let viewer: Viewer = g1t_kit::call(
97 &services.identity,
98 "user_for_access_token",
99 &TokenArgs {
100 token: token.to_owned(),
101 },
102 )
103 .await?;
104 if viewer.is_some() {
105 return Ok(Ok(viewer));
106 }
107 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
108 // Tells an MCP client where to sign in again.
109 response.headers_mut().set(
110 "www-authenticate",
111 &format!("{}, error=\"invalid_token\"", oauth::MCP_CHALLENGE),
112 )?;
113 Ok(Err(response))
114}
115
116/// Where everything is, for someone or something exploring the API.
117fn index() -> Value {
Agents as a team: lifecycle, merge queue, billing and a new shell118 let repo = format!("{API}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root119 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'120 "documentation_url": "https://docs.g1t.sh/reference/api/",
API and MCP server in Rust; a public index at the API root121 "openapi_url": format!("{API}/openapi.json"),
122 "mcp_url": "https://mcp.g1t.sh",
Agents as a team: lifecycle, merge queue, billing and a new shell123 "current_user_url": format!("{API}/user"),
124 "workspaces_url": format!("{API}/workspaces"),
125 "repositories_url": format!("{API}/repos{{?q}}"),
Search across all of g1t, Explore, and a command palette126 "search_url": format!("{API}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root127 "repository_url": repo,
128 "repository_events_url": format!("{repo}/events{{?before}}"),
129 "labels_url": format!("{repo}/labels"),
130 "issues_url": format!("{repo}/issues{{?state,label}}"),
131 "issue_url": format!("{repo}/issues/{{number}}"),
132 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
133 "pulls_url": format!("{repo}/pulls{{?state}}"),
134 "pull_url": format!("{repo}/pulls/{{number}}"),
135 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts136 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root137 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Agents as a team: lifecycle, merge queue, billing and a new shell138 "device_code_url": format!("{API}/device/code"),
139 "device_token_url": format!("{API}/device/token"),
API and MCP server in Rust; a public index at the API root140 "oauth_metadata_url": format!("{API}/.well-known/oauth-authorization-server"),
141 "git_url": "https://g1t.sh/{owner}/{name}.git",
Integrations: your own model provider, alerts that open issues, tickets agents read142 "integrations_url": format!("{API}/workspaces/{{workspace}}/integrations"),
143 "context_url": format!("{repo}/context{{?reference}}"),
144 "import_issue_url": format!("{repo}/issues/import"),
145 "hooks_url": format!("{API}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root146 })
147}
148
149// Signing in from a tool. Accounts are created, and passwords typed, only
150// in a browser; a tool gets its token by having a person approve a code.
151
Integrations: your own model provider, alerts that open issues, tickets agents read152/// Passes a request from an outside system to its connection, as it came:
153/// its signature covers the exact bytes of the body.
154async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
155 let headers: std::collections::HashMap<String, String> = request
156 .headers()
157 .entries()
158 .map(|(name, value)| (name.to_lowercase(), value))
159 .collect();
160 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look161 // A push to GitHub with many commits makes a large payload.
162 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
163 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API164 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read165 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look166 // g1t's GitHub App has one webhook for every installation; it is
167 // checked against the app's own secret.
168 let (method, args) = if id == "github" {
169 ("github_receive", json!({ "headers": headers, "body": body }))
170 } else {
171 ("receive", json!({ "id": id, "headers": headers, "body": body }))
172 };
173 let received: g1t_contracts::integrations::Received =
174 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 API175 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read176}
177
Stripe webhooks, enterprise invoices, and sudo for both178async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
179 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
180 let payload = request.text().await.unwrap_or_default();
181 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 API182 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both183 }
184 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
185 &env.service("BILLING")?,
186 "stripe_webhook",
187 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
188 )
189 .await?;
190 // A refusal is a 400, so Stripe shows it as failed; anything handled,
191 // or already handled, is a 200, so Stripe stops sending it.
192 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API193 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both194 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API195 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both196 }
197 })
198}
199
API and MCP server in Rust; a public index at the API root200async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
201 let body = json_body(request).await;
202 let started: DeviceStart = g1t_kit::call(
203 &services.identity,
204 "device_start",
205 &DeviceStartArgs {
206 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
207 },
208 )
209 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API210 reply(&json!({
API and MCP server in Rust; a public index at the API root211 "device_code": started.device_code,
212 "user_code": started.user_code,
213 "verification_uri": "https://g1t.sh/device",
214 "verification_uri_complete": format!("https://g1t.sh/device?code={}", started.user_code),
215 "expires_in": started.expires_in,
216 "interval": started.interval,
217 }))
218}
219
220async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
221 let body = json_body(request).await;
222 let claim: DeviceClaim = g1t_kit::call(
223 &services.identity,
224 "device_claim",
225 &DeviceClaimArgs {
226 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
227 },
228 )
229 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API230 reply(&match claim {
API and MCP server in Rust; a public index at the API root231 DeviceClaim::Approved { token, user } => json!({
232 "status": "approved",
233 "token": token,
234 "username": user.username,
235 "verified": user.verified,
236 }),
237 DeviceClaim::Pending => json!({ "status": "pending" }),
238 DeviceClaim::Denied => json!({ "status": "denied" }),
239 DeviceClaim::Expired => json!({ "status": "expired" }),
240 })
241}
242
Acceptance checks in sandboxes, line comments and review verdicts243/// A sandbox reporting on its run of a pull request's acceptance checks.
244/// The run's own token, in the body, is the credential: it was given to
245/// that sandbox and to nothing else.
246async fn report_checks(
247 request: &mut Request,
248 services: &Services,
249 run_id: &str,
250) -> Result<Response> {
251 let body = json_body(request).await;
252 let reported: Outcome<CheckRun> = g1t_kit::call(
253 &services.work,
254 "report_checks",
255 &ReportChecksArgs {
256 run_id: run_id.to_owned(),
257 token: body["token"].as_str().unwrap_or_default().to_owned(),
258 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
259 error: body["error"].as_str().map(str::to_owned),
260 skip: false,
261 },
262 )
263 .await?;
264 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API265 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts266 Outcome::Fail(refused) => failure(&refused),
267 }
268}
269
Agents as a team: lifecycle, merge queue, billing and a new shell270/// A sandbox reporting one tested state of a merge queue. As with checks,
271/// the entry's own token is the credential.
272async fn report_queue(
273 request: &mut Request,
274 services: &Services,
275 entry_id: &str,
276) -> Result<Response> {
277 let body = json_body(request).await;
278 let reported: Outcome<QueueState> = g1t_kit::call(
279 &services.work,
280 "report_queue",
281 &ReportQueueArgs {
282 entry_id: entry_id.to_owned(),
283 token: body["token"].as_str().unwrap_or_default().to_owned(),
284 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
285 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
286 error: body["error"].as_str().map(str::to_owned),
287 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains288 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell289 },
290 )
291 .await?;
292 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API293 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell294 Outcome::Fail(refused) => failure(&refused),
295 }
296}
297
Agents and memory, checks and conflicts, profiles, slug renames, custom domains298/// A sandbox reporting whether a pull request merges cleanly. As with
299/// checks, the probe's own token is the credential.
300async fn report_mergecheck(
301 request: &mut Request,
302 services: &Services,
303 pull_id: &str,
304) -> Result<Response> {
305 let body = json_body(request).await;
306 let reported: Outcome<Mergeable> = g1t_kit::call(
307 &services.work,
308 "report_mergecheck",
309 &ReportMergecheckArgs {
310 pull_id: pull_id.to_owned(),
311 token: body["token"].as_str().unwrap_or_default().to_owned(),
312 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
313 error: body["error"].as_str().map(str::to_owned),
314 },
315 )
316 .await?;
317 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API318 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains319 Outcome::Fail(refused) => failure(&refused),
320 }
321}
322
Agents as a team: lifecycle, merge queue, billing and a new shell323/// A sandbox reporting the review its agent wrote. As with checks, the
324/// run's own token is the credential.
325async fn report_review(
326 request: &mut Request,
327 services: &Services,
328 run_id: &str,
329) -> Result<Response> {
330 let body = json_body(request).await;
331 let reported: Outcome<bool> = g1t_kit::call(
332 &services.work,
333 "report_review",
334 &ReportReviewArgs {
335 run_id: run_id.to_owned(),
336 token: body["token"].as_str().unwrap_or_default().to_owned(),
337 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
338 body: body["body"].as_str().unwrap_or_default().to_owned(),
339 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
340 model: body["model"].as_str().map(str::to_owned),
341 error: body["error"].as_str().map(str::to_owned),
342 },
343 )
344 .await?;
345 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API346 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell347 Outcome::Fail(refused) => failure(&refused),
348 }
349}
350
351/// A sandbox reporting the plan its agent wrote. As with checks, the
352/// plan's own token is the credential.
353async fn report_plan(
354 request: &mut Request,
355 services: &Services,
356 plan_id: &str,
357) -> Result<Response> {
358 let body = json_body(request).await;
359 let reported: Outcome<bool> = g1t_kit::call(
360 &services.work,
361 "report_plan",
362 &ReportPlanArgs {
363 plan_id: plan_id.to_owned(),
364 token: body["token"].as_str().unwrap_or_default().to_owned(),
365 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
366 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
367 error: body["error"].as_str().map(str::to_owned),
368 },
369 )
370 .await?;
371 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API372 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell373 Outcome::Fail(refused) => failure(&refused),
374 }
375}
376
377/// A sandbox reporting what its agent's run cost, so that the workspace
378/// it worked for is charged. As with checks, the run's own token is the
379/// credential.
380async fn report_usage(
381 request: &mut Request,
382 services: &Services,
383 run_id: &str,
384) -> Result<Response> {
385 let body = json_body(request).await;
386 let charged: Outcome<bool> = g1t_kit::call(
387 &services.billing,
388 "finish_run",
389 &FinishRunArgs {
390 run_id: run_id.to_owned(),
391 token: body["token"].as_str().unwrap_or_default().to_owned(),
392 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
393 turns: body["turns"].as_u64().unwrap_or_default() as u32,
394 },
395 )
396 .await?;
397 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API398 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell399 Outcome::Fail(refused) => failure(&refused),
400 }
401}
402
API and MCP server in Rust; a public index at the API root403async fn respond(mut request: Request, env: &Env) -> Result<Response> {
404 let method = method_name(request.method());
405 if method == "OPTIONS" {
406 return Ok(Response::empty()?.with_status(204));
407 }
408 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell409 // Paths carry no version. An earlier form began with `/v1`, which is
410 // still accepted so that nothing already written against it breaks.
411 let path = match url.path().strip_prefix("/v1") {
412 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
413 _ => url.path().to_owned(),
414 };
API and MCP server in Rust; a public index at the API root415 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 shell416 let mut services = Services::new(env)?;
API and MCP server in Rust; a public index at the API root417
Stripe webhooks, enterprise invoices, and sudo for both418 // Stripe reporting to billing. Signed with the secret of the endpoint
419 // billing registered; the body goes through exactly as received, since
420 // the signature covers its bytes.
421 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
422 return receive_stripe(&mut request, env).await;
423 }
424
Integrations: your own model provider, alerts that open issues, tickets agents read425 // Outside systems reporting to a connection. They sign what they send
426 // with the connection's own secret, which is not a g1t token, so this
427 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide428 if method == "POST" && !on_mcp
429 && 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 read430 return receive_hook(&mut request, &services, id).await;
431 }
432
Deployments: a preview for every pull request, production on g1t.page433 // A sandbox building a deployment, reporting with its build's token,
434 // which is not a g1t token. The body goes through as it is: it can
435 // carry a Worker's bundled code.
436 if method == "POST" && !on_mcp
437 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
438 {
439 let target = format!("https://deployments/jobs/{rest}");
440 let body = request.bytes().await?;
441 let headers = worker::Headers::new();
442 headers.set("content-type", "application/json")?;
443 let mut init = worker::RequestInit::new();
444 init.with_method(Method::Post)
445 .with_headers(headers)
446 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run447 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page448 .service("DEPLOYMENTS")?
449 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run450 .await?;
451 // A fresh response: a fetched one's headers cannot be changed, and
452 // every response gets the API's own on the way out.
453 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API454 let bytes = answer.bytes().await?;
455 let bytes = match serde_json::from_slice::<Value>(&bytes) {
456 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
457 Err(_) => bytes,
458 };
459 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run460 .with_status(status)
461 .with_headers({
462 let headers = worker::Headers::new();
463 headers.set("content-type", "application/json")?;
464 headers
465 }));
Deployments: a preview for every pull request, production on g1t.page466 }
467
A repository has its own sidebar, as settings do468 // A sandbox's artifacts and cache, with its job's token, which is not a
469 // g1t token either.
470 if !on_mcp
471 && let Some(rest) = path.strip_prefix("/actions/jobs/")
472 && (rest.contains("/artifacts") || rest.ends_with("/cache"))
473 {
474 let rest = rest.to_owned();
475 return blobs::for_job(request, env, &services, method, &rest).await;
476 }
477
API and MCP server in Rust; a public index at the API root478 let viewer = match authenticate(&request, &services).await? {
479 Ok(viewer) => viewer,
480 Err(refused) => return Ok(refused),
481 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API482 services.audit = audit::AuditContext::of(&request, on_mcp);
483 // An agent's token: what it may do comes with it, on the composite
484 // identity identity resolved it to.
485 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
486 services.scope = Some(acting.scope.clone());
487 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell488 let header = request.headers().get("authorization")?.unwrap_or_default();
489 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
490 let scope: Option<AgentScope> = g1t_kit::call(
491 &services.identity,
492 "agent_scope",
493 &TokenArgs {
494 token: token.to_owned(),
495 },
496 )
497 .await?;
498 // A scope is what lets an agent's token do anything at all.
499 let Some(scope) = scope else {
500 return fail(FailureCode::Unauthenticated, "Invalid access token.");
501 };
502 services.scope = Some(scope);
503 }
API and MCP server in Rust; a public index at the API root504 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
505 return Ok(response);
506 }
507 if on_mcp {
508 return mcp::handle(request, &services, &viewer).await;
509 }
510
511 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 API512 ("GET", "") => return reply(&index()),
API and MCP server in Rust; a public index at the API root513 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do514 // A run's artifacts: listed, or one downloaded.
515 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
516 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
517 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
518 return match rest {
519 [] => {
520 let seen: Outcome<Value> = g1t_kit::call(
521 &services.actions,
522 "run",
523 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
524 )
525 .await?;
526 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API527 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do528 Outcome::Fail(refused) => failure(&refused),
529 }
530 }
531 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
532 _ => fail(FailureCode::NotFound, "No such endpoint."),
533 };
534 }
535 }
Agents as a team: lifecycle, merge queue, billing and a new shell536 ("POST", "/device/code") => return device_code(&mut request, &services).await,
537 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically538 // Where a pull request lives, for a tool that knows only its fork.
539 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
540 let located: Outcome<Value> = g1t_kit::call(
541 &services.work,
542 "locate_pull",
543 &json!({ "id": &path[7..], "viewer": viewer }),
544 )
545 .await?;
546 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API547 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically548 Outcome::Fail(refused) => failure(&refused),
549 };
550 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains551 ("POST", path) if path.starts_with("/mergechecks/") => {
552 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
553 return report_mergecheck(&mut request, &services, &pull_id).await;
554 }
Agents as a team: lifecycle, merge queue, billing and a new shell555 ("POST", path) if path.starts_with("/queue/") => {
556 let entry_id = path.trim_start_matches("/queue/").to_owned();
557 return report_queue(&mut request, &services, &entry_id).await;
558 }
GitHub Actions on g1t, part two: running workflows559 // A sandbox running a GitHub Actions job: fetching the job, and
560 // reporting how it goes. The job's own token is the credential.
561 ("POST", path) if path.starts_with("/actions/jobs/") => {
562 let rest = path.trim_start_matches("/actions/jobs/");
563 let (job, method) = match rest.strip_suffix("/spec") {
564 Some(job) => (job.to_owned(), "job_spec"),
565 None => (rest.to_owned(), "job_report"),
566 };
567 let body = json_body(&mut request).await;
568 let answered: Outcome<Value> = g1t_kit::call(
569 &services.actions,
570 method,
571 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
572 )
573 .await?;
574 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API575 // A job's spec is the workflow and its contexts as GitHub
576 // has them; only g1t's own keys around them are converted.
577 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows578 Outcome::Fail(refused) => failure(&refused),
579 };
580 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains581 // A sandbox reporting its agent run's steps, cost and end. As with
582 // checks, the run's own token, in the body, is the credential.
583 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
584 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
585 let mut body = json_body(&mut request).await;
586 if !body.is_object() {
587 body = json!({});
588 }
589 body["runId"] = json!(run_id);
590 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
591 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API592 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains593 Outcome::Fail(refused) => failure(&refused),
594 };
595 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API596 // What a run's agent learned, as memory candidates; the same token.
597 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
598 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
599 let body = json_body(&mut request).await;
600 let learned = json!({
601 "runId": run_id,
602 "token": body["token"].as_str().unwrap_or_default(),
603 "items": body["items"].as_array().cloned().unwrap_or_default(),
604 });
605 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
606 return match captured {
607 Outcome::Ok(captured) => reply(&captured),
608 Outcome::Fail(refused) => failure(&refused),
609 };
610 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step611 // How sure a run's agent is of its change; the same token.
612 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
613 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
614 let body = json_body(&mut request).await;
615 let said = json!({
616 "runId": run_id,
617 "token": body["token"].as_str().unwrap_or_default(),
618 "confidence": body["confidence"].as_str().unwrap_or_default(),
619 "uncertainAbout": body["uncertain_about"]
620 .as_array()
621 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
622 .unwrap_or_default(),
623 });
624 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
625 return match recorded {
626 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
627 Outcome::Fail(refused) => failure(&refused),
628 };
629 }
Agents as a team: lifecycle, merge queue, billing and a new shell630 ("POST", path) if path.starts_with("/checks/") => {
631 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts632 return report_checks(&mut request, &services, &run_id).await;
633 }
Agents as a team: lifecycle, merge queue, billing and a new shell634 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
635 let run_id = path
636 .trim_start_matches("/runs/")
637 .trim_end_matches("/usage")
638 .to_owned();
639 return report_usage(&mut request, &services, &run_id).await;
640 }
641 ("POST", path) if path.starts_with("/plans/") => {
642 let plan_id = path.trim_start_matches("/plans/").to_owned();
643 return report_plan(&mut request, &services, &plan_id).await;
644 }
645 ("POST", path) if path.starts_with("/reviews/") => {
646 let run_id = path.trim_start_matches("/reviews/").to_owned();
647 return report_review(&mut request, &services, &run_id).await;
648 }
API and MCP server in Rust; a public index at the API root649 _ => {}
650 }
651
652 let query: Vec<(String, String)> = url
653 .query_pairs()
654 .map(|(name, value)| (name.into_owned(), value.into_owned()))
655 .collect();
656 let body = if method == "GET" {
657 Value::Null
658 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell659 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root660 };
661 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
662 return fail(FailureCode::NotFound, "No such endpoint.");
663 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API664 match audit::run(route.op, &services, &viewer, &input).await? {
665 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 step666 // A token without the scope a call needs is told which one.
667 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
668 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
669 "error": {
670 "code": refused.code,
671 "message": refused.message,
672 "needed_scope": scope.as_str(),
673 }
674 }))?
675 .with_status(403)),
676 _ => failure(&refused),
677 },
API and MCP server in Rust; a public index at the API root678 }
679}
680
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API681/// Request bodies take the same keys as the MCP tools, `snake_case`, as
682/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell683fn snake_case_keys(body: Value) -> Value {
684 let Value::Object(fields) = body else {
685 return body;
686 };
687 let mut out = serde_json::Map::new();
688 for (key, value) in fields {
689 let mut snake = String::with_capacity(key.len() + 4);
690 for c in key.chars() {
691 if c.is_ascii_uppercase() {
692 snake.push('_');
693 snake.push(c.to_ascii_lowercase());
694 } else {
695 snake.push(c);
696 }
697 }
698 // A key given in both spellings keeps the snake_case one.
699 if snake != key && out.contains_key(&snake) {
700 continue;
701 }
702 out.insert(snake, value);
703 }
704 Value::Object(out)
705}
706
707#[cfg(test)]
708mod tests {
709 use super::snake_case_keys;
710 use serde_json::json;
711
712 #[test]
713 fn camel_case_keys_are_accepted() {
714 assert_eq!(
715 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
716 json!({ "count_agent_approvals": false, "title": "x" })
717 );
718 }
719
720 #[test]
721 fn snake_case_wins_when_both_are_given() {
722 assert_eq!(
723 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
724 json!({ "keep_issue_open": true })
725 );
726 }
727}
728
API and MCP server in Rust; a public index at the API root729// The API is called from browsers too: the reference's explorer, and apps
730// built on g1t. It carries no cookies, so any origin may call it.
731#[event(fetch)]
732async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
733 let mut response = respond(request, &env).await?;
734 let headers = response.headers_mut();
735 headers.set("access-control-allow-origin", "*")?;
736 headers.set(
737 "access-control-allow-headers",
738 "authorization, content-type",
739 )?;
740 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
741 headers.set("access-control-expose-headers", "www-authenticate")?;
742 Ok(response)
743}

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