flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/lib.rs

756 lines31,074 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
Agents as a team: lifecycle, merge queue, billing and a new shell326/// A sandbox reporting the review its agent wrote. As with checks, the
327/// run's own token is the credential.
328async fn report_review(
329 request: &mut Request,
330 services: &Services,
331 run_id: &str,
332) -> Result<Response> {
333 let body = json_body(request).await;
334 let reported: Outcome<bool> = g1t_kit::call(
335 &services.work,
336 "report_review",
337 &ReportReviewArgs {
338 run_id: run_id.to_owned(),
339 token: body["token"].as_str().unwrap_or_default().to_owned(),
340 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
341 body: body["body"].as_str().unwrap_or_default().to_owned(),
342 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
343 model: body["model"].as_str().map(str::to_owned),
344 error: body["error"].as_str().map(str::to_owned),
345 },
346 )
347 .await?;
348 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API349 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell350 Outcome::Fail(refused) => failure(&refused),
351 }
352}
353
354/// A sandbox reporting the plan its agent wrote. As with checks, the
355/// plan's own token is the credential.
356async fn report_plan(
357 request: &mut Request,
358 services: &Services,
359 plan_id: &str,
360) -> Result<Response> {
361 let body = json_body(request).await;
362 let reported: Outcome<bool> = g1t_kit::call(
363 &services.work,
364 "report_plan",
365 &ReportPlanArgs {
366 plan_id: plan_id.to_owned(),
367 token: body["token"].as_str().unwrap_or_default().to_owned(),
368 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
369 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
370 error: body["error"].as_str().map(str::to_owned),
371 },
372 )
373 .await?;
374 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API375 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell376 Outcome::Fail(refused) => failure(&refused),
377 }
378}
379
380/// A sandbox reporting what its agent's run cost, so that the workspace
381/// it worked for is charged. As with checks, the run's own token is the
382/// credential.
383async fn report_usage(
384 request: &mut Request,
385 services: &Services,
386 run_id: &str,
387) -> Result<Response> {
388 let body = json_body(request).await;
389 let charged: Outcome<bool> = g1t_kit::call(
390 &services.billing,
391 "finish_run",
392 &FinishRunArgs {
393 run_id: run_id.to_owned(),
394 token: body["token"].as_str().unwrap_or_default().to_owned(),
395 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
396 turns: body["turns"].as_u64().unwrap_or_default() as u32,
397 },
398 )
399 .await?;
400 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API401 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell402 Outcome::Fail(refused) => failure(&refused),
403 }
404}
405
API and MCP server in Rust; a public index at the API root406async fn respond(mut request: Request, env: &Env) -> Result<Response> {
407 let method = method_name(request.method());
408 if method == "OPTIONS" {
409 return Ok(Response::empty()?.with_status(204));
410 }
411 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell412 // Paths carry no version. An earlier form began with `/v1`, which is
413 // still accepted so that nothing already written against it breaks.
414 let path = match url.path().strip_prefix("/v1") {
415 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
416 _ => url.path().to_owned(),
417 };
API and MCP server in Rust; a public index at the API root418 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 shell419 let mut services = Services::new(env)?;
API and MCP server in Rust; a public index at the API root420
Stripe webhooks, enterprise invoices, and sudo for both421 // Stripe reporting to billing. Signed with the secret of the endpoint
422 // billing registered; the body goes through exactly as received, since
423 // the signature covers its bytes.
424 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
425 return receive_stripe(&mut request, env).await;
426 }
427
Integrations: your own model provider, alerts that open issues, tickets agents read428 // Outside systems reporting to a connection. They sign what they send
429 // with the connection's own secret, which is not a g1t token, so this
430 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide431 if method == "POST" && !on_mcp
432 && 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 read433 return receive_hook(&mut request, &services, id).await;
434 }
435
Deployments: a preview for every pull request, production on g1t.page436 // A sandbox building a deployment, reporting with its build's token,
437 // which is not a g1t token. The body goes through as it is: it can
438 // carry a Worker's bundled code.
439 if method == "POST" && !on_mcp
440 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
441 {
442 let target = format!("https://deployments/jobs/{rest}");
443 let body = request.bytes().await?;
444 let headers = worker::Headers::new();
445 headers.set("content-type", "application/json")?;
446 let mut init = worker::RequestInit::new();
447 init.with_method(Method::Post)
448 .with_headers(headers)
449 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run450 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page451 .service("DEPLOYMENTS")?
452 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run453 .await?;
454 // A fresh response: a fetched one's headers cannot be changed, and
455 // every response gets the API's own on the way out.
456 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API457 let bytes = answer.bytes().await?;
458 let bytes = match serde_json::from_slice::<Value>(&bytes) {
459 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
460 Err(_) => bytes,
461 };
462 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run463 .with_status(status)
464 .with_headers({
465 let headers = worker::Headers::new();
466 headers.set("content-type", "application/json")?;
467 headers
468 }));
Deployments: a preview for every pull request, production on g1t.page469 }
470
A repository has its own sidebar, as settings do471 // A sandbox's artifacts and cache, with its job's token, which is not a
472 // g1t token either.
473 if !on_mcp
474 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents475 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do476 {
477 let rest = rest.to_owned();
478 return blobs::for_job(request, env, &services, method, &rest).await;
479 }
480
Fast pages, required checks on the branch, self-hosted runners, honest incidents481 // A self-hosted runner, with a registration token or its own
482 // credential, neither of which is a g1t access token.
483 if method == "POST"
484 && !on_mcp
485 && path.starts_with("/runners/")
486 && let Some(response) = runners::handle(&mut request, &services, &path).await?
487 {
488 return Ok(response);
489 }
490
API and MCP server in Rust; a public index at the API root491 let viewer = match authenticate(&request, &services).await? {
492 Ok(viewer) => viewer,
493 Err(refused) => return Ok(refused),
494 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API495 services.audit = audit::AuditContext::of(&request, on_mcp);
496 // An agent's token: what it may do comes with it, on the composite
497 // identity identity resolved it to.
498 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
499 services.scope = Some(acting.scope.clone());
500 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell501 let header = request.headers().get("authorization")?.unwrap_or_default();
502 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
503 let scope: Option<AgentScope> = g1t_kit::call(
504 &services.identity,
505 "agent_scope",
506 &TokenArgs {
507 token: token.to_owned(),
508 },
509 )
510 .await?;
511 // A scope is what lets an agent's token do anything at all.
512 let Some(scope) = scope else {
513 return fail(FailureCode::Unauthenticated, "Invalid access token.");
514 };
515 services.scope = Some(scope);
516 }
API and MCP server in Rust; a public index at the API root517 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
518 return Ok(response);
519 }
520 if on_mcp {
521 return mcp::handle(request, &services, &viewer).await;
522 }
523
524 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 API525 ("GET", "") => return reply(&index()),
API and MCP server in Rust; a public index at the API root526 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
A repository has its own sidebar, as settings do527 // A run's artifacts: listed, or one downloaded.
528 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
529 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
530 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
531 return match rest {
532 [] => {
533 let seen: Outcome<Value> = g1t_kit::call(
534 &services.actions,
535 "run",
536 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
537 )
538 .await?;
539 match seen {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API540 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
A repository has its own sidebar, as settings do541 Outcome::Fail(refused) => failure(&refused),
542 }
543 }
544 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
545 _ => fail(FailureCode::NotFound, "No such endpoint."),
546 };
547 }
548 }
Agents as a team: lifecycle, merge queue, billing and a new shell549 ("POST", "/device/code") => return device_code(&mut request, &services).await,
550 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically551 // Where a pull request lives, for a tool that knows only its fork.
552 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
553 let located: Outcome<Value> = g1t_kit::call(
554 &services.work,
555 "locate_pull",
556 &json!({ "id": &path[7..], "viewer": viewer }),
557 )
558 .await?;
559 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API560 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically561 Outcome::Fail(refused) => failure(&refused),
562 };
563 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains564 ("POST", path) if path.starts_with("/mergechecks/") => {
565 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
566 return report_mergecheck(&mut request, &services, &pull_id).await;
567 }
Agents as a team: lifecycle, merge queue, billing and a new shell568 ("POST", path) if path.starts_with("/queue/") => {
569 let entry_id = path.trim_start_matches("/queue/").to_owned();
570 return report_queue(&mut request, &services, &entry_id).await;
571 }
GitHub Actions on g1t, part two: running workflows572 // A sandbox running a GitHub Actions job: fetching the job, and
573 // reporting how it goes. The job's own token is the credential.
574 ("POST", path) if path.starts_with("/actions/jobs/") => {
575 let rest = path.trim_start_matches("/actions/jobs/");
576 let (job, method) = match rest.strip_suffix("/spec") {
577 Some(job) => (job.to_owned(), "job_spec"),
578 None => (rest.to_owned(), "job_report"),
579 };
580 let body = json_body(&mut request).await;
581 let answered: Outcome<Value> = g1t_kit::call(
582 &services.actions,
583 method,
584 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
585 )
586 .await?;
587 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API588 // A job's spec is the workflow and its contexts as GitHub
589 // has them; only g1t's own keys around them are converted.
590 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
GitHub Actions on g1t, part two: running workflows591 Outcome::Fail(refused) => failure(&refused),
592 };
593 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains594 // A sandbox reporting its agent run's steps, cost and end. As with
595 // checks, the run's own token, in the body, is the credential.
596 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
597 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
598 let mut body = json_body(&mut request).await;
599 if !body.is_object() {
600 body = json!({});
601 }
602 body["runId"] = json!(run_id);
603 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
604 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API605 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains606 Outcome::Fail(refused) => failure(&refused),
607 };
608 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API609 // What a run's agent learned, as memory candidates; the same token.
610 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
611 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
612 let body = json_body(&mut request).await;
613 let learned = json!({
614 "runId": run_id,
615 "token": body["token"].as_str().unwrap_or_default(),
616 "items": body["items"].as_array().cloned().unwrap_or_default(),
617 });
618 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
619 return match captured {
620 Outcome::Ok(captured) => reply(&captured),
621 Outcome::Fail(refused) => failure(&refused),
622 };
623 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step624 // How sure a run's agent is of its change; the same token.
625 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
626 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
627 let body = json_body(&mut request).await;
628 let said = json!({
629 "runId": run_id,
630 "token": body["token"].as_str().unwrap_or_default(),
631 "confidence": body["confidence"].as_str().unwrap_or_default(),
632 "uncertainAbout": body["uncertain_about"]
633 .as_array()
634 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
635 .unwrap_or_default(),
636 });
637 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
638 return match recorded {
639 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
640 Outcome::Fail(refused) => failure(&refused),
641 };
642 }
Agents as a team: lifecycle, merge queue, billing and a new shell643 ("POST", path) if path.starts_with("/checks/") => {
644 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts645 return report_checks(&mut request, &services, &run_id).await;
646 }
Agents as a team: lifecycle, merge queue, billing and a new shell647 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
648 let run_id = path
649 .trim_start_matches("/runs/")
650 .trim_end_matches("/usage")
651 .to_owned();
652 return report_usage(&mut request, &services, &run_id).await;
653 }
654 ("POST", path) if path.starts_with("/plans/") => {
655 let plan_id = path.trim_start_matches("/plans/").to_owned();
656 return report_plan(&mut request, &services, &plan_id).await;
657 }
658 ("POST", path) if path.starts_with("/reviews/") => {
659 let run_id = path.trim_start_matches("/reviews/").to_owned();
660 return report_review(&mut request, &services, &run_id).await;
661 }
API and MCP server in Rust; a public index at the API root662 _ => {}
663 }
664
665 let query: Vec<(String, String)> = url
666 .query_pairs()
667 .map(|(name, value)| (name.into_owned(), value.into_owned()))
668 .collect();
669 let body = if method == "GET" {
670 Value::Null
671 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell672 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root673 };
674 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
675 return fail(FailureCode::NotFound, "No such endpoint.");
676 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API677 match audit::run(route.op, &services, &viewer, &input).await? {
678 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 step679 // A token without the scope a call needs is told which one.
680 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
681 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
682 "error": {
683 "code": refused.code,
684 "message": refused.message,
685 "needed_scope": scope.as_str(),
686 }
687 }))?
688 .with_status(403)),
689 _ => failure(&refused),
690 },
API and MCP server in Rust; a public index at the API root691 }
692}
693
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API694/// Request bodies take the same keys as the MCP tools, `snake_case`, as
695/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell696fn snake_case_keys(body: Value) -> Value {
697 let Value::Object(fields) = body else {
698 return body;
699 };
700 let mut out = serde_json::Map::new();
701 for (key, value) in fields {
702 let mut snake = String::with_capacity(key.len() + 4);
703 for c in key.chars() {
704 if c.is_ascii_uppercase() {
705 snake.push('_');
706 snake.push(c.to_ascii_lowercase());
707 } else {
708 snake.push(c);
709 }
710 }
711 // A key given in both spellings keeps the snake_case one.
712 if snake != key && out.contains_key(&snake) {
713 continue;
714 }
715 out.insert(snake, value);
716 }
717 Value::Object(out)
718}
719
720#[cfg(test)]
721mod tests {
722 use super::snake_case_keys;
723 use serde_json::json;
724
725 #[test]
726 fn camel_case_keys_are_accepted() {
727 assert_eq!(
728 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
729 json!({ "count_agent_approvals": false, "title": "x" })
730 );
731 }
732
733 #[test]
734 fn snake_case_wins_when_both_are_given() {
735 assert_eq!(
736 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
737 json!({ "keep_issue_open": true })
738 );
739 }
740}
741
API and MCP server in Rust; a public index at the API root742// The API is called from browsers too: the reference's explorer, and apps
743// built on g1t. It carries no cookies, so any origin may call it.
744#[event(fetch)]
745async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
746 let mut response = respond(request, &env).await?;
747 let headers = response.headers_mut();
748 headers.set("access-control-allow-origin", "*")?;
749 headers.set(
750 "access-control-allow-headers",
751 "authorization, content-type",
752 )?;
753 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
754 headers.set("access-control-expose-headers", "www-authenticate")?;
755 Ok(response)
756}

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