Skip to content
988 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.

Workspace names and icons, and a component kit for every control1//! 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;
The artifacts service is services/artifacts, the Worker g1t-artifacts, bound as ARTIFACTS by the API, the site and the agents; its live rooms move to it with a Durable Object transfer from g1t-docs-service, and its database, bucket, indexes and queue keep their names. The git store's binding and settings are GITSTORE, its ops scripts gitstore-*, and workflow run artifacts keep their compatible API under run_artifacts modules. The deploy tool puts a Worker that has never deployed before the Workers in its stage that bind to it, and the deploy guide gives the cutover runbook.8mod run_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;
Workspace names and icons, and a component kit for every control13mod blobs;
Merge checks: statuses and check runs on every commit14mod checks;
Merge branch 'customize' into main: Customize replaces the Marketplace, the Artifacts trash and spaces changes, the Security-free cleanup, with the desktop app's own title bar kept in the shell.15mod customize;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9716mod deployments;
Merge branch 'worktree-agent-a5a5de74d8863d554' into worktree-agent-a16631325aecf58ca17mod deploy_keys;
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails18mod limits;
Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009)19mod logs;
Merge branch 'mirroring' into artifacts-mode20mod mirrors;
Workspace names and icons, and a component kit for every control21mod mcp;
API: notifications over REST and MCP, with notifications scopes22mod notifications;
Workspace names and icons, and a component kit for every control23mod oauth;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R224mod oidc;
Merge packages: roles, Actions access, source label, soft delete, API25mod packages;
Merge main into Artifacts Phase 226mod folios;
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar27mod people;
Workspace names and icons, and a component kit for every control28mod openapi;
API: pinned projects over REST and MCP29mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9730mod projects;
Merge branch 'worktree-agent-a3abfcce648e87dca'31mod protection;
Workspace names and icons, and a component kit for every control32mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains33mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API34#[cfg(test)]
35mod responses;
Workspace names and icons, and a component kit for every control36mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge37mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents38mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar39mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step40mod tools;
API and MCP for a workspace's personal access token rules, members' tokens and approvals41mod token_policy;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R242mod toolkit;
Workspace names and icons, and a component kit for every control43
Merge branch 'model-routing'44use g1t_contracts::billing::{FinishRunArgs, RunTokens};
Workspace names and icons, and a component kit for every control45use g1t_contracts::identity::{
46 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
47};
48use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains49 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
50 ReportQueueArgs, ReportReviewArgs,
Workspace names and icons, and a component kit for every control51};
52use g1t_contracts::identity::AgentScope;
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)53use 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 API54use g1t_kit::wire;
Workspace names and icons, and a component kit for every control55use serde_json::{Value, json};
56use worker::{Context, Env, Method, Request, Response, Result, event};
57
58use operations::Services;
59
60fn method_name(method: Method) -> &'static str {
61 match method {
62 Method::Get => "GET",
63 Method::Post => "POST",
64 Method::Patch => "PATCH",
65 Method::Put => "PUT",
66 Method::Delete => "DELETE",
67 Method::Options => "OPTIONS",
68 Method::Head => "HEAD",
69 _ => "OTHER",
70 }
71}
72
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API73/// A JSON response. Every body the API sends has its keys in `snake_case`;
74/// the contracts it passes through are `camelCase`, so they are converted
75/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
76/// the MCP protocol's own envelope keep the spelling their standards use.
77pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
78 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
79}
80
81/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
82/// workflow file, GitHub's contexts and event, and where to check out, all
83/// passed through as they are.
84const JOB_SPEC_AS_GIVEN: &[&str] = &[
Merge branch 'worktree-agent-a3abfcce648e87dca'85 "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 API86];
87
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R288/// Puts the toolkit's variables in a job's spec: its runtime token, where
89/// the toolkit's services are, and where to ask for an OIDC token when the
90/// job may have one and this installation issues them. The `runtime` the
91/// actions service sent goes no further.
92fn with_runtime(spec: &mut Value, api: &str, oidc: bool) {
93 let Some(runtime) = spec.as_object_mut().and_then(|s| s.remove("runtime")) else { return };
94 let Some(token) = runtime["token"].as_str().filter(|t| !t.is_empty()) else { return };
95 let id_token = oidc && runtime["id_token"].as_bool() == Some(true);
96 let vars = toolkit::runtime_variables(api, token, id_token);
97 if let Some(variables) = spec.get_mut("variables").and_then(Value::as_object_mut) {
98 variables.extend(vars);
99 }
100}
101
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)102/// What a person whose account has not confirmed its email address may
103/// call: who they are, their addresses, and confirming one with the code
104/// from the email. Nothing over MCP.
105fn pending_may(method: &str, path: &str, on_mcp: bool) -> bool {
106 !on_mcp
107 && matches!(
108 (method, path.trim_end_matches('/')),
109 ("GET", "/user") | ("GET", "/user/emails") | ("POST", "/user/emails/confirm")
110 )
111}
112
Workspace names and icons, and a component kit for every control113/// An error in the shape every endpoint uses.
114fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API115 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
Workspace names and icons, and a component kit for every control116}
117
118fn fail(code: FailureCode, message: &str) -> Result<Response> {
119 failure(&Failure {
120 code,
121 message: message.to_owned(),
122 })
123}
124
125/// A request body as JSON. An empty or malformed body is no input.
126async fn json_body(request: &mut Request) -> Value {
127 request.json().await.unwrap_or(Value::Null)
128}
129
130/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
131/// an anonymous viewer; a wrong one is refused, so that a typo does not
132/// silently look signed out.
133async fn authenticate(
134 request: &Request,
135 services: &Services,
136) -> Result<std::result::Result<Viewer, Response>> {
137 let header = request.headers().get("authorization")?.unwrap_or_default();
138 let token = match header.split_once(' ') {
139 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
140 token.trim()
141 }
142 _ => return Ok(Ok(None)),
143 };
144 let viewer: Viewer = g1t_kit::call(
145 &services.identity,
146 "user_for_access_token",
147 &TokenArgs {
148 token: token.to_owned(),
149 },
150 )
151 .await?;
152 if viewer.is_some() {
153 return Ok(Ok(viewer));
154 }
155 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
156 // Tells an MCP client where to sign in again.
157 response.headers_mut().set(
158 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'159 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
Workspace names and icons, and a component kit for every control160 )?;
161 Ok(Err(response))
162}
163
164/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'165fn index(addresses: &addresses::Addresses) -> Value {
166 let api = &addresses.api;
167 let repo = format!("{api}/repos/{{owner}}/{{name}}");
Workspace names and icons, and a component kit for every control168 json!({
169 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'170 "openapi_url": format!("{api}/openapi.json"),
171 "mcp_url": addresses.mcp,
172 "current_user_url": format!("{api}/user"),
173 "workspaces_url": format!("{api}/workspaces"),
174 "repositories_url": format!("{api}/repos{{?q}}"),
175 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
Workspace names and icons, and a component kit for every control176 "repository_url": repo,
177 "repository_events_url": format!("{repo}/events{{?before}}"),
178 "labels_url": format!("{repo}/labels"),
179 "issues_url": format!("{repo}/issues{{?state,label}}"),
180 "issue_url": format!("{repo}/issues/{{number}}"),
181 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
182 "pulls_url": format!("{repo}/pulls{{?state}}"),
183 "pull_url": format!("{repo}/pulls/{{number}}"),
184 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
185 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
186 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'187 "device_code_url": format!("{api}/device/code"),
188 "device_token_url": format!("{api}/device/token"),
189 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
190 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
191 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Workspace names and icons, and a component kit for every control192 "context_url": format!("{repo}/context{{?reference}}"),
193 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'194 "hooks_url": format!("{api}/hooks/{{integration}}"),
Workspace names and icons, and a component kit for every control195 })
196}
197
198// Signing in from a tool. Accounts are created, and passwords typed, only
199// in a browser; a tool gets its token by having a person approve a code.
200
201/// Passes a request from an outside system to its connection, as it came:
202/// its signature covers the exact bytes of the body.
203async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
204 let headers: std::collections::HashMap<String, String> = request
205 .headers()
206 .entries()
207 .map(|(name, value)| (name.to_lowercase(), value))
208 .collect();
209 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look210 // A push to GitHub with many commits makes a large payload.
211 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
212 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API213 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Workspace names and icons, and a component kit for every control214 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look215 // g1t's GitHub App has one webhook for every installation; it is
216 // checked against the app's own secret.
217 let (method, args) = if id == "github" {
218 ("github_receive", json!({ "headers": headers, "body": body }))
219 } else {
220 ("receive", json!({ "id": id, "headers": headers, "body": body }))
221 };
222 let received: g1t_contracts::integrations::Received =
223 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 API224 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Workspace names and icons, and a component kit for every control225}
226
227async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
228 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
229 let payload = request.text().await.unwrap_or_default();
230 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 API231 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Workspace names and icons, and a component kit for every control232 }
233 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
234 &env.service("BILLING")?,
235 "stripe_webhook",
236 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
237 )
238 .await?;
239 // A refusal is a 400, so Stripe shows it as failed; anything handled,
240 // or already handled, is a 200, so Stripe stops sending it.
241 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API242 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Workspace names and icons, and a component kit for every control243 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API244 reply(&json!({ "message": failure.message }))?.with_status(400)
Workspace names and icons, and a component kit for every control245 }
246 })
247}
248
249async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
250 let body = json_body(request).await;
251 let started: DeviceStart = g1t_kit::call(
252 &services.identity,
253 "device_start",
254 &DeviceStartArgs {
255 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
256 },
257 )
258 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API259 reply(&json!({
Workspace names and icons, and a component kit for every control260 "device_code": started.device_code,
261 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'262 "verification_uri": format!("{}/device", services.addresses.site),
263 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
Workspace names and icons, and a component kit for every control264 "expires_in": started.expires_in,
265 "interval": started.interval,
266 }))
267}
268
269async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
270 let body = json_body(request).await;
271 let claim: DeviceClaim = g1t_kit::call(
272 &services.identity,
273 "device_claim",
274 &DeviceClaimArgs {
275 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
276 },
277 )
278 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API279 reply(&match claim {
Workspace names and icons, and a component kit for every control280 DeviceClaim::Approved { token, user } => json!({
281 "status": "approved",
282 "token": token,
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar283 "display_username": user.display_username.clone().filter(|display| display.eq_ignore_ascii_case(&user.username)).unwrap_or_else(|| user.username.clone()),
Workspace names and icons, and a component kit for every control284 "username": user.username,
285 "verified": user.verified,
286 }),
287 DeviceClaim::Pending => json!({ "status": "pending" }),
288 DeviceClaim::Denied => json!({ "status": "denied" }),
289 DeviceClaim::Expired => json!({ "status": "expired" }),
290 })
291}
292
Fast pages, required checks on the branch, self-hosted runners, honest incidents293/// A sandbox reporting on a run of an issue's commands, from before a pull
294/// request's checks were the workflows run on it.
Workspace names and icons, and a component kit for every control295/// The run's own token, in the body, is the credential: it was given to
296/// that sandbox and to nothing else.
297async fn report_checks(
298 request: &mut Request,
299 services: &Services,
300 run_id: &str,
301) -> Result<Response> {
302 let body = json_body(request).await;
303 let reported: Outcome<CheckRun> = g1t_kit::call(
304 &services.work,
305 "report_checks",
306 &ReportChecksArgs {
307 run_id: run_id.to_owned(),
308 token: body["token"].as_str().unwrap_or_default().to_owned(),
309 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
310 error: body["error"].as_str().map(str::to_owned),
311 skip: false,
312 },
313 )
314 .await?;
315 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API316 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Workspace names and icons, and a component kit for every control317 Outcome::Fail(refused) => failure(&refused),
318 }
319}
320
321/// A sandbox reporting one tested state of a merge queue. As with checks,
322/// the entry's own token is the credential.
323async fn report_queue(
324 request: &mut Request,
325 services: &Services,
326 entry_id: &str,
327) -> Result<Response> {
328 let body = json_body(request).await;
329 let reported: Outcome<QueueState> = g1t_kit::call(
330 &services.work,
331 "report_queue",
332 &ReportQueueArgs {
333 entry_id: entry_id.to_owned(),
334 token: body["token"].as_str().unwrap_or_default().to_owned(),
335 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
336 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
337 error: body["error"].as_str().map(str::to_owned),
338 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains339 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Workspace names and icons, and a component kit for every control340 },
341 )
342 .await?;
343 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API344 Outcome::Ok(state) => reply(&json!({ "state": state })),
Workspace names and icons, and a component kit for every control345 Outcome::Fail(refused) => failure(&refused),
346 }
347}
348
Agents and memory, checks and conflicts, profiles, slug renames, custom domains349/// A sandbox reporting whether a pull request merges cleanly. As with
350/// checks, the probe's own token is the credential.
351async fn report_mergecheck(
352 request: &mut Request,
353 services: &Services,
354 pull_id: &str,
355) -> Result<Response> {
356 let body = json_body(request).await;
357 let reported: Outcome<Mergeable> = g1t_kit::call(
358 &services.work,
359 "report_mergecheck",
360 &ReportMergecheckArgs {
361 pull_id: pull_id.to_owned(),
362 token: body["token"].as_str().unwrap_or_default().to_owned(),
363 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
364 error: body["error"].as_str().map(str::to_owned),
365 },
366 )
367 .await?;
368 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API369 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains370 Outcome::Fail(refused) => failure(&refused),
371 }
372}
373
Merge branch 'worktree-agent-ac5b181a013e54348'374/// A backup's sandbox, passed on to the repos service, which holds the
375/// job (services/repos/src/backups.rs; the flow is in
376/// `g1t_contracts::backups`):
377///
378/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
379/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
380/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
381/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
382///
383/// Bodies are passed through as they are: snake_case already, and a
384/// bundle's refs are keyed by ref names, which must not be converted.
385async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
386 use g1t_contracts::backups::TOKEN_HEADER;
387 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
388 let rest = path.trim_start_matches("/backups/");
389 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
390 if job.is_empty() || token.is_empty() {
391 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
392 }
393 if method == "PUT" && action.starts_with("parts/") {
394 let bytes = request.bytes().await?;
395 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
396 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
397 }
398 let headers = worker::Headers::new();
399 headers.set(TOKEN_HEADER, &token)?;
400 let mut init = worker::RequestInit::new();
401 init.with_method(Method::Put)
402 .with_headers(headers)
403 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
404 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
405 let mut answered = services.repos.fetch_request(forwarded).await?;
406 return outcome_as_given(answered.json().await?);
407 }
408 let rpc = match (method, action) {
409 ("POST", "spec") => "backup_spec",
410 ("POST", "complete") => "backup_complete",
411 ("POST", "fail") => "backup_fail",
412 _ => return fail(FailureCode::NotFound, "No such endpoint."),
413 };
414 let mut body = json_body(request).await;
415 if !body.is_object() {
416 body = json!({});
417 }
418 body["job_id"] = json!(job);
419 body["token"] = json!(token);
420 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
421 outcome_as_given(answered)
422}
423
424/// An `Outcome` from a service whose keys are already the API's: the value,
425/// or the failure in the shape every endpoint uses.
426fn outcome_as_given(answered: Value) -> Result<Response> {
427 match serde_json::from_value::<Outcome<Value>>(answered)? {
428 Outcome::Ok(value) => Response::from_json(&value),
429 Outcome::Fail(refused) => failure(&refused),
430 }
431}
432
Workspace names and icons, and a component kit for every control433/// A sandbox reporting the review its agent wrote. As with checks, the
434/// run's own token is the credential.
435async fn report_review(
436 request: &mut Request,
437 services: &Services,
438 run_id: &str,
439) -> Result<Response> {
440 let body = json_body(request).await;
441 let reported: Outcome<bool> = g1t_kit::call(
442 &services.work,
443 "report_review",
444 &ReportReviewArgs {
445 run_id: run_id.to_owned(),
446 token: body["token"].as_str().unwrap_or_default().to_owned(),
447 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
448 body: body["body"].as_str().unwrap_or_default().to_owned(),
449 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
450 model: body["model"].as_str().map(str::to_owned),
451 error: body["error"].as_str().map(str::to_owned),
452 },
453 )
454 .await?;
455 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API456 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Workspace names and icons, and a component kit for every control457 Outcome::Fail(refused) => failure(&refused),
458 }
459}
460
461/// A sandbox reporting the plan its agent wrote. As with checks, the
462/// plan's own token is the credential.
463async fn report_plan(
464 request: &mut Request,
465 services: &Services,
466 plan_id: &str,
467) -> Result<Response> {
468 let body = json_body(request).await;
469 let reported: Outcome<bool> = g1t_kit::call(
470 &services.work,
471 "report_plan",
472 &ReportPlanArgs {
473 plan_id: plan_id.to_owned(),
474 token: body["token"].as_str().unwrap_or_default().to_owned(),
475 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
476 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
477 error: body["error"].as_str().map(str::to_owned),
478 },
479 )
480 .await?;
481 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API482 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Workspace names and icons, and a component kit for every control483 Outcome::Fail(refused) => failure(&refused),
484 }
485}
486
487/// A sandbox reporting what its agent's run cost, so that the workspace
488/// it worked for is charged. As with checks, the run's own token is the
489/// credential.
490async fn report_usage(
491 request: &mut Request,
492 services: &Services,
493 run_id: &str,
494) -> Result<Response> {
495 let body = json_body(request).await;
496 let charged: Outcome<bool> = g1t_kit::call(
497 &services.billing,
498 "finish_run",
499 &FinishRunArgs {
500 run_id: run_id.to_owned(),
501 token: body["token"].as_str().unwrap_or_default().to_owned(),
502 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
503 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'504 // What the harness counted; the agent rate is charged on no
505 // fewer, on a workspace's own model key too.
506 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
507 input: t["input"].as_u64().unwrap_or_default(),
508 output: t["output"].as_u64().unwrap_or_default(),
509 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
510 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
511 }),
Workspace names and icons, and a component kit for every control512 },
513 )
514 .await?;
515 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API516 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Workspace names and icons, and a component kit for every control517 Outcome::Fail(refused) => failure(&refused),
518 }
519}
520
521async fn respond(mut request: Request, env: &Env) -> Result<Response> {
522 let method = method_name(request.method());
523 if method == "OPTIONS" {
524 return Ok(Response::empty()?.with_status(204));
525 }
526 let url = request.url()?;
527 // Paths carry no version. An earlier form began with `/v1`, which is
528 // still accepted so that nothing already written against it breaks.
529 let path = match url.path().strip_prefix("/v1") {
530 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
531 _ => url.path().to_owned(),
532 };
533 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'534 // MCP is a host of its own hosted, and may be a path on this one
535 // self-hosted (addresses.rs).
536 let on_mcp = services.addresses.mcp_path(&url).is_some();
Workspace names and icons, and a component kit for every control537
538 // Stripe reporting to billing. Signed with the secret of the endpoint
539 // billing registered; the body goes through exactly as received, since
540 // the signature covers its bytes.
541 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
542 return receive_stripe(&mut request, env).await;
543 }
544
545 // Outside systems reporting to a connection. They sign what they send
546 // with the connection's own secret, which is not a g1t token, so this
547 // comes before anything that would read one.
548 if method == "POST" && !on_mcp
549 && let Some(id) = path.strip_prefix("/hooks/").filter(|id| !id.is_empty() && !id.contains('/')) {
550 return receive_hook(&mut request, &services, id).await;
551 }
552
553 // A sandbox building a deployment, reporting with its build's token,
554 // which is not a g1t token. The body goes through as it is: it can
555 // carry a Worker's bundled code.
556 if method == "POST" && !on_mcp
557 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
558 {
559 let target = format!("https://deployments/jobs/{rest}");
560 let body = request.bytes().await?;
561 let headers = worker::Headers::new();
562 headers.set("content-type", "application/json")?;
563 let mut init = worker::RequestInit::new();
564 init.with_method(Method::Post)
565 .with_headers(headers)
566 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
567 let mut answer = env
568 .service("DEPLOYMENTS")?
569 .fetch_request(Request::new_with_init(&target, &init)?)
570 .await?;
571 // A fresh response: a fetched one's headers cannot be changed, and
572 // every response gets the API's own on the way out.
573 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API574 let bytes = answer.bytes().await?;
575 let bytes = match serde_json::from_slice::<Value>(&bytes) {
576 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
577 Err(_) => bytes,
578 };
579 return Ok(Response::from_bytes(bytes)?
Workspace names and icons, and a component kit for every control580 .with_status(status)
581 .with_headers({
582 let headers = worker::Headers::new();
583 headers.set("content-type", "application/json")?;
584 headers
585 }));
586 }
587
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2588 // The services GitHub's toolkit calls from inside a job, with its
589 // runtime token, and the links they hand out (toolkit.rs).
590 if !on_mcp && method == "POST"
591 && let Some(rest) = path.strip_prefix("/twirp/")
592 {
593 let (service, rpc) = rest.split_once('/').unwrap_or((rest, ""));
594 let (service, rpc) = (service.to_owned(), rpc.to_owned());
595 return toolkit::twirp(request, env, &services, &service, &rpc).await;
596 }
597 if !on_mcp && let Some(rest) = path.strip_prefix("/actions/toolkit/_apis/artifactcache/") {
598 let rest = rest.to_owned();
599 return toolkit::cache_v1(request, env, &services, method, &rest).await;
600 }
601 if !on_mcp && let Some(token) = path.strip_prefix("/actions/toolkit/blobs/") {
602 let token = token.to_owned();
603 return toolkit::blob(request, env, &services, method, &token).await;
604 }
605 // g1t as an OIDC issuer for workflow jobs (oidc.rs).
606 if !on_mcp && method == "GET" && path.starts_with("/actions/oidc/") {
607 return oidc::handle(&request, env, &services, &path).await;
608 }
609
Workspace names and icons, and a component kit for every control610 // A sandbox's artifacts and cache, with its job's token, which is not a
611 // g1t token either.
612 if !on_mcp
613 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents614 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
Workspace names and icons, and a component kit for every control615 {
616 let rest = rest.to_owned();
617 return blobs::for_job(request, env, &services, method, &rest).await;
618 }
619
Fast pages, required checks on the branch, self-hosted runners, honest incidents620 // A self-hosted runner, with a registration token or its own
621 // credential, neither of which is a g1t access token.
622 if method == "POST"
623 && !on_mcp
624 && path.starts_with("/runners/")
625 && let Some(response) = runners::handle(&mut request, &services, &path).await?
626 {
627 return Ok(response);
628 }
629
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails630 // Per token, or per address without one (limits.rs).
631 if let Some(limited) = limits::limited(&request, env, method, &path, on_mcp).await? {
632 return Ok(limited);
633 }
Workspace names and icons, and a component kit for every control634 let viewer = match authenticate(&request, &services).await? {
635 Ok(viewer) => viewer,
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails636 Err(refused) => return Ok(limits::wrong_token(&request, env, on_mcp).await?.unwrap_or(refused)),
Workspace names and icons, and a component kit for every control637 };
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)638 // A person who has not confirmed their email address: who they are,
639 // their addresses, and confirming one, nothing else (REST or MCP).
640 if viewer.as_ref().is_some_and(User::awaits_confirmation) && !pending_may(method, &path, on_mcp) {
641 return fail(
642 FailureCode::Forbidden,
643 &g1t_contracts::accounts::confirm_email_first(&services.addresses.site),
644 );
645 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API646 services.audit = audit::AuditContext::of(&request, on_mcp);
647 // An agent's token: what it may do comes with it, on the composite
648 // identity identity resolved it to.
649 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
650 services.scope = Some(acting.scope.clone());
651 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Workspace names and icons, and a component kit for every control652 let header = request.headers().get("authorization")?.unwrap_or_default();
653 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
654 let scope: Option<AgentScope> = g1t_kit::call(
655 &services.identity,
656 "agent_scope",
657 &TokenArgs {
658 token: token.to_owned(),
659 },
660 )
661 .await?;
662 // A scope is what lets an agent's token do anything at all.
663 let Some(scope) = scope else {
664 return fail(FailureCode::Unauthenticated, "Invalid access token.");
665 };
666 services.scope = Some(scope);
667 }
668 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
669 return Ok(response);
670 }
671 if on_mcp {
672 return mcp::handle(request, &services, &viewer).await;
673 }
674
Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009)675 // Workflow logs to download: a run's as a zip, a job's as text (logs.rs).
676 if method == "GET" {
677 let text = url.query_pairs().any(|(name, value)| name == "format" && value == "text");
678 if let Some(wanted) = logs::wanted(&path, text) {
679 return logs::download(&services, &viewer, wanted).await;
680 }
681 }
682
Workspace names and icons, and a component kit for every control683 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'684 ("GET", "") => return reply(&index(&services.addresses)),
Workspace names and icons, and a component kit for every control685 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2686 // One of a run's artifacts downloaded by name (the run's artifacts
687 // are listed by the REST route in rest.rs).
688 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts/") => {
Workspace names and icons, and a component kit for every control689 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2690 if let [owner, repo, "actions", "runs", run, "artifacts", name] = parts.as_slice() {
Merge branch 'worktree-agent-a3abfcce648e87dca'691 // A workflow job's token reaches its own repository only.
692 if viewer
693 .as_ref()
694 .and_then(|user| user.token.as_deref())
695 .is_some_and(|token| !token.reaches(&format!("{owner}/{repo}")))
696 {
697 return fail(FailureCode::NotFound, "No such run.");
698 }
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2699 return blobs::download(env, &services, &viewer, owner, repo, run, name).await;
Workspace names and icons, and a component kit for every control700 }
701 }
702 ("POST", "/device/code") => return device_code(&mut request, &services).await,
703 ("POST", "/device/token") => return device_token(&mut request, &services).await,
704 // Where a pull request lives, for a tool that knows only its fork.
705 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
706 let located: Outcome<Value> = g1t_kit::call(
707 &services.work,
708 "locate_pull",
709 &json!({ "id": &path[7..], "viewer": viewer }),
710 )
711 .await?;
712 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API713 Outcome::Ok(value) => reply(&value),
Workspace names and icons, and a component kit for every control714 Outcome::Fail(refused) => failure(&refused),
715 };
716 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains717 ("POST", path) if path.starts_with("/mergechecks/") => {
718 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
719 return report_mergecheck(&mut request, &services, &pull_id).await;
720 }
Merge branch 'worktree-agent-ac5b181a013e54348'721 // A sandbox making a repository's nightly backup. The job's own
722 // token, in its header, is the credential.
723 (method, path) if path.starts_with("/backups/") => {
724 return backup_job(&mut request, &services, method, path).await;
725 }
Workspace names and icons, and a component kit for every control726 ("POST", path) if path.starts_with("/queue/") => {
727 let entry_id = path.trim_start_matches("/queue/").to_owned();
728 return report_queue(&mut request, &services, &entry_id).await;
729 }
730 // A sandbox running a GitHub Actions job: fetching the job, and
731 // reporting how it goes. The job's own token is the credential.
Merge remote-tracking branch 'origin/claude/peaceful-franklin-7qtkwx'732 // A sandbox downloading an action's archive that g1t keeps
733 // (actions' registry.rs). The job's own token is the credential.
734 ("POST", path) if path.starts_with("/actions/jobs/") && path.ends_with("/archive") => {
735 let job = path.trim_start_matches("/actions/jobs/").trim_end_matches("/archive").to_owned();
736 let body = json_body(&mut request).await;
737 let kept: Outcome<Value> = g1t_kit::call(
738 &services.actions,
739 "job_action_archive",
740 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
741 )
742 .await?;
743 let kept = match kept {
744 Outcome::Ok(kept) => kept,
745 Outcome::Fail(refused) => return failure(&refused),
746 };
747 let bucket = env.bucket("ACTIONS_CACHE")?;
748 let object = kept["object"].as_str().unwrap_or_default();
749 let Some(stored) = bucket.get(object).execute().await? else {
750 return fail(FailureCode::NotFound, "The archive is gone.");
751 };
752 let Some(body) = stored.body() else {
753 return fail(FailureCode::NotFound, "The archive is gone.");
754 };
755 let mut response = Response::from_body(body.response_body()?)?;
756 response.headers_mut().set("content-type", "application/gzip")?;
757 return Ok(response);
758 }
Workspace names and icons, and a component kit for every control759 ("POST", path) if path.starts_with("/actions/jobs/") => {
760 let rest = path.trim_start_matches("/actions/jobs/");
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts761 // `/action`: where to fetch another repository's action from (on
762 // g1t, with a read token for a private one, or GitHub).
763 let (job, method) = match (rest.strip_suffix("/spec"), rest.strip_suffix("/action")) {
764 (Some(job), _) => (job.to_owned(), "job_spec"),
765 (_, Some(job)) => (job.to_owned(), "job_action"),
766 _ => (rest.to_owned(), "job_report"),
Workspace names and icons, and a component kit for every control767 };
768 let body = json_body(&mut request).await;
769 let answered: Outcome<Value> = g1t_kit::call(
770 &services.actions,
771 method,
772 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
773 )
774 .await?;
775 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API776 // A job's spec is the workflow and its contexts as GitHub
777 // has them; only g1t's own keys around them are converted.
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2778 Outcome::Ok(value) => {
779 let mut spec = wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN);
780 with_runtime(&mut spec, &services.addresses.api, oidc::configured(env));
781 Response::from_json(&spec)
782 }
Workspace names and icons, and a component kit for every control783 Outcome::Fail(refused) => failure(&refused),
784 };
785 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains786 // A sandbox reporting its agent run's steps, cost and end. As with
787 // checks, the run's own token, in the body, is the credential.
788 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
789 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
790 let mut body = json_body(&mut request).await;
791 if !body.is_object() {
792 body = json!({});
793 }
794 body["runId"] = json!(run_id);
795 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
796 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API797 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains798 Outcome::Fail(refused) => failure(&refused),
799 };
800 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API801 // What a run's agent learned, as memory candidates; the same token.
802 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
803 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
804 let body = json_body(&mut request).await;
805 let learned = json!({
806 "runId": run_id,
807 "token": body["token"].as_str().unwrap_or_default(),
808 "items": body["items"].as_array().cloned().unwrap_or_default(),
809 });
810 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
811 return match captured {
812 Outcome::Ok(captured) => reply(&captured),
813 Outcome::Fail(refused) => failure(&refused),
814 };
815 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step816 // How sure a run's agent is of its change; the same token.
817 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
818 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
819 let body = json_body(&mut request).await;
820 let said = json!({
821 "runId": run_id,
822 "token": body["token"].as_str().unwrap_or_default(),
823 "confidence": body["confidence"].as_str().unwrap_or_default(),
824 "uncertainAbout": body["uncertain_about"]
825 .as_array()
826 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
827 .unwrap_or_default(),
828 });
829 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
830 return match recorded {
831 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
832 Outcome::Fail(refused) => failure(&refused),
833 };
834 }
Workspace names and icons, and a component kit for every control835 ("POST", path) if path.starts_with("/checks/") => {
836 let run_id = path.trim_start_matches("/checks/").to_owned();
837 return report_checks(&mut request, &services, &run_id).await;
838 }
839 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
840 let run_id = path
841 .trim_start_matches("/runs/")
842 .trim_end_matches("/usage")
843 .to_owned();
844 return report_usage(&mut request, &services, &run_id).await;
845 }
846 ("POST", path) if path.starts_with("/plans/") => {
847 let plan_id = path.trim_start_matches("/plans/").to_owned();
848 return report_plan(&mut request, &services, &plan_id).await;
849 }
850 ("POST", path) if path.starts_with("/reviews/") => {
851 let run_id = path.trim_start_matches("/reviews/").to_owned();
852 return report_review(&mut request, &services, &run_id).await;
853 }
854 _ => {}
855 }
856
857 let query: Vec<(String, String)> = url
858 .query_pairs()
859 .map(|(name, value)| (name.into_owned(), value.into_owned()))
860 .collect();
861 let body = if method == "GET" {
862 Value::Null
863 } else {
864 snake_case_keys(json_body(&mut request).await)
865 };
866 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
867 return fail(FailureCode::NotFound, "No such endpoint.");
868 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API869 match audit::run(route.op, &services, &viewer, &input).await? {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2870 // A download is a redirect to its signed link, as GitHub's is.
The artifacts service is services/artifacts, the Worker g1t-artifacts, bound as ARTIFACTS by the API, the site and the agents; its live rooms move to it with a Durable Object transfer from g1t-docs-service, and its database, bucket, indexes and queue keep their names. The git store's binding and settings are GITSTORE, its ops scripts gitstore-*, and workflow run artifacts keep their compatible API under run_artifacts modules. The deploy tool puts a Worker that has never deployed before the Workers in its stage that bind to it, and the deploy guide gives the cutover runbook.871 Outcome::Ok(value) if route.op == operations::Op::Artifacts(run_artifacts::ArtifactsOp::DownloadArtifact) => {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2872 match value["url"].as_str().and_then(|url| worker::Url::parse(url).ok()) {
873 Some(url) => Response::redirect_with_status(url, 302),
874 None => reply(&value),
875 }
876 }
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts877 // A deleted comment has nothing to say, as GitHub's says nothing.
878 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 API879 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 step880 // A token without the scope a call needs is told which one.
881 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
882 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
883 "error": {
884 "code": refused.code,
885 "message": refused.message,
886 "needed_scope": scope.as_str(),
887 }
888 }))?
889 .with_status(403)),
890 _ => failure(&refused),
891 },
Workspace names and icons, and a component kit for every control892 }
893}
894
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API895/// Request bodies take the same keys as the MCP tools, `snake_case`, as
896/// responses use; the `camelCase` spelling is accepted too.
Workspace names and icons, and a component kit for every control897fn snake_case_keys(body: Value) -> Value {
898 let Value::Object(fields) = body else {
899 return body;
900 };
901 let mut out = serde_json::Map::new();
902 for (key, value) in fields {
903 let mut snake = String::with_capacity(key.len() + 4);
904 for c in key.chars() {
905 if c.is_ascii_uppercase() {
906 snake.push('_');
907 snake.push(c.to_ascii_lowercase());
908 } else {
909 snake.push(c);
910 }
911 }
912 // A key given in both spellings keeps the snake_case one.
913 if snake != key && out.contains_key(&snake) {
914 continue;
915 }
916 out.insert(snake, value);
917 }
918 Value::Object(out)
919}
920
921#[cfg(test)]
922mod tests {
923 use super::snake_case_keys;
924 use serde_json::json;
925
926 #[test]
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)927 fn an_unconfirmed_account_may_only_see_itself_and_confirm_its_address() {
928 assert!(super::pending_may("GET", "/user", false));
929 assert!(super::pending_may("GET", "/user/emails/", false));
930 assert!(super::pending_may("POST", "/user/emails/confirm", false));
931 assert!(!super::pending_may("POST", "/user/emails", false));
932 assert!(!super::pending_may("POST", "/workspaces", false));
933 assert!(!super::pending_may("GET", "/repos/acme/rocket", false));
934 assert!(!super::pending_may("POST", "/user/emails/confirm", true));
935 assert!(!super::pending_may("POST", "/", true));
936 }
937
938 #[test]
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2939 fn a_job_spec_gets_the_toolkits_variables() {
940 // As the actions service sends it, converted as the API does.
941 let sent = json!({ "variables": { "GITHUB_SHA": "abc" }, "runtime": { "token": "h.p.s", "idToken": true } });
942 let mut spec = g1t_kit::wire::snake_case_keeping(sent.clone(), super::JOB_SPEC_AS_GIVEN);
943 super::with_runtime(&mut spec, "https://api.g1t.sh", true);
944 assert!(spec.get("runtime").is_none(), "the runner never sees it");
945 let vars = &spec["variables"];
946 assert_eq!(vars["GITHUB_SHA"], "abc");
947 assert_eq!(vars["ACTIONS_RUNTIME_TOKEN"], "h.p.s");
948 assert_eq!(vars["ACTIONS_CACHE_URL"], "https://api.g1t.sh/actions/toolkit/");
949 assert_eq!(vars["ACTIONS_ID_TOKEN_REQUEST_TOKEN"], "h.p.s");
950 // No OIDC key here: no OIDC variables, whatever the job may do.
951 let mut spec = g1t_kit::wire::snake_case_keeping(sent, super::JOB_SPEC_AS_GIVEN);
952 super::with_runtime(&mut spec, "https://api.g1t.sh", false);
953 assert!(spec["variables"].get("ACTIONS_ID_TOKEN_REQUEST_URL").is_none());
954 assert_eq!(spec["variables"]["ACTIONS_RESULTS_URL"], "https://api.g1t.sh/");
955 }
956
957 #[test]
Workspace names and icons, and a component kit for every control958 fn camel_case_keys_are_accepted() {
959 assert_eq!(
960 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
961 json!({ "count_agent_approvals": false, "title": "x" })
962 );
963 }
964
965 #[test]
966 fn snake_case_wins_when_both_are_given() {
967 assert_eq!(
968 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
969 json!({ "keep_issue_open": true })
970 );
971 }
972}
973
974// The API is called from browsers too: the reference's explorer, and apps
975// built on g1t. It carries no cookies, so any origin may call it.
976#[event(fetch)]
977async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
978 let mut response = respond(request, &env).await?;
979 let headers = response.headers_mut();
980 headers.set("access-control-allow-origin", "*")?;
981 headers.set(
982 "access-control-allow-headers",
983 "authorization, content-type",
984 )?;
985 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
Merge branch 'worktree-agent-a8752162fea25f63f' into spend-guardrails986 headers.set("access-control-expose-headers", "www-authenticate, retry-after")?;
Workspace names and icons, and a component kit for every control987 Ok(response)
988}

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