Skip to content
956 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;
API and MCP server in Rust; a public index at the API root24mod openapi;
API: pinned projects over REST and MCP25mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9726mod projects;
Merge branch 'worktree-agent-a3abfcce648e87dca'27mod protection;
API and MCP server in Rust; a public index at the API root28mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains29mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API30#[cfg(test)]
31mod responses;
API and MCP server in Rust; a public index at the API root32mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge33mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents34mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar35mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step36mod tools;
API and MCP for a workspace's personal access token rules, members' tokens and approvals37mod token_policy;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R238mod toolkit;
API and MCP server in Rust; a public index at the API root39
Merge branch 'model-routing'40use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root41use g1t_contracts::identity::{
42 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
43};
Agents as a team: lifecycle, merge queue, billing and a new shell44use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains45 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
46 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell47};
48use g1t_contracts::identity::AgentScope;
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)49use 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 API50use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root51use serde_json::{Value, json};
52use worker::{Context, Env, Method, Request, Response, Result, event};
53
54use operations::Services;
55
56fn method_name(method: Method) -> &'static str {
57 match method {
58 Method::Get => "GET",
59 Method::Post => "POST",
60 Method::Patch => "PATCH",
61 Method::Put => "PUT",
62 Method::Delete => "DELETE",
63 Method::Options => "OPTIONS",
64 Method::Head => "HEAD",
65 _ => "OTHER",
66 }
67}
68
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API69/// A JSON response. Every body the API sends has its keys in `snake_case`;
70/// the contracts it passes through are `camelCase`, so they are converted
71/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
72/// the MCP protocol's own envelope keep the spelling their standards use.
73pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
74 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
75}
76
77/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
78/// workflow file, GitHub's contexts and event, and where to check out, all
79/// passed through as they are.
80const JOB_SPEC_AS_GIVEN: &[&str] = &[
Merge branch 'worktree-agent-a3abfcce648e87dca'81 "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 API82];
83
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R284/// Puts the toolkit's variables in a job's spec: its runtime token, where
85/// the toolkit's services are, and where to ask for an OIDC token when the
86/// job may have one and this installation issues them. The `runtime` the
87/// actions service sent goes no further.
88fn with_runtime(spec: &mut Value, api: &str, oidc: bool) {
89 let Some(runtime) = spec.as_object_mut().and_then(|s| s.remove("runtime")) else { return };
90 let Some(token) = runtime["token"].as_str().filter(|t| !t.is_empty()) else { return };
91 let id_token = oidc && runtime["id_token"].as_bool() == Some(true);
92 let vars = toolkit::runtime_variables(api, token, id_token);
93 if let Some(variables) = spec.get_mut("variables").and_then(Value::as_object_mut) {
94 variables.extend(vars);
95 }
96}
97
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)98/// What a person whose account has not confirmed its email address may
99/// call: who they are, their addresses, and confirming one with the code
100/// from the email. Nothing over MCP.
101fn pending_may(method: &str, path: &str, on_mcp: bool) -> bool {
102 !on_mcp
103 && matches!(
104 (method, path.trim_end_matches('/')),
105 ("GET", "/user") | ("GET", "/user/emails") | ("POST", "/user/emails/confirm")
106 )
107}
108
API and MCP server in Rust; a public index at the API root109/// An error in the shape every endpoint uses.
110fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API111 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root112}
113
114fn fail(code: FailureCode, message: &str) -> Result<Response> {
115 failure(&Failure {
116 code,
117 message: message.to_owned(),
118 })
119}
120
121/// A request body as JSON. An empty or malformed body is no input.
122async fn json_body(request: &mut Request) -> Value {
123 request.json().await.unwrap_or(Value::Null)
124}
125
126/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
127/// an anonymous viewer; a wrong one is refused, so that a typo does not
128/// silently look signed out.
129async fn authenticate(
130 request: &Request,
131 services: &Services,
132) -> Result<std::result::Result<Viewer, Response>> {
133 let header = request.headers().get("authorization")?.unwrap_or_default();
134 let token = match header.split_once(' ') {
135 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
136 token.trim()
137 }
138 _ => return Ok(Ok(None)),
139 };
140 let viewer: Viewer = g1t_kit::call(
141 &services.identity,
142 "user_for_access_token",
143 &TokenArgs {
144 token: token.to_owned(),
145 },
146 )
147 .await?;
148 if viewer.is_some() {
149 return Ok(Ok(viewer));
150 }
151 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
152 // Tells an MCP client where to sign in again.
153 response.headers_mut().set(
154 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'155 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root156 )?;
157 Ok(Err(response))
158}
159
160/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'161fn index(addresses: &addresses::Addresses) -> Value {
162 let api = &addresses.api;
163 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root164 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'165 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'166 "openapi_url": format!("{api}/openapi.json"),
167 "mcp_url": addresses.mcp,
168 "current_user_url": format!("{api}/user"),
169 "workspaces_url": format!("{api}/workspaces"),
170 "repositories_url": format!("{api}/repos{{?q}}"),
171 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root172 "repository_url": repo,
173 "repository_events_url": format!("{repo}/events{{?before}}"),
174 "labels_url": format!("{repo}/labels"),
175 "issues_url": format!("{repo}/issues{{?state,label}}"),
176 "issue_url": format!("{repo}/issues/{{number}}"),
177 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
178 "pulls_url": format!("{repo}/pulls{{?state}}"),
179 "pull_url": format!("{repo}/pulls/{{number}}"),
180 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts181 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root182 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'183 "device_code_url": format!("{api}/device/code"),
184 "device_token_url": format!("{api}/device/token"),
185 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
186 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
187 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read188 "context_url": format!("{repo}/context{{?reference}}"),
189 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'190 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root191 })
192}
193
194// Signing in from a tool. Accounts are created, and passwords typed, only
195// in a browser; a tool gets its token by having a person approve a code.
196
Integrations: your own model provider, alerts that open issues, tickets agents read197/// Passes a request from an outside system to its connection, as it came:
198/// its signature covers the exact bytes of the body.
199async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
200 let headers: std::collections::HashMap<String, String> = request
201 .headers()
202 .entries()
203 .map(|(name, value)| (name.to_lowercase(), value))
204 .collect();
205 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look206 // A push to GitHub with many commits makes a large payload.
207 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
208 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API209 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read210 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look211 // g1t's GitHub App has one webhook for every installation; it is
212 // checked against the app's own secret.
213 let (method, args) = if id == "github" {
214 ("github_receive", json!({ "headers": headers, "body": body }))
215 } else {
216 ("receive", json!({ "id": id, "headers": headers, "body": body }))
217 };
218 let received: g1t_contracts::integrations::Received =
219 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 API220 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read221}
222
Stripe webhooks, enterprise invoices, and sudo for both223async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
224 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
225 let payload = request.text().await.unwrap_or_default();
226 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 API227 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both228 }
229 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
230 &env.service("BILLING")?,
231 "stripe_webhook",
232 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
233 )
234 .await?;
235 // A refusal is a 400, so Stripe shows it as failed; anything handled,
236 // or already handled, is a 200, so Stripe stops sending it.
237 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API238 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both239 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API240 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both241 }
242 })
243}
244
API and MCP server in Rust; a public index at the API root245async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
246 let body = json_body(request).await;
247 let started: DeviceStart = g1t_kit::call(
248 &services.identity,
249 "device_start",
250 &DeviceStartArgs {
251 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
252 },
253 )
254 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API255 reply(&json!({
API and MCP server in Rust; a public index at the API root256 "device_code": started.device_code,
257 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'258 "verification_uri": format!("{}/device", services.addresses.site),
259 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root260 "expires_in": started.expires_in,
261 "interval": started.interval,
262 }))
263}
264
265async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
266 let body = json_body(request).await;
267 let claim: DeviceClaim = g1t_kit::call(
268 &services.identity,
269 "device_claim",
270 &DeviceClaimArgs {
271 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
272 },
273 )
274 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API275 reply(&match claim {
API and MCP server in Rust; a public index at the API root276 DeviceClaim::Approved { token, user } => json!({
277 "status": "approved",
278 "token": token,
279 "username": user.username,
280 "verified": user.verified,
281 }),
282 DeviceClaim::Pending => json!({ "status": "pending" }),
283 DeviceClaim::Denied => json!({ "status": "denied" }),
284 DeviceClaim::Expired => json!({ "status": "expired" }),
285 })
286}
287
Fast pages, required checks on the branch, self-hosted runners, honest incidents288/// A sandbox reporting on a run of an issue's commands, from before a pull
289/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts290/// The run's own token, in the body, is the credential: it was given to
291/// that sandbox and to nothing else.
292async fn report_checks(
293 request: &mut Request,
294 services: &Services,
295 run_id: &str,
296) -> Result<Response> {
297 let body = json_body(request).await;
298 let reported: Outcome<CheckRun> = g1t_kit::call(
299 &services.work,
300 "report_checks",
301 &ReportChecksArgs {
302 run_id: run_id.to_owned(),
303 token: body["token"].as_str().unwrap_or_default().to_owned(),
304 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
305 error: body["error"].as_str().map(str::to_owned),
306 skip: false,
307 },
308 )
309 .await?;
310 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API311 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts312 Outcome::Fail(refused) => failure(&refused),
313 }
314}
315
Agents as a team: lifecycle, merge queue, billing and a new shell316/// A sandbox reporting one tested state of a merge queue. As with checks,
317/// the entry's own token is the credential.
318async fn report_queue(
319 request: &mut Request,
320 services: &Services,
321 entry_id: &str,
322) -> Result<Response> {
323 let body = json_body(request).await;
324 let reported: Outcome<QueueState> = g1t_kit::call(
325 &services.work,
326 "report_queue",
327 &ReportQueueArgs {
328 entry_id: entry_id.to_owned(),
329 token: body["token"].as_str().unwrap_or_default().to_owned(),
330 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
331 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
332 error: body["error"].as_str().map(str::to_owned),
333 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains334 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell335 },
336 )
337 .await?;
338 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API339 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell340 Outcome::Fail(refused) => failure(&refused),
341 }
342}
343
Agents and memory, checks and conflicts, profiles, slug renames, custom domains344/// A sandbox reporting whether a pull request merges cleanly. As with
345/// checks, the probe's own token is the credential.
346async fn report_mergecheck(
347 request: &mut Request,
348 services: &Services,
349 pull_id: &str,
350) -> Result<Response> {
351 let body = json_body(request).await;
352 let reported: Outcome<Mergeable> = g1t_kit::call(
353 &services.work,
354 "report_mergecheck",
355 &ReportMergecheckArgs {
356 pull_id: pull_id.to_owned(),
357 token: body["token"].as_str().unwrap_or_default().to_owned(),
358 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
359 error: body["error"].as_str().map(str::to_owned),
360 },
361 )
362 .await?;
363 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API364 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains365 Outcome::Fail(refused) => failure(&refused),
366 }
367}
368
Merge branch 'worktree-agent-ac5b181a013e54348'369/// A backup's sandbox, passed on to the repos service, which holds the
370/// job (services/repos/src/backups.rs; the flow is in
371/// `g1t_contracts::backups`):
372///
373/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
374/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
375/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
376/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
377///
378/// Bodies are passed through as they are: snake_case already, and a
379/// bundle's refs are keyed by ref names, which must not be converted.
380async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
381 use g1t_contracts::backups::TOKEN_HEADER;
382 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
383 let rest = path.trim_start_matches("/backups/");
384 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
385 if job.is_empty() || token.is_empty() {
386 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
387 }
388 if method == "PUT" && action.starts_with("parts/") {
389 let bytes = request.bytes().await?;
390 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
391 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
392 }
393 let headers = worker::Headers::new();
394 headers.set(TOKEN_HEADER, &token)?;
395 let mut init = worker::RequestInit::new();
396 init.with_method(Method::Put)
397 .with_headers(headers)
398 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
399 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
400 let mut answered = services.repos.fetch_request(forwarded).await?;
401 return outcome_as_given(answered.json().await?);
402 }
403 let rpc = match (method, action) {
404 ("POST", "spec") => "backup_spec",
405 ("POST", "complete") => "backup_complete",
406 ("POST", "fail") => "backup_fail",
407 _ => return fail(FailureCode::NotFound, "No such endpoint."),
408 };
409 let mut body = json_body(request).await;
410 if !body.is_object() {
411 body = json!({});
412 }
413 body["job_id"] = json!(job);
414 body["token"] = json!(token);
415 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
416 outcome_as_given(answered)
417}
418
419/// An `Outcome` from a service whose keys are already the API's: the value,
420/// or the failure in the shape every endpoint uses.
421fn outcome_as_given(answered: Value) -> Result<Response> {
422 match serde_json::from_value::<Outcome<Value>>(answered)? {
423 Outcome::Ok(value) => Response::from_json(&value),
424 Outcome::Fail(refused) => failure(&refused),
425 }
426}
427
Agents as a team: lifecycle, merge queue, billing and a new shell428/// A sandbox reporting the review its agent wrote. As with checks, the
429/// run's own token is the credential.
430async fn report_review(
431 request: &mut Request,
432 services: &Services,
433 run_id: &str,
434) -> Result<Response> {
435 let body = json_body(request).await;
436 let reported: Outcome<bool> = g1t_kit::call(
437 &services.work,
438 "report_review",
439 &ReportReviewArgs {
440 run_id: run_id.to_owned(),
441 token: body["token"].as_str().unwrap_or_default().to_owned(),
442 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
443 body: body["body"].as_str().unwrap_or_default().to_owned(),
444 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
445 model: body["model"].as_str().map(str::to_owned),
446 error: body["error"].as_str().map(str::to_owned),
447 },
448 )
449 .await?;
450 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API451 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell452 Outcome::Fail(refused) => failure(&refused),
453 }
454}
455
456/// A sandbox reporting the plan its agent wrote. As with checks, the
457/// plan's own token is the credential.
458async fn report_plan(
459 request: &mut Request,
460 services: &Services,
461 plan_id: &str,
462) -> Result<Response> {
463 let body = json_body(request).await;
464 let reported: Outcome<bool> = g1t_kit::call(
465 &services.work,
466 "report_plan",
467 &ReportPlanArgs {
468 plan_id: plan_id.to_owned(),
469 token: body["token"].as_str().unwrap_or_default().to_owned(),
470 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
471 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
472 error: body["error"].as_str().map(str::to_owned),
473 },
474 )
475 .await?;
476 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API477 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell478 Outcome::Fail(refused) => failure(&refused),
479 }
480}
481
482/// A sandbox reporting what its agent's run cost, so that the workspace
483/// it worked for is charged. As with checks, the run's own token is the
484/// credential.
485async fn report_usage(
486 request: &mut Request,
487 services: &Services,
488 run_id: &str,
489) -> Result<Response> {
490 let body = json_body(request).await;
491 let charged: Outcome<bool> = g1t_kit::call(
492 &services.billing,
493 "finish_run",
494 &FinishRunArgs {
495 run_id: run_id.to_owned(),
496 token: body["token"].as_str().unwrap_or_default().to_owned(),
497 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
498 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'499 // What the harness counted; the agent rate is charged on no
500 // fewer, on a workspace's own model key too.
501 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
502 input: t["input"].as_u64().unwrap_or_default(),
503 output: t["output"].as_u64().unwrap_or_default(),
504 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
505 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
506 }),
Agents as a team: lifecycle, merge queue, billing and a new shell507 },
508 )
509 .await?;
510 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API511 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell512 Outcome::Fail(refused) => failure(&refused),
513 }
514}
515
API and MCP server in Rust; a public index at the API root516async fn respond(mut request: Request, env: &Env) -> Result<Response> {
517 let method = method_name(request.method());
518 if method == "OPTIONS" {
519 return Ok(Response::empty()?.with_status(204));
520 }
521 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell522 // Paths carry no version. An earlier form began with `/v1`, which is
523 // still accepted so that nothing already written against it breaks.
524 let path = match url.path().strip_prefix("/v1") {
525 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
526 _ => url.path().to_owned(),
527 };
528 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'529 // MCP is a host of its own hosted, and may be a path on this one
530 // self-hosted (addresses.rs).
531 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root532
Stripe webhooks, enterprise invoices, and sudo for both533 // Stripe reporting to billing. Signed with the secret of the endpoint
534 // billing registered; the body goes through exactly as received, since
535 // the signature covers its bytes.
536 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
537 return receive_stripe(&mut request, env).await;
538 }
539
Integrations: your own model provider, alerts that open issues, tickets agents read540 // Outside systems reporting to a connection. They sign what they send
541 // with the connection's own secret, which is not a g1t token, so this
542 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide543 if method == "POST" && !on_mcp
544 && 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 read545 return receive_hook(&mut request, &services, id).await;
546 }
547
Deployments: a preview for every pull request, production on g1t.page548 // A sandbox building a deployment, reporting with its build's token,
549 // which is not a g1t token. The body goes through as it is: it can
550 // carry a Worker's bundled code.
551 if method == "POST" && !on_mcp
552 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
553 {
554 let target = format!("https://deployments/jobs/{rest}");
555 let body = request.bytes().await?;
556 let headers = worker::Headers::new();
557 headers.set("content-type", "application/json")?;
558 let mut init = worker::RequestInit::new();
559 init.with_method(Method::Post)
560 .with_headers(headers)
561 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run562 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page563 .service("DEPLOYMENTS")?
564 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run565 .await?;
566 // A fresh response: a fetched one's headers cannot be changed, and
567 // every response gets the API's own on the way out.
568 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API569 let bytes = answer.bytes().await?;
570 let bytes = match serde_json::from_slice::<Value>(&bytes) {
571 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
572 Err(_) => bytes,
573 };
574 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run575 .with_status(status)
576 .with_headers({
577 let headers = worker::Headers::new();
578 headers.set("content-type", "application/json")?;
579 headers
580 }));
Deployments: a preview for every pull request, production on g1t.page581 }
582
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2583 // The services GitHub's toolkit calls from inside a job, with its
584 // runtime token, and the links they hand out (toolkit.rs).
585 if !on_mcp && method == "POST"
586 && let Some(rest) = path.strip_prefix("/twirp/")
587 {
588 let (service, rpc) = rest.split_once('/').unwrap_or((rest, ""));
589 let (service, rpc) = (service.to_owned(), rpc.to_owned());
590 return toolkit::twirp(request, env, &services, &service, &rpc).await;
591 }
592 if !on_mcp && let Some(rest) = path.strip_prefix("/actions/toolkit/_apis/artifactcache/") {
593 let rest = rest.to_owned();
594 return toolkit::cache_v1(request, env, &services, method, &rest).await;
595 }
596 if !on_mcp && let Some(token) = path.strip_prefix("/actions/toolkit/blobs/") {
597 let token = token.to_owned();
598 return toolkit::blob(request, env, &services, method, &token).await;
599 }
600 // g1t as an OIDC issuer for workflow jobs (oidc.rs).
601 if !on_mcp && method == "GET" && path.starts_with("/actions/oidc/") {
602 return oidc::handle(&request, env, &services, &path).await;
603 }
604
A repository has its own sidebar, as settings do605 // A sandbox's artifacts and cache, with its job's token, which is not a
606 // g1t token either.
607 if !on_mcp
608 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents609 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do610 {
611 let rest = rest.to_owned();
612 return blobs::for_job(request, env, &services, method, &rest).await;
613 }
614
Fast pages, required checks on the branch, self-hosted runners, honest incidents615 // A self-hosted runner, with a registration token or its own
616 // credential, neither of which is a g1t access token.
617 if method == "POST"
618 && !on_mcp
619 && path.starts_with("/runners/")
620 && let Some(response) = runners::handle(&mut request, &services, &path).await?
621 {
622 return Ok(response);
623 }
624
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails625 // Per token, or per address without one (limits.rs).
626 if let Some(limited) = limits::limited(&request, env, method, &path, on_mcp).await? {
627 return Ok(limited);
628 }
API and MCP server in Rust; a public index at the API root629 let viewer = match authenticate(&request, &services).await? {
630 Ok(viewer) => viewer,
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails631 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 root632 };
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)633 // A person who has not confirmed their email address: who they are,
634 // their addresses, and confirming one, nothing else (REST or MCP).
635 if viewer.as_ref().is_some_and(User::awaits_confirmation) && !pending_may(method, &path, on_mcp) {
636 return fail(
637 FailureCode::Forbidden,
638 &g1t_contracts::accounts::confirm_email_first(&services.addresses.site),
639 );
640 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API641 services.audit = audit::AuditContext::of(&request, on_mcp);
642 // An agent's token: what it may do comes with it, on the composite
643 // identity identity resolved it to.
644 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
645 services.scope = Some(acting.scope.clone());
646 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell647 let header = request.headers().get("authorization")?.unwrap_or_default();
648 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
649 let scope: Option<AgentScope> = g1t_kit::call(
650 &services.identity,
651 "agent_scope",
652 &TokenArgs {
653 token: token.to_owned(),
654 },
655 )
656 .await?;
657 // A scope is what lets an agent's token do anything at all.
658 let Some(scope) = scope else {
659 return fail(FailureCode::Unauthenticated, "Invalid access token.");
660 };
661 services.scope = Some(scope);
662 }
API and MCP server in Rust; a public index at the API root663 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
664 return Ok(response);
665 }
666 if on_mcp {
667 return mcp::handle(request, &services, &viewer).await;
668 }
669
Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009)670 // Workflow logs to download: a run's as a zip, a job's as text (logs.rs).
671 if method == "GET" {
672 let text = url.query_pairs().any(|(name, value)| name == "format" && value == "text");
673 if let Some(wanted) = logs::wanted(&path, text) {
674 return logs::download(&services, &viewer, wanted).await;
675 }
676 }
677
API and MCP server in Rust; a public index at the API root678 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'679 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root680 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2681 // One of a run's artifacts downloaded by name (the run's artifacts
682 // are listed by the REST route in rest.rs).
683 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts/") => {
A repository has its own sidebar, as settings do684 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2685 if let [owner, repo, "actions", "runs", run, "artifacts", name] = parts.as_slice() {
Merge branch 'worktree-agent-a3abfcce648e87dca'686 // A workflow job's token reaches its own repository only.
687 if viewer
688 .as_ref()
689 .and_then(|user| user.token.as_deref())
690 .is_some_and(|token| !token.reaches(&format!("{owner}/{repo}")))
691 {
692 return fail(FailureCode::NotFound, "No such run.");
693 }
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2694 return blobs::download(env, &services, &viewer, owner, repo, run, name).await;
A repository has its own sidebar, as settings do695 }
696 }
Agents as a team: lifecycle, merge queue, billing and a new shell697 ("POST", "/device/code") => return device_code(&mut request, &services).await,
698 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically699 // Where a pull request lives, for a tool that knows only its fork.
700 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
701 let located: Outcome<Value> = g1t_kit::call(
702 &services.work,
703 "locate_pull",
704 &json!({ "id": &path[7..], "viewer": viewer }),
705 )
706 .await?;
707 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API708 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically709 Outcome::Fail(refused) => failure(&refused),
710 };
711 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains712 ("POST", path) if path.starts_with("/mergechecks/") => {
713 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
714 return report_mergecheck(&mut request, &services, &pull_id).await;
715 }
Merge branch 'worktree-agent-ac5b181a013e54348'716 // A sandbox making a repository's nightly backup. The job's own
717 // token, in its header, is the credential.
718 (method, path) if path.starts_with("/backups/") => {
719 return backup_job(&mut request, &services, method, path).await;
720 }
Agents as a team: lifecycle, merge queue, billing and a new shell721 ("POST", path) if path.starts_with("/queue/") => {
722 let entry_id = path.trim_start_matches("/queue/").to_owned();
723 return report_queue(&mut request, &services, &entry_id).await;
724 }
GitHub Actions on g1t, part two: running workflows725 // A sandbox running a GitHub Actions job: fetching the job, and
726 // reporting how it goes. The job's own token is the credential.
727 ("POST", path) if path.starts_with("/actions/jobs/") => {
728 let rest = path.trim_start_matches("/actions/jobs/");
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts729 // `/action`: where to fetch another repository's action from (on
730 // g1t, with a read token for a private one, or GitHub).
731 let (job, method) = match (rest.strip_suffix("/spec"), rest.strip_suffix("/action")) {
732 (Some(job), _) => (job.to_owned(), "job_spec"),
733 (_, Some(job)) => (job.to_owned(), "job_action"),
734 _ => (rest.to_owned(), "job_report"),
GitHub Actions on g1t, part two: running workflows735 };
736 let body = json_body(&mut request).await;
737 let answered: Outcome<Value> = g1t_kit::call(
738 &services.actions,
739 method,
740 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
741 )
742 .await?;
743 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API744 // A job's spec is the workflow and its contexts as GitHub
745 // has them; only g1t's own keys around them are converted.
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2746 Outcome::Ok(value) => {
747 let mut spec = wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN);
748 with_runtime(&mut spec, &services.addresses.api, oidc::configured(env));
749 Response::from_json(&spec)
750 }
GitHub Actions on g1t, part two: running workflows751 Outcome::Fail(refused) => failure(&refused),
752 };
753 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains754 // A sandbox reporting its agent run's steps, cost and end. As with
755 // checks, the run's own token, in the body, is the credential.
756 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
757 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
758 let mut body = json_body(&mut request).await;
759 if !body.is_object() {
760 body = json!({});
761 }
762 body["runId"] = json!(run_id);
763 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
764 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API765 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains766 Outcome::Fail(refused) => failure(&refused),
767 };
768 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API769 // What a run's agent learned, as memory candidates; the same token.
770 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
771 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
772 let body = json_body(&mut request).await;
773 let learned = json!({
774 "runId": run_id,
775 "token": body["token"].as_str().unwrap_or_default(),
776 "items": body["items"].as_array().cloned().unwrap_or_default(),
777 });
778 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
779 return match captured {
780 Outcome::Ok(captured) => reply(&captured),
781 Outcome::Fail(refused) => failure(&refused),
782 };
783 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step784 // How sure a run's agent is of its change; the same token.
785 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
786 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
787 let body = json_body(&mut request).await;
788 let said = json!({
789 "runId": run_id,
790 "token": body["token"].as_str().unwrap_or_default(),
791 "confidence": body["confidence"].as_str().unwrap_or_default(),
792 "uncertainAbout": body["uncertain_about"]
793 .as_array()
794 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
795 .unwrap_or_default(),
796 });
797 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
798 return match recorded {
799 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
800 Outcome::Fail(refused) => failure(&refused),
801 };
802 }
Agents as a team: lifecycle, merge queue, billing and a new shell803 ("POST", path) if path.starts_with("/checks/") => {
804 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts805 return report_checks(&mut request, &services, &run_id).await;
806 }
Agents as a team: lifecycle, merge queue, billing and a new shell807 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
808 let run_id = path
809 .trim_start_matches("/runs/")
810 .trim_end_matches("/usage")
811 .to_owned();
812 return report_usage(&mut request, &services, &run_id).await;
813 }
814 ("POST", path) if path.starts_with("/plans/") => {
815 let plan_id = path.trim_start_matches("/plans/").to_owned();
816 return report_plan(&mut request, &services, &plan_id).await;
817 }
818 ("POST", path) if path.starts_with("/reviews/") => {
819 let run_id = path.trim_start_matches("/reviews/").to_owned();
820 return report_review(&mut request, &services, &run_id).await;
821 }
API and MCP server in Rust; a public index at the API root822 _ => {}
823 }
824
825 let query: Vec<(String, String)> = url
826 .query_pairs()
827 .map(|(name, value)| (name.into_owned(), value.into_owned()))
828 .collect();
829 let body = if method == "GET" {
830 Value::Null
831 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell832 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root833 };
834 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
835 return fail(FailureCode::NotFound, "No such endpoint.");
836 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API837 match audit::run(route.op, &services, &viewer, &input).await? {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2838 // A download is a redirect to its signed link, as GitHub's is.
839 Outcome::Ok(value) if route.op == operations::Op::Artifacts(artifacts::ArtifactsOp::DownloadArtifact) => {
840 match value["url"].as_str().and_then(|url| worker::Url::parse(url).ok()) {
841 Some(url) => Response::redirect_with_status(url, 302),
842 None => reply(&value),
843 }
844 }
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts845 // A deleted comment has nothing to say, as GitHub's says nothing.
846 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 API847 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 step848 // A token without the scope a call needs is told which one.
849 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
850 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
851 "error": {
852 "code": refused.code,
853 "message": refused.message,
854 "needed_scope": scope.as_str(),
855 }
856 }))?
857 .with_status(403)),
858 _ => failure(&refused),
859 },
API and MCP server in Rust; a public index at the API root860 }
861}
862
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API863/// Request bodies take the same keys as the MCP tools, `snake_case`, as
864/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell865fn snake_case_keys(body: Value) -> Value {
866 let Value::Object(fields) = body else {
867 return body;
868 };
869 let mut out = serde_json::Map::new();
870 for (key, value) in fields {
871 let mut snake = String::with_capacity(key.len() + 4);
872 for c in key.chars() {
873 if c.is_ascii_uppercase() {
874 snake.push('_');
875 snake.push(c.to_ascii_lowercase());
876 } else {
877 snake.push(c);
878 }
879 }
880 // A key given in both spellings keeps the snake_case one.
881 if snake != key && out.contains_key(&snake) {
882 continue;
883 }
884 out.insert(snake, value);
885 }
886 Value::Object(out)
887}
888
889#[cfg(test)]
890mod tests {
891 use super::snake_case_keys;
892 use serde_json::json;
893
894 #[test]
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)895 fn an_unconfirmed_account_may_only_see_itself_and_confirm_its_address() {
896 assert!(super::pending_may("GET", "/user", false));
897 assert!(super::pending_may("GET", "/user/emails/", false));
898 assert!(super::pending_may("POST", "/user/emails/confirm", false));
899 assert!(!super::pending_may("POST", "/user/emails", false));
900 assert!(!super::pending_may("POST", "/workspaces", false));
901 assert!(!super::pending_may("GET", "/repos/acme/rocket", false));
902 assert!(!super::pending_may("POST", "/user/emails/confirm", true));
903 assert!(!super::pending_may("POST", "/", true));
904 }
905
906 #[test]
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2907 fn a_job_spec_gets_the_toolkits_variables() {
908 // As the actions service sends it, converted as the API does.
909 let sent = json!({ "variables": { "GITHUB_SHA": "abc" }, "runtime": { "token": "h.p.s", "idToken": true } });
910 let mut spec = g1t_kit::wire::snake_case_keeping(sent.clone(), super::JOB_SPEC_AS_GIVEN);
911 super::with_runtime(&mut spec, "https://api.g1t.sh", true);
912 assert!(spec.get("runtime").is_none(), "the runner never sees it");
913 let vars = &spec["variables"];
914 assert_eq!(vars["GITHUB_SHA"], "abc");
915 assert_eq!(vars["ACTIONS_RUNTIME_TOKEN"], "h.p.s");
916 assert_eq!(vars["ACTIONS_CACHE_URL"], "https://api.g1t.sh/actions/toolkit/");
917 assert_eq!(vars["ACTIONS_ID_TOKEN_REQUEST_TOKEN"], "h.p.s");
918 // No OIDC key here: no OIDC variables, whatever the job may do.
919 let mut spec = g1t_kit::wire::snake_case_keeping(sent, super::JOB_SPEC_AS_GIVEN);
920 super::with_runtime(&mut spec, "https://api.g1t.sh", false);
921 assert!(spec["variables"].get("ACTIONS_ID_TOKEN_REQUEST_URL").is_none());
922 assert_eq!(spec["variables"]["ACTIONS_RESULTS_URL"], "https://api.g1t.sh/");
923 }
924
925 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell926 fn camel_case_keys_are_accepted() {
927 assert_eq!(
928 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
929 json!({ "count_agent_approvals": false, "title": "x" })
930 );
931 }
932
933 #[test]
934 fn snake_case_wins_when_both_are_given() {
935 assert_eq!(
936 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
937 json!({ "keep_issue_open": true })
938 );
939 }
940}
941
API and MCP server in Rust; a public index at the API root942// The API is called from browsers too: the reference's explorer, and apps
943// built on g1t. It carries no cookies, so any origin may call it.
944#[event(fetch)]
945async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
946 let mut response = respond(request, &env).await?;
947 let headers = response.headers_mut();
948 headers.set("access-control-allow-origin", "*")?;
949 headers.set(
950 "access-control-allow-headers",
951 "authorization, content-type",
952 )?;
953 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails954 headers.set("access-control-expose-headers", "www-authenticate, retry-after")?;
API and MCP server in Rust; a public index at the API root955 Ok(response)
956}

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