Skip to content
958 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

API and MCP server in Rust; a public index at the API root1//! The public API: REST at api.g1t.sh and the MCP server at mcp.g1t.sh.
2//!
3//! One Worker, two hostnames. Both are thin adapters over the same
4//! operations (see [`operations::Op`]), which call the services that own
5//! the data. This Worker holds none.
6
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb977mod about;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R28mod artifacts;
Merge branch 'worktree-agent-aaf03bdceac799c89'9mod addresses;
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily10mod alerts;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API11mod audit;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit12mod billing;
A repository has its own sidebar, as settings do13mod blobs;
Merge checks: statuses and check runs on every commit14mod checks;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9715mod deployments;
Merge branch 'worktree-agent-a5a5de74d8863d554' into worktree-agent-a16631325aecf58ca16mod deploy_keys;
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails17mod limits;
Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009)18mod logs;
API and MCP server in Rust; a public index at the API root19mod mcp;
API: notifications over REST and MCP, with notifications scopes20mod notifications;
API and MCP server in Rust; a public index at the API root21mod oauth;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R222mod oidc;
Merge packages: roles, Actions access, source label, soft delete, API23mod packages;
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar24mod people;
API and MCP server in Rust; a public index at the API root25mod openapi;
API: pinned projects over REST and MCP26mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9727mod projects;
Merge branch 'worktree-agent-a3abfcce648e87dca'28mod protection;
API and MCP server in Rust; a public index at the API root29mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains30mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API31#[cfg(test)]
32mod responses;
API and MCP server in Rust; a public index at the API root33mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge34mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents35mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar36mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step37mod tools;
API and MCP for a workspace's personal access token rules, members' tokens and approvals38mod token_policy;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R239mod toolkit;
API and MCP server in Rust; a public index at the API root40
Merge branch 'model-routing'41use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root42use g1t_contracts::identity::{
43 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
44};
Agents as a team: lifecycle, merge queue, billing and a new shell45use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains46 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
47 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell48};
49use g1t_contracts::identity::AgentScope;
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)50use g1t_contracts::{Failure, FailureCode, Outcome, PrincipalKind, User, Viewer};
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API51use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root52use serde_json::{Value, json};
53use worker::{Context, Env, Method, Request, Response, Result, event};
54
55use operations::Services;
56
57fn method_name(method: Method) -> &'static str {
58 match method {
59 Method::Get => "GET",
60 Method::Post => "POST",
61 Method::Patch => "PATCH",
62 Method::Put => "PUT",
63 Method::Delete => "DELETE",
64 Method::Options => "OPTIONS",
65 Method::Head => "HEAD",
66 _ => "OTHER",
67 }
68}
69
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API70/// A JSON response. Every body the API sends has its keys in `snake_case`;
71/// the contracts it passes through are `camelCase`, so they are converted
72/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
73/// the MCP protocol's own envelope keep the spelling their standards use.
74pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
75 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
76}
77
78/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
79/// workflow file, GitHub's contexts and event, and where to check out, all
80/// passed through as they are.
81const JOB_SPEC_AS_GIVEN: &[&str] = &[
Merge branch 'worktree-agent-a3abfcce648e87dca'82 "spec", "workflow", "github", "event", "contexts", "checkout", "permissions",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API83];
84
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R285/// Puts the toolkit's variables in a job's spec: its runtime token, where
86/// the toolkit's services are, and where to ask for an OIDC token when the
87/// job may have one and this installation issues them. The `runtime` the
88/// actions service sent goes no further.
89fn with_runtime(spec: &mut Value, api: &str, oidc: bool) {
90 let Some(runtime) = spec.as_object_mut().and_then(|s| s.remove("runtime")) else { return };
91 let Some(token) = runtime["token"].as_str().filter(|t| !t.is_empty()) else { return };
92 let id_token = oidc && runtime["id_token"].as_bool() == Some(true);
93 let vars = toolkit::runtime_variables(api, token, id_token);
94 if let Some(variables) = spec.get_mut("variables").and_then(Value::as_object_mut) {
95 variables.extend(vars);
96 }
97}
98
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)99/// What a person whose account has not confirmed its email address may
100/// call: who they are, their addresses, and confirming one with the code
101/// from the email. Nothing over MCP.
102fn pending_may(method: &str, path: &str, on_mcp: bool) -> bool {
103 !on_mcp
104 && matches!(
105 (method, path.trim_end_matches('/')),
106 ("GET", "/user") | ("GET", "/user/emails") | ("POST", "/user/emails/confirm")
107 )
108}
109
API and MCP server in Rust; a public index at the API root110/// An error in the shape every endpoint uses.
111fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API112 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root113}
114
115fn fail(code: FailureCode, message: &str) -> Result<Response> {
116 failure(&Failure {
117 code,
118 message: message.to_owned(),
119 })
120}
121
122/// A request body as JSON. An empty or malformed body is no input.
123async fn json_body(request: &mut Request) -> Value {
124 request.json().await.unwrap_or(Value::Null)
125}
126
127/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
128/// an anonymous viewer; a wrong one is refused, so that a typo does not
129/// silently look signed out.
130async fn authenticate(
131 request: &Request,
132 services: &Services,
133) -> Result<std::result::Result<Viewer, Response>> {
134 let header = request.headers().get("authorization")?.unwrap_or_default();
135 let token = match header.split_once(' ') {
136 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
137 token.trim()
138 }
139 _ => return Ok(Ok(None)),
140 };
141 let viewer: Viewer = g1t_kit::call(
142 &services.identity,
143 "user_for_access_token",
144 &TokenArgs {
145 token: token.to_owned(),
146 },
147 )
148 .await?;
149 if viewer.is_some() {
150 return Ok(Ok(viewer));
151 }
152 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
153 // Tells an MCP client where to sign in again.
154 response.headers_mut().set(
155 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'156 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root157 )?;
158 Ok(Err(response))
159}
160
161/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'162fn index(addresses: &addresses::Addresses) -> Value {
163 let api = &addresses.api;
164 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root165 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'166 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'167 "openapi_url": format!("{api}/openapi.json"),
168 "mcp_url": addresses.mcp,
169 "current_user_url": format!("{api}/user"),
170 "workspaces_url": format!("{api}/workspaces"),
171 "repositories_url": format!("{api}/repos{{?q}}"),
172 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root173 "repository_url": repo,
174 "repository_events_url": format!("{repo}/events{{?before}}"),
175 "labels_url": format!("{repo}/labels"),
176 "issues_url": format!("{repo}/issues{{?state,label}}"),
177 "issue_url": format!("{repo}/issues/{{number}}"),
178 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
179 "pulls_url": format!("{repo}/pulls{{?state}}"),
180 "pull_url": format!("{repo}/pulls/{{number}}"),
181 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts182 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root183 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'184 "device_code_url": format!("{api}/device/code"),
185 "device_token_url": format!("{api}/device/token"),
186 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
187 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
188 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read189 "context_url": format!("{repo}/context{{?reference}}"),
190 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'191 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root192 })
193}
194
195// Signing in from a tool. Accounts are created, and passwords typed, only
196// in a browser; a tool gets its token by having a person approve a code.
197
Integrations: your own model provider, alerts that open issues, tickets agents read198/// Passes a request from an outside system to its connection, as it came:
199/// its signature covers the exact bytes of the body.
200async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
201 let headers: std::collections::HashMap<String, String> = request
202 .headers()
203 .entries()
204 .map(|(name, value)| (name.to_lowercase(), value))
205 .collect();
206 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look207 // A push to GitHub with many commits makes a large payload.
208 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
209 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API210 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read211 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look212 // g1t's GitHub App has one webhook for every installation; it is
213 // checked against the app's own secret.
214 let (method, args) = if id == "github" {
215 ("github_receive", json!({ "headers": headers, "body": body }))
216 } else {
217 ("receive", json!({ "id": id, "headers": headers, "body": body }))
218 };
219 let received: g1t_contracts::integrations::Received =
220 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 API221 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read222}
223
Stripe webhooks, enterprise invoices, and sudo for both224async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
225 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
226 let payload = request.text().await.unwrap_or_default();
227 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 API228 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both229 }
230 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
231 &env.service("BILLING")?,
232 "stripe_webhook",
233 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
234 )
235 .await?;
236 // A refusal is a 400, so Stripe shows it as failed; anything handled,
237 // or already handled, is a 200, so Stripe stops sending it.
238 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API239 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both240 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API241 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both242 }
243 })
244}
245
API and MCP server in Rust; a public index at the API root246async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
247 let body = json_body(request).await;
248 let started: DeviceStart = g1t_kit::call(
249 &services.identity,
250 "device_start",
251 &DeviceStartArgs {
252 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
253 },
254 )
255 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API256 reply(&json!({
API and MCP server in Rust; a public index at the API root257 "device_code": started.device_code,
258 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'259 "verification_uri": format!("{}/device", services.addresses.site),
260 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root261 "expires_in": started.expires_in,
262 "interval": started.interval,
263 }))
264}
265
266async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
267 let body = json_body(request).await;
268 let claim: DeviceClaim = g1t_kit::call(
269 &services.identity,
270 "device_claim",
271 &DeviceClaimArgs {
272 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
273 },
274 )
275 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API276 reply(&match claim {
API and MCP server in Rust; a public index at the API root277 DeviceClaim::Approved { token, user } => json!({
278 "status": "approved",
279 "token": token,
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar280 "display_username": user.display_username.clone().filter(|display| display.eq_ignore_ascii_case(&user.username)).unwrap_or_else(|| user.username.clone()),
API and MCP server in Rust; a public index at the API root281 "username": user.username,
282 "verified": user.verified,
283 }),
284 DeviceClaim::Pending => json!({ "status": "pending" }),
285 DeviceClaim::Denied => json!({ "status": "denied" }),
286 DeviceClaim::Expired => json!({ "status": "expired" }),
287 })
288}
289
Fast pages, required checks on the branch, self-hosted runners, honest incidents290/// A sandbox reporting on a run of an issue's commands, from before a pull
291/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts292/// The run's own token, in the body, is the credential: it was given to
293/// that sandbox and to nothing else.
294async fn report_checks(
295 request: &mut Request,
296 services: &Services,
297 run_id: &str,
298) -> Result<Response> {
299 let body = json_body(request).await;
300 let reported: Outcome<CheckRun> = g1t_kit::call(
301 &services.work,
302 "report_checks",
303 &ReportChecksArgs {
304 run_id: run_id.to_owned(),
305 token: body["token"].as_str().unwrap_or_default().to_owned(),
306 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
307 error: body["error"].as_str().map(str::to_owned),
308 skip: false,
309 },
310 )
311 .await?;
312 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API313 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts314 Outcome::Fail(refused) => failure(&refused),
315 }
316}
317
Agents as a team: lifecycle, merge queue, billing and a new shell318/// A sandbox reporting one tested state of a merge queue. As with checks,
319/// the entry's own token is the credential.
320async fn report_queue(
321 request: &mut Request,
322 services: &Services,
323 entry_id: &str,
324) -> Result<Response> {
325 let body = json_body(request).await;
326 let reported: Outcome<QueueState> = g1t_kit::call(
327 &services.work,
328 "report_queue",
329 &ReportQueueArgs {
330 entry_id: entry_id.to_owned(),
331 token: body["token"].as_str().unwrap_or_default().to_owned(),
332 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
333 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
334 error: body["error"].as_str().map(str::to_owned),
335 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains336 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell337 },
338 )
339 .await?;
340 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API341 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell342 Outcome::Fail(refused) => failure(&refused),
343 }
344}
345
Agents and memory, checks and conflicts, profiles, slug renames, custom domains346/// A sandbox reporting whether a pull request merges cleanly. As with
347/// checks, the probe's own token is the credential.
348async fn report_mergecheck(
349 request: &mut Request,
350 services: &Services,
351 pull_id: &str,
352) -> Result<Response> {
353 let body = json_body(request).await;
354 let reported: Outcome<Mergeable> = g1t_kit::call(
355 &services.work,
356 "report_mergecheck",
357 &ReportMergecheckArgs {
358 pull_id: pull_id.to_owned(),
359 token: body["token"].as_str().unwrap_or_default().to_owned(),
360 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
361 error: body["error"].as_str().map(str::to_owned),
362 },
363 )
364 .await?;
365 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API366 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains367 Outcome::Fail(refused) => failure(&refused),
368 }
369}
370
Merge branch 'worktree-agent-ac5b181a013e54348'371/// A backup's sandbox, passed on to the repos service, which holds the
372/// job (services/repos/src/backups.rs; the flow is in
373/// `g1t_contracts::backups`):
374///
375/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
376/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
377/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
378/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
379///
380/// Bodies are passed through as they are: snake_case already, and a
381/// bundle's refs are keyed by ref names, which must not be converted.
382async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
383 use g1t_contracts::backups::TOKEN_HEADER;
384 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
385 let rest = path.trim_start_matches("/backups/");
386 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
387 if job.is_empty() || token.is_empty() {
388 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
389 }
390 if method == "PUT" && action.starts_with("parts/") {
391 let bytes = request.bytes().await?;
392 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
393 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
394 }
395 let headers = worker::Headers::new();
396 headers.set(TOKEN_HEADER, &token)?;
397 let mut init = worker::RequestInit::new();
398 init.with_method(Method::Put)
399 .with_headers(headers)
400 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
401 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
402 let mut answered = services.repos.fetch_request(forwarded).await?;
403 return outcome_as_given(answered.json().await?);
404 }
405 let rpc = match (method, action) {
406 ("POST", "spec") => "backup_spec",
407 ("POST", "complete") => "backup_complete",
408 ("POST", "fail") => "backup_fail",
409 _ => return fail(FailureCode::NotFound, "No such endpoint."),
410 };
411 let mut body = json_body(request).await;
412 if !body.is_object() {
413 body = json!({});
414 }
415 body["job_id"] = json!(job);
416 body["token"] = json!(token);
417 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
418 outcome_as_given(answered)
419}
420
421/// An `Outcome` from a service whose keys are already the API's: the value,
422/// or the failure in the shape every endpoint uses.
423fn outcome_as_given(answered: Value) -> Result<Response> {
424 match serde_json::from_value::<Outcome<Value>>(answered)? {
425 Outcome::Ok(value) => Response::from_json(&value),
426 Outcome::Fail(refused) => failure(&refused),
427 }
428}
429
Agents as a team: lifecycle, merge queue, billing and a new shell430/// A sandbox reporting the review its agent wrote. As with checks, the
431/// run's own token is the credential.
432async fn report_review(
433 request: &mut Request,
434 services: &Services,
435 run_id: &str,
436) -> Result<Response> {
437 let body = json_body(request).await;
438 let reported: Outcome<bool> = g1t_kit::call(
439 &services.work,
440 "report_review",
441 &ReportReviewArgs {
442 run_id: run_id.to_owned(),
443 token: body["token"].as_str().unwrap_or_default().to_owned(),
444 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
445 body: body["body"].as_str().unwrap_or_default().to_owned(),
446 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
447 model: body["model"].as_str().map(str::to_owned),
448 error: body["error"].as_str().map(str::to_owned),
449 },
450 )
451 .await?;
452 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API453 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell454 Outcome::Fail(refused) => failure(&refused),
455 }
456}
457
458/// A sandbox reporting the plan its agent wrote. As with checks, the
459/// plan's own token is the credential.
460async fn report_plan(
461 request: &mut Request,
462 services: &Services,
463 plan_id: &str,
464) -> Result<Response> {
465 let body = json_body(request).await;
466 let reported: Outcome<bool> = g1t_kit::call(
467 &services.work,
468 "report_plan",
469 &ReportPlanArgs {
470 plan_id: plan_id.to_owned(),
471 token: body["token"].as_str().unwrap_or_default().to_owned(),
472 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
473 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
474 error: body["error"].as_str().map(str::to_owned),
475 },
476 )
477 .await?;
478 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API479 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell480 Outcome::Fail(refused) => failure(&refused),
481 }
482}
483
484/// A sandbox reporting what its agent's run cost, so that the workspace
485/// it worked for is charged. As with checks, the run's own token is the
486/// credential.
487async fn report_usage(
488 request: &mut Request,
489 services: &Services,
490 run_id: &str,
491) -> Result<Response> {
492 let body = json_body(request).await;
493 let charged: Outcome<bool> = g1t_kit::call(
494 &services.billing,
495 "finish_run",
496 &FinishRunArgs {
497 run_id: run_id.to_owned(),
498 token: body["token"].as_str().unwrap_or_default().to_owned(),
499 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
500 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'501 // What the harness counted; the agent rate is charged on no
502 // fewer, on a workspace's own model key too.
503 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
504 input: t["input"].as_u64().unwrap_or_default(),
505 output: t["output"].as_u64().unwrap_or_default(),
506 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
507 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
508 }),
Agents as a team: lifecycle, merge queue, billing and a new shell509 },
510 )
511 .await?;
512 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API513 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell514 Outcome::Fail(refused) => failure(&refused),
515 }
516}
517
API and MCP server in Rust; a public index at the API root518async fn respond(mut request: Request, env: &Env) -> Result<Response> {
519 let method = method_name(request.method());
520 if method == "OPTIONS" {
521 return Ok(Response::empty()?.with_status(204));
522 }
523 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell524 // Paths carry no version. An earlier form began with `/v1`, which is
525 // still accepted so that nothing already written against it breaks.
526 let path = match url.path().strip_prefix("/v1") {
527 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
528 _ => url.path().to_owned(),
529 };
530 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'531 // MCP is a host of its own hosted, and may be a path on this one
532 // self-hosted (addresses.rs).
533 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root534
Stripe webhooks, enterprise invoices, and sudo for both535 // Stripe reporting to billing. Signed with the secret of the endpoint
536 // billing registered; the body goes through exactly as received, since
537 // the signature covers its bytes.
538 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
539 return receive_stripe(&mut request, env).await;
540 }
541
Integrations: your own model provider, alerts that open issues, tickets agents read542 // Outside systems reporting to a connection. They sign what they send
543 // with the connection's own secret, which is not a g1t token, so this
544 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide545 if method == "POST" && !on_mcp
546 && 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 read547 return receive_hook(&mut request, &services, id).await;
548 }
549
Deployments: a preview for every pull request, production on g1t.page550 // A sandbox building a deployment, reporting with its build's token,
551 // which is not a g1t token. The body goes through as it is: it can
552 // carry a Worker's bundled code.
553 if method == "POST" && !on_mcp
554 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
555 {
556 let target = format!("https://deployments/jobs/{rest}");
557 let body = request.bytes().await?;
558 let headers = worker::Headers::new();
559 headers.set("content-type", "application/json")?;
560 let mut init = worker::RequestInit::new();
561 init.with_method(Method::Post)
562 .with_headers(headers)
563 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run564 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page565 .service("DEPLOYMENTS")?
566 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run567 .await?;
568 // A fresh response: a fetched one's headers cannot be changed, and
569 // every response gets the API's own on the way out.
570 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API571 let bytes = answer.bytes().await?;
572 let bytes = match serde_json::from_slice::<Value>(&bytes) {
573 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
574 Err(_) => bytes,
575 };
576 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run577 .with_status(status)
578 .with_headers({
579 let headers = worker::Headers::new();
580 headers.set("content-type", "application/json")?;
581 headers
582 }));
Deployments: a preview for every pull request, production on g1t.page583 }
584
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2585 // The services GitHub's toolkit calls from inside a job, with its
586 // runtime token, and the links they hand out (toolkit.rs).
587 if !on_mcp && method == "POST"
588 && let Some(rest) = path.strip_prefix("/twirp/")
589 {
590 let (service, rpc) = rest.split_once('/').unwrap_or((rest, ""));
591 let (service, rpc) = (service.to_owned(), rpc.to_owned());
592 return toolkit::twirp(request, env, &services, &service, &rpc).await;
593 }
594 if !on_mcp && let Some(rest) = path.strip_prefix("/actions/toolkit/_apis/artifactcache/") {
595 let rest = rest.to_owned();
596 return toolkit::cache_v1(request, env, &services, method, &rest).await;
597 }
598 if !on_mcp && let Some(token) = path.strip_prefix("/actions/toolkit/blobs/") {
599 let token = token.to_owned();
600 return toolkit::blob(request, env, &services, method, &token).await;
601 }
602 // g1t as an OIDC issuer for workflow jobs (oidc.rs).
603 if !on_mcp && method == "GET" && path.starts_with("/actions/oidc/") {
604 return oidc::handle(&request, env, &services, &path).await;
605 }
606
A repository has its own sidebar, as settings do607 // A sandbox's artifacts and cache, with its job's token, which is not a
608 // g1t token either.
609 if !on_mcp
610 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents611 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do612 {
613 let rest = rest.to_owned();
614 return blobs::for_job(request, env, &services, method, &rest).await;
615 }
616
Fast pages, required checks on the branch, self-hosted runners, honest incidents617 // A self-hosted runner, with a registration token or its own
618 // credential, neither of which is a g1t access token.
619 if method == "POST"
620 && !on_mcp
621 && path.starts_with("/runners/")
622 && let Some(response) = runners::handle(&mut request, &services, &path).await?
623 {
624 return Ok(response);
625 }
626
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails627 // Per token, or per address without one (limits.rs).
628 if let Some(limited) = limits::limited(&request, env, method, &path, on_mcp).await? {
629 return Ok(limited);
630 }
API and MCP server in Rust; a public index at the API root631 let viewer = match authenticate(&request, &services).await? {
632 Ok(viewer) => viewer,
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails633 Err(refused) => return Ok(limits::wrong_token(&request, env, on_mcp).await?.unwrap_or(refused)),
API and MCP server in Rust; a public index at the API root634 };
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)635 // A person who has not confirmed their email address: who they are,
636 // their addresses, and confirming one, nothing else (REST or MCP).
637 if viewer.as_ref().is_some_and(User::awaits_confirmation) && !pending_may(method, &path, on_mcp) {
638 return fail(
639 FailureCode::Forbidden,
640 &g1t_contracts::accounts::confirm_email_first(&services.addresses.site),
641 );
642 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API643 services.audit = audit::AuditContext::of(&request, on_mcp);
644 // An agent's token: what it may do comes with it, on the composite
645 // identity identity resolved it to.
646 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
647 services.scope = Some(acting.scope.clone());
648 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell649 let header = request.headers().get("authorization")?.unwrap_or_default();
650 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
651 let scope: Option<AgentScope> = g1t_kit::call(
652 &services.identity,
653 "agent_scope",
654 &TokenArgs {
655 token: token.to_owned(),
656 },
657 )
658 .await?;
659 // A scope is what lets an agent's token do anything at all.
660 let Some(scope) = scope else {
661 return fail(FailureCode::Unauthenticated, "Invalid access token.");
662 };
663 services.scope = Some(scope);
664 }
API and MCP server in Rust; a public index at the API root665 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
666 return Ok(response);
667 }
668 if on_mcp {
669 return mcp::handle(request, &services, &viewer).await;
670 }
671
Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009)672 // Workflow logs to download: a run's as a zip, a job's as text (logs.rs).
673 if method == "GET" {
674 let text = url.query_pairs().any(|(name, value)| name == "format" && value == "text");
675 if let Some(wanted) = logs::wanted(&path, text) {
676 return logs::download(&services, &viewer, wanted).await;
677 }
678 }
679
API and MCP server in Rust; a public index at the API root680 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'681 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root682 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2683 // One of a run's artifacts downloaded by name (the run's artifacts
684 // are listed by the REST route in rest.rs).
685 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts/") => {
A repository has its own sidebar, as settings do686 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2687 if let [owner, repo, "actions", "runs", run, "artifacts", name] = parts.as_slice() {
Merge branch 'worktree-agent-a3abfcce648e87dca'688 // A workflow job's token reaches its own repository only.
689 if viewer
690 .as_ref()
691 .and_then(|user| user.token.as_deref())
692 .is_some_and(|token| !token.reaches(&format!("{owner}/{repo}")))
693 {
694 return fail(FailureCode::NotFound, "No such run.");
695 }
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2696 return blobs::download(env, &services, &viewer, owner, repo, run, name).await;
A repository has its own sidebar, as settings do697 }
698 }
Agents as a team: lifecycle, merge queue, billing and a new shell699 ("POST", "/device/code") => return device_code(&mut request, &services).await,
700 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically701 // Where a pull request lives, for a tool that knows only its fork.
702 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
703 let located: Outcome<Value> = g1t_kit::call(
704 &services.work,
705 "locate_pull",
706 &json!({ "id": &path[7..], "viewer": viewer }),
707 )
708 .await?;
709 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API710 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically711 Outcome::Fail(refused) => failure(&refused),
712 };
713 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains714 ("POST", path) if path.starts_with("/mergechecks/") => {
715 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
716 return report_mergecheck(&mut request, &services, &pull_id).await;
717 }
Merge branch 'worktree-agent-ac5b181a013e54348'718 // A sandbox making a repository's nightly backup. The job's own
719 // token, in its header, is the credential.
720 (method, path) if path.starts_with("/backups/") => {
721 return backup_job(&mut request, &services, method, path).await;
722 }
Agents as a team: lifecycle, merge queue, billing and a new shell723 ("POST", path) if path.starts_with("/queue/") => {
724 let entry_id = path.trim_start_matches("/queue/").to_owned();
725 return report_queue(&mut request, &services, &entry_id).await;
726 }
GitHub Actions on g1t, part two: running workflows727 // A sandbox running a GitHub Actions job: fetching the job, and
728 // reporting how it goes. The job's own token is the credential.
729 ("POST", path) if path.starts_with("/actions/jobs/") => {
730 let rest = path.trim_start_matches("/actions/jobs/");
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts731 // `/action`: where to fetch another repository's action from (on
732 // g1t, with a read token for a private one, or GitHub).
733 let (job, method) = match (rest.strip_suffix("/spec"), rest.strip_suffix("/action")) {
734 (Some(job), _) => (job.to_owned(), "job_spec"),
735 (_, Some(job)) => (job.to_owned(), "job_action"),
736 _ => (rest.to_owned(), "job_report"),
GitHub Actions on g1t, part two: running workflows737 };
738 let body = json_body(&mut request).await;
739 let answered: Outcome<Value> = g1t_kit::call(
740 &services.actions,
741 method,
742 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
743 )
744 .await?;
745 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API746 // A job's spec is the workflow and its contexts as GitHub
747 // has them; only g1t's own keys around them are converted.
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2748 Outcome::Ok(value) => {
749 let mut spec = wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN);
750 with_runtime(&mut spec, &services.addresses.api, oidc::configured(env));
751 Response::from_json(&spec)
752 }
GitHub Actions on g1t, part two: running workflows753 Outcome::Fail(refused) => failure(&refused),
754 };
755 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains756 // A sandbox reporting its agent run's steps, cost and end. As with
757 // checks, the run's own token, in the body, is the credential.
758 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
759 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
760 let mut body = json_body(&mut request).await;
761 if !body.is_object() {
762 body = json!({});
763 }
764 body["runId"] = json!(run_id);
765 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
766 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API767 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains768 Outcome::Fail(refused) => failure(&refused),
769 };
770 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API771 // What a run's agent learned, as memory candidates; the same token.
772 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
773 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
774 let body = json_body(&mut request).await;
775 let learned = json!({
776 "runId": run_id,
777 "token": body["token"].as_str().unwrap_or_default(),
778 "items": body["items"].as_array().cloned().unwrap_or_default(),
779 });
780 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
781 return match captured {
782 Outcome::Ok(captured) => reply(&captured),
783 Outcome::Fail(refused) => failure(&refused),
784 };
785 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step786 // How sure a run's agent is of its change; the same token.
787 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
788 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
789 let body = json_body(&mut request).await;
790 let said = json!({
791 "runId": run_id,
792 "token": body["token"].as_str().unwrap_or_default(),
793 "confidence": body["confidence"].as_str().unwrap_or_default(),
794 "uncertainAbout": body["uncertain_about"]
795 .as_array()
796 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
797 .unwrap_or_default(),
798 });
799 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
800 return match recorded {
801 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
802 Outcome::Fail(refused) => failure(&refused),
803 };
804 }
Agents as a team: lifecycle, merge queue, billing and a new shell805 ("POST", path) if path.starts_with("/checks/") => {
806 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts807 return report_checks(&mut request, &services, &run_id).await;
808 }
Agents as a team: lifecycle, merge queue, billing and a new shell809 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
810 let run_id = path
811 .trim_start_matches("/runs/")
812 .trim_end_matches("/usage")
813 .to_owned();
814 return report_usage(&mut request, &services, &run_id).await;
815 }
816 ("POST", path) if path.starts_with("/plans/") => {
817 let plan_id = path.trim_start_matches("/plans/").to_owned();
818 return report_plan(&mut request, &services, &plan_id).await;
819 }
820 ("POST", path) if path.starts_with("/reviews/") => {
821 let run_id = path.trim_start_matches("/reviews/").to_owned();
822 return report_review(&mut request, &services, &run_id).await;
823 }
API and MCP server in Rust; a public index at the API root824 _ => {}
825 }
826
827 let query: Vec<(String, String)> = url
828 .query_pairs()
829 .map(|(name, value)| (name.into_owned(), value.into_owned()))
830 .collect();
831 let body = if method == "GET" {
832 Value::Null
833 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell834 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root835 };
836 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
837 return fail(FailureCode::NotFound, "No such endpoint.");
838 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API839 match audit::run(route.op, &services, &viewer, &input).await? {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2840 // A download is a redirect to its signed link, as GitHub's is.
841 Outcome::Ok(value) if route.op == operations::Op::Artifacts(artifacts::ArtifactsOp::DownloadArtifact) => {
842 match value["url"].as_str().and_then(|url| worker::Url::parse(url).ok()) {
843 Some(url) => Response::redirect_with_status(url, 302),
844 None => reply(&value),
845 }
846 }
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts847 // A deleted comment has nothing to say, as GitHub's says nothing.
848 Outcome::Ok(_) if route.no_content() => Ok(Response::empty()?.with_status(204)),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API849 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 step850 // A token without the scope a call needs is told which one.
851 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
852 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
853 "error": {
854 "code": refused.code,
855 "message": refused.message,
856 "needed_scope": scope.as_str(),
857 }
858 }))?
859 .with_status(403)),
860 _ => failure(&refused),
861 },
API and MCP server in Rust; a public index at the API root862 }
863}
864
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API865/// Request bodies take the same keys as the MCP tools, `snake_case`, as
866/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell867fn snake_case_keys(body: Value) -> Value {
868 let Value::Object(fields) = body else {
869 return body;
870 };
871 let mut out = serde_json::Map::new();
872 for (key, value) in fields {
873 let mut snake = String::with_capacity(key.len() + 4);
874 for c in key.chars() {
875 if c.is_ascii_uppercase() {
876 snake.push('_');
877 snake.push(c.to_ascii_lowercase());
878 } else {
879 snake.push(c);
880 }
881 }
882 // A key given in both spellings keeps the snake_case one.
883 if snake != key && out.contains_key(&snake) {
884 continue;
885 }
886 out.insert(snake, value);
887 }
888 Value::Object(out)
889}
890
891#[cfg(test)]
892mod tests {
893 use super::snake_case_keys;
894 use serde_json::json;
895
896 #[test]
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)897 fn an_unconfirmed_account_may_only_see_itself_and_confirm_its_address() {
898 assert!(super::pending_may("GET", "/user", false));
899 assert!(super::pending_may("GET", "/user/emails/", false));
900 assert!(super::pending_may("POST", "/user/emails/confirm", false));
901 assert!(!super::pending_may("POST", "/user/emails", false));
902 assert!(!super::pending_may("POST", "/workspaces", false));
903 assert!(!super::pending_may("GET", "/repos/acme/rocket", false));
904 assert!(!super::pending_may("POST", "/user/emails/confirm", true));
905 assert!(!super::pending_may("POST", "/", true));
906 }
907
908 #[test]
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2909 fn a_job_spec_gets_the_toolkits_variables() {
910 // As the actions service sends it, converted as the API does.
911 let sent = json!({ "variables": { "GITHUB_SHA": "abc" }, "runtime": { "token": "h.p.s", "idToken": true } });
912 let mut spec = g1t_kit::wire::snake_case_keeping(sent.clone(), super::JOB_SPEC_AS_GIVEN);
913 super::with_runtime(&mut spec, "https://api.g1t.sh", true);
914 assert!(spec.get("runtime").is_none(), "the runner never sees it");
915 let vars = &spec["variables"];
916 assert_eq!(vars["GITHUB_SHA"], "abc");
917 assert_eq!(vars["ACTIONS_RUNTIME_TOKEN"], "h.p.s");
918 assert_eq!(vars["ACTIONS_CACHE_URL"], "https://api.g1t.sh/actions/toolkit/");
919 assert_eq!(vars["ACTIONS_ID_TOKEN_REQUEST_TOKEN"], "h.p.s");
920 // No OIDC key here: no OIDC variables, whatever the job may do.
921 let mut spec = g1t_kit::wire::snake_case_keeping(sent, super::JOB_SPEC_AS_GIVEN);
922 super::with_runtime(&mut spec, "https://api.g1t.sh", false);
923 assert!(spec["variables"].get("ACTIONS_ID_TOKEN_REQUEST_URL").is_none());
924 assert_eq!(spec["variables"]["ACTIONS_RESULTS_URL"], "https://api.g1t.sh/");
925 }
926
927 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell928 fn camel_case_keys_are_accepted() {
929 assert_eq!(
930 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
931 json!({ "count_agent_approvals": false, "title": "x" })
932 );
933 }
934
935 #[test]
936 fn snake_case_wins_when_both_are_given() {
937 assert_eq!(
938 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
939 json!({ "keep_issue_open": true })
940 );
941 }
942}
943
API and MCP server in Rust; a public index at the API root944// The API is called from browsers too: the reference's explorer, and apps
945// built on g1t. It carries no cookies, so any origin may call it.
946#[event(fetch)]
947async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
948 let mut response = respond(request, &env).await?;
949 let headers = response.headers_mut();
950 headers.set("access-control-allow-origin", "*")?;
951 headers.set(
952 "access-control-allow-headers",
953 "authorization, content-type",
954 )?;
955 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails956 headers.set("access-control-expose-headers", "www-authenticate, retry-after")?;
API and MCP server in Rust; a public index at the API root957 Ok(response)
958}

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