Skip to content
937 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;
API and MCP server in Rust; a public index at the API root17mod mcp;
API: notifications over REST and MCP, with notifications scopes18mod notifications;
API and MCP server in Rust; a public index at the API root19mod oauth;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R220mod oidc;
Merge packages: roles, Actions access, source label, soft delete, API21mod packages;
API and MCP server in Rust; a public index at the API root22mod openapi;
API: pinned projects over REST and MCP23mod pins;
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb9724mod projects;
Merge branch 'worktree-agent-a3abfcce648e87dca'25mod protection;
API and MCP server in Rust; a public index at the API root26mod operations;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains27mod renamed;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API28#[cfg(test)]
29mod responses;
API and MCP server in Rust; a public index at the API root30mod rest;
Merge rulesets: branch and tag rules, agent-first, enforced on push and merge31mod rules;
Fast pages, required checks on the branch, self-hosted runners, honest incidents32mod runners;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar33mod security;
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step34mod tools;
API and MCP for a workspace's personal access token rules, members' tokens and approvals35mod token_policy;
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R236mod toolkit;
API and MCP server in Rust; a public index at the API root37
Merge branch 'model-routing'38use g1t_contracts::billing::{FinishRunArgs, RunTokens};
API and MCP server in Rust; a public index at the API root39use g1t_contracts::identity::{
40 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
41};
Agents as a team: lifecycle, merge queue, billing and a new shell42use g1t_contracts::work::{
Agents and memory, checks and conflicts, profiles, slug renames, custom domains43 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
44 ReportQueueArgs, ReportReviewArgs,
Agents as a team: lifecycle, merge queue, billing and a new shell45};
46use g1t_contracts::identity::AgentScope;
Email confirmation gate: a code and a link, nothing else until confirmed47use 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 API48use g1t_kit::wire;
API and MCP server in Rust; a public index at the API root49use serde_json::{Value, json};
50use worker::{Context, Env, Method, Request, Response, Result, event};
51
52use operations::Services;
53
54fn method_name(method: Method) -> &'static str {
55 match method {
56 Method::Get => "GET",
57 Method::Post => "POST",
58 Method::Patch => "PATCH",
59 Method::Put => "PUT",
60 Method::Delete => "DELETE",
61 Method::Options => "OPTIONS",
62 Method::Head => "HEAD",
63 _ => "OTHER",
64 }
65}
66
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API67/// A JSON response. Every body the API sends has its keys in `snake_case`;
68/// the contracts it passes through are `camelCase`, so they are converted
69/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
70/// the MCP protocol's own envelope keep the spelling their standards use.
71pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
72 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
73}
74
75/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
76/// workflow file, GitHub's contexts and event, and where to check out, all
77/// passed through as they are.
78const JOB_SPEC_AS_GIVEN: &[&str] = &[
Merge branch 'worktree-agent-a3abfcce648e87dca'79 "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 API80];
81
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R282/// Puts the toolkit's variables in a job's spec: its runtime token, where
83/// the toolkit's services are, and where to ask for an OIDC token when the
84/// job may have one and this installation issues them. The `runtime` the
85/// actions service sent goes no further.
86fn with_runtime(spec: &mut Value, api: &str, oidc: bool) {
87 let Some(runtime) = spec.as_object_mut().and_then(|s| s.remove("runtime")) else { return };
88 let Some(token) = runtime["token"].as_str().filter(|t| !t.is_empty()) else { return };
89 let id_token = oidc && runtime["id_token"].as_bool() == Some(true);
90 let vars = toolkit::runtime_variables(api, token, id_token);
91 if let Some(variables) = spec.get_mut("variables").and_then(Value::as_object_mut) {
92 variables.extend(vars);
93 }
94}
95
Email confirmation gate: a code and a link, nothing else until confirmed96/// What a person whose account has not confirmed its email address may
97/// call: who they are, their addresses, and confirming one with the code
98/// from the email. Nothing over MCP.
99fn pending_may(method: &str, path: &str, on_mcp: bool) -> bool {
100 !on_mcp
101 && matches!(
102 (method, path.trim_end_matches('/')),
103 ("GET", "/user") | ("GET", "/user/emails") | ("POST", "/user/emails/confirm")
104 )
105}
106
API and MCP server in Rust; a public index at the API root107/// An error in the shape every endpoint uses.
108fn failure(failure: &Failure) -> Result<Response> {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API109 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
API and MCP server in Rust; a public index at the API root110}
111
112fn fail(code: FailureCode, message: &str) -> Result<Response> {
113 failure(&Failure {
114 code,
115 message: message.to_owned(),
116 })
117}
118
119/// A request body as JSON. An empty or malformed body is no input.
120async fn json_body(request: &mut Request) -> Value {
121 request.json().await.unwrap_or(Value::Null)
122}
123
124/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
125/// an anonymous viewer; a wrong one is refused, so that a typo does not
126/// silently look signed out.
127async fn authenticate(
128 request: &Request,
129 services: &Services,
130) -> Result<std::result::Result<Viewer, Response>> {
131 let header = request.headers().get("authorization")?.unwrap_or_default();
132 let token = match header.split_once(' ') {
133 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
134 token.trim()
135 }
136 _ => return Ok(Ok(None)),
137 };
138 let viewer: Viewer = g1t_kit::call(
139 &services.identity,
140 "user_for_access_token",
141 &TokenArgs {
142 token: token.to_owned(),
143 },
144 )
145 .await?;
146 if viewer.is_some() {
147 return Ok(Ok(viewer));
148 }
149 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
150 // Tells an MCP client where to sign in again.
151 response.headers_mut().set(
152 "www-authenticate",
Merge branch 'worktree-agent-aaf03bdceac799c89'153 &format!("{}, error=\"invalid_token\"", services.addresses.mcp_challenge()),
API and MCP server in Rust; a public index at the API root154 )?;
155 Ok(Err(response))
156}
157
158/// Where everything is, for someone or something exploring the API.
Merge branch 'worktree-agent-aaf03bdceac799c89'159fn index(addresses: &addresses::Addresses) -> Value {
160 let api = &addresses.api;
161 let repo = format!("{api}/repos/{{owner}}/{{name}}");
API and MCP server in Rust; a public index at the API root162 json!({
Merge branch 'worktree-agent-ab2e39e11a6493412'163 "documentation_url": "https://docs.g1t.sh/reference/api/",
Merge branch 'worktree-agent-aaf03bdceac799c89'164 "openapi_url": format!("{api}/openapi.json"),
165 "mcp_url": addresses.mcp,
166 "current_user_url": format!("{api}/user"),
167 "workspaces_url": format!("{api}/workspaces"),
168 "repositories_url": format!("{api}/repos{{?q}}"),
169 "search_url": format!("{api}/search{{?q,type,page,per_page}}"),
API and MCP server in Rust; a public index at the API root170 "repository_url": repo,
171 "repository_events_url": format!("{repo}/events{{?before}}"),
172 "labels_url": format!("{repo}/labels"),
173 "issues_url": format!("{repo}/issues{{?state,label}}"),
174 "issue_url": format!("{repo}/issues/{{number}}"),
175 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
176 "pulls_url": format!("{repo}/pulls{{?state}}"),
177 "pull_url": format!("{repo}/pulls/{{number}}"),
178 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
Acceptance checks in sandboxes, line comments and review verdicts179 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
API and MCP server in Rust; a public index at the API root180 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
Merge branch 'worktree-agent-aaf03bdceac799c89'181 "device_code_url": format!("{api}/device/code"),
182 "device_token_url": format!("{api}/device/token"),
183 "oauth_metadata_url": format!("{api}/.well-known/oauth-authorization-server"),
184 "git_url": format!("{}/{{owner}}/{{name}}.git", addresses.site),
185 "integrations_url": format!("{api}/workspaces/{{workspace}}/integrations"),
Integrations: your own model provider, alerts that open issues, tickets agents read186 "context_url": format!("{repo}/context{{?reference}}"),
187 "import_issue_url": format!("{repo}/issues/import"),
Merge branch 'worktree-agent-aaf03bdceac799c89'188 "hooks_url": format!("{api}/hooks/{{integration}}"),
API and MCP server in Rust; a public index at the API root189 })
190}
191
192// Signing in from a tool. Accounts are created, and passwords typed, only
193// in a browser; a tool gets its token by having a person approve a code.
194
Integrations: your own model provider, alerts that open issues, tickets agents read195/// Passes a request from an outside system to its connection, as it came:
196/// its signature covers the exact bytes of the body.
197async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
198 let headers: std::collections::HashMap<String, String> = request
199 .headers()
200 .entries()
201 .map(|(name, value)| (name.to_lowercase(), value))
202 .collect();
203 let body = request.text().await.unwrap_or_default();
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look204 // A push to GitHub with many commits makes a large payload.
205 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
206 if body.len() > limit {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API207 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
Integrations: your own model provider, alerts that open issues, tickets agents read208 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look209 // g1t's GitHub App has one webhook for every installation; it is
210 // checked against the app's own secret.
211 let (method, args) = if id == "github" {
212 ("github_receive", json!({ "headers": headers, "body": body }))
213 } else {
214 ("receive", json!({ "id": id, "headers": headers, "body": body }))
215 };
216 let received: g1t_contracts::integrations::Received =
217 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 API218 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
Integrations: your own model provider, alerts that open issues, tickets agents read219}
220
Stripe webhooks, enterprise invoices, and sudo for both221async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
222 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
223 let payload = request.text().await.unwrap_or_default();
224 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 API225 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
Stripe webhooks, enterprise invoices, and sudo for both226 }
227 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
228 &env.service("BILLING")?,
229 "stripe_webhook",
230 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
231 )
232 .await?;
233 // A refusal is a 400, so Stripe shows it as failed; anything handled,
234 // or already handled, is a 200, so Stripe stops sending it.
235 Ok(match handled {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API236 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
Stripe webhooks, enterprise invoices, and sudo for both237 g1t_contracts::Outcome::Fail(failure) => {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API238 reply(&json!({ "message": failure.message }))?.with_status(400)
Stripe webhooks, enterprise invoices, and sudo for both239 }
240 })
241}
242
API and MCP server in Rust; a public index at the API root243async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
244 let body = json_body(request).await;
245 let started: DeviceStart = g1t_kit::call(
246 &services.identity,
247 "device_start",
248 &DeviceStartArgs {
249 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
250 },
251 )
252 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API253 reply(&json!({
API and MCP server in Rust; a public index at the API root254 "device_code": started.device_code,
255 "user_code": started.user_code,
Merge branch 'worktree-agent-aaf03bdceac799c89'256 "verification_uri": format!("{}/device", services.addresses.site),
257 "verification_uri_complete": format!("{}/device?code={}", services.addresses.site, started.user_code),
API and MCP server in Rust; a public index at the API root258 "expires_in": started.expires_in,
259 "interval": started.interval,
260 }))
261}
262
263async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
264 let body = json_body(request).await;
265 let claim: DeviceClaim = g1t_kit::call(
266 &services.identity,
267 "device_claim",
268 &DeviceClaimArgs {
269 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
270 },
271 )
272 .await?;
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API273 reply(&match claim {
API and MCP server in Rust; a public index at the API root274 DeviceClaim::Approved { token, user } => json!({
275 "status": "approved",
276 "token": token,
277 "username": user.username,
278 "verified": user.verified,
279 }),
280 DeviceClaim::Pending => json!({ "status": "pending" }),
281 DeviceClaim::Denied => json!({ "status": "denied" }),
282 DeviceClaim::Expired => json!({ "status": "expired" }),
283 })
284}
285
Fast pages, required checks on the branch, self-hosted runners, honest incidents286/// A sandbox reporting on a run of an issue's commands, from before a pull
287/// request's checks were the workflows run on it.
Acceptance checks in sandboxes, line comments and review verdicts288/// The run's own token, in the body, is the credential: it was given to
289/// that sandbox and to nothing else.
290async fn report_checks(
291 request: &mut Request,
292 services: &Services,
293 run_id: &str,
294) -> Result<Response> {
295 let body = json_body(request).await;
296 let reported: Outcome<CheckRun> = g1t_kit::call(
297 &services.work,
298 "report_checks",
299 &ReportChecksArgs {
300 run_id: run_id.to_owned(),
301 token: body["token"].as_str().unwrap_or_default().to_owned(),
302 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
303 error: body["error"].as_str().map(str::to_owned),
304 skip: false,
305 },
306 )
307 .await?;
308 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API309 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
Acceptance checks in sandboxes, line comments and review verdicts310 Outcome::Fail(refused) => failure(&refused),
311 }
312}
313
Agents as a team: lifecycle, merge queue, billing and a new shell314/// A sandbox reporting one tested state of a merge queue. As with checks,
315/// the entry's own token is the credential.
316async fn report_queue(
317 request: &mut Request,
318 services: &Services,
319 entry_id: &str,
320) -> Result<Response> {
321 let body = json_body(request).await;
322 let reported: Outcome<QueueState> = g1t_kit::call(
323 &services.work,
324 "report_queue",
325 &ReportQueueArgs {
326 entry_id: entry_id.to_owned(),
327 token: body["token"].as_str().unwrap_or_default().to_owned(),
328 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
329 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
330 error: body["error"].as_str().map(str::to_owned),
331 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains332 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
Agents as a team: lifecycle, merge queue, billing and a new shell333 },
334 )
335 .await?;
336 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API337 Outcome::Ok(state) => reply(&json!({ "state": state })),
Agents as a team: lifecycle, merge queue, billing and a new shell338 Outcome::Fail(refused) => failure(&refused),
339 }
340}
341
Agents and memory, checks and conflicts, profiles, slug renames, custom domains342/// A sandbox reporting whether a pull request merges cleanly. As with
343/// checks, the probe's own token is the credential.
344async fn report_mergecheck(
345 request: &mut Request,
346 services: &Services,
347 pull_id: &str,
348) -> Result<Response> {
349 let body = json_body(request).await;
350 let reported: Outcome<Mergeable> = g1t_kit::call(
351 &services.work,
352 "report_mergecheck",
353 &ReportMergecheckArgs {
354 pull_id: pull_id.to_owned(),
355 token: body["token"].as_str().unwrap_or_default().to_owned(),
356 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
357 error: body["error"].as_str().map(str::to_owned),
358 },
359 )
360 .await?;
361 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API362 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains363 Outcome::Fail(refused) => failure(&refused),
364 }
365}
366
Merge branch 'worktree-agent-ac5b181a013e54348'367/// A backup's sandbox, passed on to the repos service, which holds the
368/// job (services/repos/src/backups.rs; the flow is in
369/// `g1t_contracts::backups`):
370///
371/// - `POST /backups/{job}/spec`: what to cut, and a read-only git credential
372/// - `PUT /backups/{job}/parts/{n}`: one part of the bundle, as bytes
373/// - `POST /backups/{job}/complete` with `{ refs, size, sha256, parts, fetched_bytes }`
374/// - `POST /backups/{job}/fail` with `{ error, fetched_bytes }`
375///
376/// Bodies are passed through as they are: snake_case already, and a
377/// bundle's refs are keyed by ref names, which must not be converted.
378async fn backup_job(request: &mut Request, services: &Services, method: &str, path: &str) -> Result<Response> {
379 use g1t_contracts::backups::TOKEN_HEADER;
380 let token = request.headers().get(TOKEN_HEADER)?.unwrap_or_default();
381 let rest = path.trim_start_matches("/backups/");
382 let (job, action) = rest.split_once('/').unwrap_or((rest, ""));
383 if job.is_empty() || token.is_empty() {
384 return fail(FailureCode::Unauthenticated, "A backup job's token is required.");
385 }
386 if method == "PUT" && action.starts_with("parts/") {
387 let bytes = request.bytes().await?;
388 if bytes.len() as u64 > g1t_contracts::backups::PART_BYTES {
389 return fail(FailureCode::Invalid, "A part holds 32 MiB at most.");
390 }
391 let headers = worker::Headers::new();
392 headers.set(TOKEN_HEADER, &token)?;
393 let mut init = worker::RequestInit::new();
394 init.with_method(Method::Put)
395 .with_headers(headers)
396 .with_body(Some(worker::js_sys::Uint8Array::from(bytes.as_slice()).into()));
397 let forwarded = Request::new_with_init(&format!("https://repos/backups/{job}/{action}"), &init)?;
398 let mut answered = services.repos.fetch_request(forwarded).await?;
399 return outcome_as_given(answered.json().await?);
400 }
401 let rpc = match (method, action) {
402 ("POST", "spec") => "backup_spec",
403 ("POST", "complete") => "backup_complete",
404 ("POST", "fail") => "backup_fail",
405 _ => return fail(FailureCode::NotFound, "No such endpoint."),
406 };
407 let mut body = json_body(request).await;
408 if !body.is_object() {
409 body = json!({});
410 }
411 body["job_id"] = json!(job);
412 body["token"] = json!(token);
413 let answered: Value = g1t_kit::call(&services.repos, rpc, &body).await?;
414 outcome_as_given(answered)
415}
416
417/// An `Outcome` from a service whose keys are already the API's: the value,
418/// or the failure in the shape every endpoint uses.
419fn outcome_as_given(answered: Value) -> Result<Response> {
420 match serde_json::from_value::<Outcome<Value>>(answered)? {
421 Outcome::Ok(value) => Response::from_json(&value),
422 Outcome::Fail(refused) => failure(&refused),
423 }
424}
425
Agents as a team: lifecycle, merge queue, billing and a new shell426/// A sandbox reporting the review its agent wrote. As with checks, the
427/// run's own token is the credential.
428async fn report_review(
429 request: &mut Request,
430 services: &Services,
431 run_id: &str,
432) -> Result<Response> {
433 let body = json_body(request).await;
434 let reported: Outcome<bool> = g1t_kit::call(
435 &services.work,
436 "report_review",
437 &ReportReviewArgs {
438 run_id: run_id.to_owned(),
439 token: body["token"].as_str().unwrap_or_default().to_owned(),
440 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
441 body: body["body"].as_str().unwrap_or_default().to_owned(),
442 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
443 model: body["model"].as_str().map(str::to_owned),
444 error: body["error"].as_str().map(str::to_owned),
445 },
446 )
447 .await?;
448 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API449 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell450 Outcome::Fail(refused) => failure(&refused),
451 }
452}
453
454/// A sandbox reporting the plan its agent wrote. As with checks, the
455/// plan's own token is the credential.
456async fn report_plan(
457 request: &mut Request,
458 services: &Services,
459 plan_id: &str,
460) -> Result<Response> {
461 let body = json_body(request).await;
462 let reported: Outcome<bool> = g1t_kit::call(
463 &services.work,
464 "report_plan",
465 &ReportPlanArgs {
466 plan_id: plan_id.to_owned(),
467 token: body["token"].as_str().unwrap_or_default().to_owned(),
468 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
469 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
470 error: body["error"].as_str().map(str::to_owned),
471 },
472 )
473 .await?;
474 match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API475 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell476 Outcome::Fail(refused) => failure(&refused),
477 }
478}
479
480/// A sandbox reporting what its agent's run cost, so that the workspace
481/// it worked for is charged. As with checks, the run's own token is the
482/// credential.
483async fn report_usage(
484 request: &mut Request,
485 services: &Services,
486 run_id: &str,
487) -> Result<Response> {
488 let body = json_body(request).await;
489 let charged: Outcome<bool> = g1t_kit::call(
490 &services.billing,
491 "finish_run",
492 &FinishRunArgs {
493 run_id: run_id.to_owned(),
494 token: body["token"].as_str().unwrap_or_default().to_owned(),
495 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
496 turns: body["turns"].as_u64().unwrap_or_default() as u32,
Merge branch 'model-routing'497 // What the harness counted; the agent rate is charged on no
498 // fewer, on a workspace's own model key too.
499 tokens: body.get("tokens").filter(|t| t.is_object()).map(|t| RunTokens {
500 input: t["input"].as_u64().unwrap_or_default(),
501 output: t["output"].as_u64().unwrap_or_default(),
502 cache_read: t["cache_read"].as_u64().unwrap_or_default(),
503 cache_write: t["cache_write"].as_u64().unwrap_or_default(),
504 }),
Agents as a team: lifecycle, merge queue, billing and a new shell505 },
506 )
507 .await?;
508 match charged {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API509 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
Agents as a team: lifecycle, merge queue, billing and a new shell510 Outcome::Fail(refused) => failure(&refused),
511 }
512}
513
API and MCP server in Rust; a public index at the API root514async fn respond(mut request: Request, env: &Env) -> Result<Response> {
515 let method = method_name(request.method());
516 if method == "OPTIONS" {
517 return Ok(Response::empty()?.with_status(204));
518 }
519 let url = request.url()?;
Agents as a team: lifecycle, merge queue, billing and a new shell520 // Paths carry no version. An earlier form began with `/v1`, which is
521 // still accepted so that nothing already written against it breaks.
522 let path = match url.path().strip_prefix("/v1") {
523 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
524 _ => url.path().to_owned(),
525 };
526 let mut services = Services::new(env)?;
Merge branch 'worktree-agent-aaf03bdceac799c89'527 // MCP is a host of its own hosted, and may be a path on this one
528 // self-hosted (addresses.rs).
529 let on_mcp = services.addresses.mcp_path(&url).is_some();
API and MCP server in Rust; a public index at the API root530
Stripe webhooks, enterprise invoices, and sudo for both531 // Stripe reporting to billing. Signed with the secret of the endpoint
532 // billing registered; the body goes through exactly as received, since
533 // the signature covers its bytes.
534 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
535 return receive_stripe(&mut request, env).await;
536 }
537
Integrations: your own model provider, alerts that open issues, tickets agents read538 // Outside systems reporting to a connection. They sign what they send
539 // with the connection's own secret, which is not a g1t token, so this
540 // comes before anything that would read one.
Polish: phones, copy boxes, the plan page, the landing page, a real glide541 if method == "POST" && !on_mcp
542 && 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 read543 return receive_hook(&mut request, &services, id).await;
544 }
545
Deployments: a preview for every pull request, production on g1t.page546 // A sandbox building a deployment, reporting with its build's token,
547 // which is not a g1t token. The body goes through as it is: it can
548 // carry a Worker's bundled code.
549 if method == "POST" && !on_mcp
550 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
551 {
552 let target = format!("https://deployments/jobs/{rest}");
553 let body = request.bytes().await?;
554 let headers = worker::Headers::new();
555 headers.set("content-type", "application/json")?;
556 let mut init = worker::RequestInit::new();
557 init.with_method(Method::Post)
558 .with_headers(headers)
559 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
Deployments work end to end: fixes from the first live run560 let mut answer = env
Deployments: a preview for every pull request, production on g1t.page561 .service("DEPLOYMENTS")?
562 .fetch_request(Request::new_with_init(&target, &init)?)
Deployments work end to end: fixes from the first live run563 .await?;
564 // A fresh response: a fetched one's headers cannot be changed, and
565 // every response gets the API's own on the way out.
566 let status = answer.status_code();
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API567 let bytes = answer.bytes().await?;
568 let bytes = match serde_json::from_slice::<Value>(&bytes) {
569 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
570 Err(_) => bytes,
571 };
572 return Ok(Response::from_bytes(bytes)?
Deployments work end to end: fixes from the first live run573 .with_status(status)
574 .with_headers({
575 let headers = worker::Headers::new();
576 headers.set("content-type", "application/json")?;
577 headers
578 }));
Deployments: a preview for every pull request, production on g1t.page579 }
580
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2581 // The services GitHub's toolkit calls from inside a job, with its
582 // runtime token, and the links they hand out (toolkit.rs).
583 if !on_mcp && method == "POST"
584 && let Some(rest) = path.strip_prefix("/twirp/")
585 {
586 let (service, rpc) = rest.split_once('/').unwrap_or((rest, ""));
587 let (service, rpc) = (service.to_owned(), rpc.to_owned());
588 return toolkit::twirp(request, env, &services, &service, &rpc).await;
589 }
590 if !on_mcp && let Some(rest) = path.strip_prefix("/actions/toolkit/_apis/artifactcache/") {
591 let rest = rest.to_owned();
592 return toolkit::cache_v1(request, env, &services, method, &rest).await;
593 }
594 if !on_mcp && let Some(token) = path.strip_prefix("/actions/toolkit/blobs/") {
595 let token = token.to_owned();
596 return toolkit::blob(request, env, &services, method, &token).await;
597 }
598 // g1t as an OIDC issuer for workflow jobs (oidc.rs).
599 if !on_mcp && method == "GET" && path.starts_with("/actions/oidc/") {
600 return oidc::handle(&request, env, &services, &path).await;
601 }
602
A repository has its own sidebar, as settings do603 // A sandbox's artifacts and cache, with its job's token, which is not a
604 // g1t token either.
605 if !on_mcp
606 && let Some(rest) = path.strip_prefix("/actions/jobs/")
Fast pages, required checks on the branch, self-hosted runners, honest incidents607 && (rest.contains("/artifacts") || rest.ends_with("/cache") || rest.contains("/cache/uploads"))
A repository has its own sidebar, as settings do608 {
609 let rest = rest.to_owned();
610 return blobs::for_job(request, env, &services, method, &rest).await;
611 }
612
Fast pages, required checks on the branch, self-hosted runners, honest incidents613 // A self-hosted runner, with a registration token or its own
614 // credential, neither of which is a g1t access token.
615 if method == "POST"
616 && !on_mcp
617 && path.starts_with("/runners/")
618 && let Some(response) = runners::handle(&mut request, &services, &path).await?
619 {
620 return Ok(response);
621 }
622
API and MCP server in Rust; a public index at the API root623 let viewer = match authenticate(&request, &services).await? {
624 Ok(viewer) => viewer,
625 Err(refused) => return Ok(refused),
626 };
Email confirmation gate: a code and a link, nothing else until confirmed627 // A person who has not confirmed their email address: who they are,
628 // their addresses, and confirming one, nothing else (REST or MCP).
629 if viewer.as_ref().is_some_and(User::awaits_confirmation) && !pending_may(method, &path, on_mcp) {
630 return fail(
631 FailureCode::Forbidden,
632 &g1t_contracts::accounts::confirm_email_first(&services.addresses.site),
633 );
634 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API635 services.audit = audit::AuditContext::of(&request, on_mcp);
636 // An agent's token: what it may do comes with it, on the composite
637 // identity identity resolved it to.
638 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
639 services.scope = Some(acting.scope.clone());
640 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
Agents as a team: lifecycle, merge queue, billing and a new shell641 let header = request.headers().get("authorization")?.unwrap_or_default();
642 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
643 let scope: Option<AgentScope> = g1t_kit::call(
644 &services.identity,
645 "agent_scope",
646 &TokenArgs {
647 token: token.to_owned(),
648 },
649 )
650 .await?;
651 // A scope is what lets an agent's token do anything at all.
652 let Some(scope) = scope else {
653 return fail(FailureCode::Unauthenticated, "Invalid access token.");
654 };
655 services.scope = Some(scope);
656 }
API and MCP server in Rust; a public index at the API root657 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
658 return Ok(response);
659 }
660 if on_mcp {
661 return mcp::handle(request, &services, &viewer).await;
662 }
663
664 match (method, path.trim_end_matches('/')) {
Merge branch 'worktree-agent-aaf03bdceac799c89'665 ("GET", "") => return reply(&index(&services.addresses)),
API and MCP server in Rust; a public index at the API root666 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2667 // One of a run's artifacts downloaded by name (the run's artifacts
668 // are listed by the REST route in rest.rs).
669 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts/") => {
A repository has its own sidebar, as settings do670 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2671 if let [owner, repo, "actions", "runs", run, "artifacts", name] = parts.as_slice() {
Merge branch 'worktree-agent-a3abfcce648e87dca'672 // A workflow job's token reaches its own repository only.
673 if viewer
674 .as_ref()
675 .and_then(|user| user.token.as_deref())
676 .is_some_and(|token| !token.reaches(&format!("{owner}/{repo}")))
677 {
678 return fail(FailureCode::NotFound, "No such run.");
679 }
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2680 return blobs::download(env, &services, &viewer, owner, repo, run, name).await;
A repository has its own sidebar, as settings do681 }
682 }
Agents as a team: lifecycle, merge queue, billing and a new shell683 ("POST", "/device/code") => return device_code(&mut request, &services).await,
684 ("POST", "/device/token") => return device_token(&mut request, &services).await,
Record your own agent's sessions automatically685 // Where a pull request lives, for a tool that knows only its fork.
686 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
687 let located: Outcome<Value> = g1t_kit::call(
688 &services.work,
689 "locate_pull",
690 &json!({ "id": &path[7..], "viewer": viewer }),
691 )
692 .await?;
693 return match located {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API694 Outcome::Ok(value) => reply(&value),
Record your own agent's sessions automatically695 Outcome::Fail(refused) => failure(&refused),
696 };
697 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains698 ("POST", path) if path.starts_with("/mergechecks/") => {
699 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
700 return report_mergecheck(&mut request, &services, &pull_id).await;
701 }
Merge branch 'worktree-agent-ac5b181a013e54348'702 // A sandbox making a repository's nightly backup. The job's own
703 // token, in its header, is the credential.
704 (method, path) if path.starts_with("/backups/") => {
705 return backup_job(&mut request, &services, method, path).await;
706 }
Agents as a team: lifecycle, merge queue, billing and a new shell707 ("POST", path) if path.starts_with("/queue/") => {
708 let entry_id = path.trim_start_matches("/queue/").to_owned();
709 return report_queue(&mut request, &services, &entry_id).await;
710 }
GitHub Actions on g1t, part two: running workflows711 // A sandbox running a GitHub Actions job: fetching the job, and
712 // reporting how it goes. The job's own token is the credential.
713 ("POST", path) if path.starts_with("/actions/jobs/") => {
714 let rest = path.trim_start_matches("/actions/jobs/");
715 let (job, method) = match rest.strip_suffix("/spec") {
716 Some(job) => (job.to_owned(), "job_spec"),
717 None => (rest.to_owned(), "job_report"),
718 };
719 let body = json_body(&mut request).await;
720 let answered: Outcome<Value> = g1t_kit::call(
721 &services.actions,
722 method,
723 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
724 )
725 .await?;
726 return match answered {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API727 // A job's spec is the workflow and its contexts as GitHub
728 // has them; only g1t's own keys around them are converted.
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2729 Outcome::Ok(value) => {
730 let mut spec = wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN);
731 with_runtime(&mut spec, &services.addresses.api, oidc::configured(env));
732 Response::from_json(&spec)
733 }
GitHub Actions on g1t, part two: running workflows734 Outcome::Fail(refused) => failure(&refused),
735 };
736 }
Agents and memory, checks and conflicts, profiles, slug renames, custom domains737 // A sandbox reporting its agent run's steps, cost and end. As with
738 // checks, the run's own token, in the body, is the credential.
739 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
740 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
741 let mut body = json_body(&mut request).await;
742 if !body.is_object() {
743 body = json!({});
744 }
745 body["runId"] = json!(run_id);
746 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
747 return match reported {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API748 Outcome::Ok(status) => reply(&json!({ "status": status })),
Agents and memory, checks and conflicts, profiles, slug renames, custom domains749 Outcome::Fail(refused) => failure(&refused),
750 };
751 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API752 // What a run's agent learned, as memory candidates; the same token.
753 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
754 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
755 let body = json_body(&mut request).await;
756 let learned = json!({
757 "runId": run_id,
758 "token": body["token"].as_str().unwrap_or_default(),
759 "items": body["items"].as_array().cloned().unwrap_or_default(),
760 });
761 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
762 return match captured {
763 Outcome::Ok(captured) => reply(&captured),
764 Outcome::Fail(refused) => failure(&refused),
765 };
766 }
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step767 // How sure a run's agent is of its change; the same token.
768 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/confidence") => {
769 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/confidence");
770 let body = json_body(&mut request).await;
771 let said = json!({
772 "runId": run_id,
773 "token": body["token"].as_str().unwrap_or_default(),
774 "confidence": body["confidence"].as_str().unwrap_or_default(),
775 "uncertainAbout": body["uncertain_about"]
776 .as_array()
777 .map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
778 .unwrap_or_default(),
779 });
780 let recorded: Outcome<Value> = g1t_kit::call(&services.work, "report_confidence", &said).await?;
781 return match recorded {
782 Outcome::Ok(recorded) => reply(&json!({ "recorded": recorded })),
783 Outcome::Fail(refused) => failure(&refused),
784 };
785 }
Agents as a team: lifecycle, merge queue, billing and a new shell786 ("POST", path) if path.starts_with("/checks/") => {
787 let run_id = path.trim_start_matches("/checks/").to_owned();
Acceptance checks in sandboxes, line comments and review verdicts788 return report_checks(&mut request, &services, &run_id).await;
789 }
Agents as a team: lifecycle, merge queue, billing and a new shell790 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
791 let run_id = path
792 .trim_start_matches("/runs/")
793 .trim_end_matches("/usage")
794 .to_owned();
795 return report_usage(&mut request, &services, &run_id).await;
796 }
797 ("POST", path) if path.starts_with("/plans/") => {
798 let plan_id = path.trim_start_matches("/plans/").to_owned();
799 return report_plan(&mut request, &services, &plan_id).await;
800 }
801 ("POST", path) if path.starts_with("/reviews/") => {
802 let run_id = path.trim_start_matches("/reviews/").to_owned();
803 return report_review(&mut request, &services, &run_id).await;
804 }
API and MCP server in Rust; a public index at the API root805 _ => {}
806 }
807
808 let query: Vec<(String, String)> = url
809 .query_pairs()
810 .map(|(name, value)| (name.into_owned(), value.into_owned()))
811 .collect();
812 let body = if method == "GET" {
813 Value::Null
814 } else {
Agents as a team: lifecycle, merge queue, billing and a new shell815 snake_case_keys(json_body(&mut request).await)
API and MCP server in Rust; a public index at the API root816 };
817 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
818 return fail(FailureCode::NotFound, "No such endpoint.");
819 };
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API820 match audit::run(route.op, &services, &viewer, &input).await? {
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2821 // A download is a redirect to its signed link, as GitHub's is.
822 Outcome::Ok(value) if route.op == operations::Op::Artifacts(artifacts::ArtifactsOp::DownloadArtifact) => {
823 match value["url"].as_str().and_then(|url| worker::Url::parse(url).ok()) {
824 Some(url) => Response::redirect_with_status(url, 302),
825 None => reply(&value),
826 }
827 }
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API828 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 step829 // A token without the scope a call needs is told which one.
830 Outcome::Fail(refused) => match (refused.code, audit::missing_scope(route.op, &viewer, &input)) {
831 (FailureCode::Forbidden, Some(scope)) => Ok(reply(&json!({
832 "error": {
833 "code": refused.code,
834 "message": refused.message,
835 "needed_scope": scope.as_str(),
836 }
837 }))?
838 .with_status(403)),
839 _ => failure(&refused),
840 },
API and MCP server in Rust; a public index at the API root841 }
842}
843
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API844/// Request bodies take the same keys as the MCP tools, `snake_case`, as
845/// responses use; the `camelCase` spelling is accepted too.
Agents as a team: lifecycle, merge queue, billing and a new shell846fn snake_case_keys(body: Value) -> Value {
847 let Value::Object(fields) = body else {
848 return body;
849 };
850 let mut out = serde_json::Map::new();
851 for (key, value) in fields {
852 let mut snake = String::with_capacity(key.len() + 4);
853 for c in key.chars() {
854 if c.is_ascii_uppercase() {
855 snake.push('_');
856 snake.push(c.to_ascii_lowercase());
857 } else {
858 snake.push(c);
859 }
860 }
861 // A key given in both spellings keeps the snake_case one.
862 if snake != key && out.contains_key(&snake) {
863 continue;
864 }
865 out.insert(snake, value);
866 }
867 Value::Object(out)
868}
869
870#[cfg(test)]
871mod tests {
872 use super::snake_case_keys;
873 use serde_json::json;
874
875 #[test]
Email confirmation gate: a code and a link, nothing else until confirmed876 fn an_unconfirmed_account_may_only_see_itself_and_confirm_its_address() {
877 assert!(super::pending_may("GET", "/user", false));
878 assert!(super::pending_may("GET", "/user/emails/", false));
879 assert!(super::pending_may("POST", "/user/emails/confirm", false));
880 assert!(!super::pending_may("POST", "/user/emails", false));
881 assert!(!super::pending_may("POST", "/workspaces", false));
882 assert!(!super::pending_may("GET", "/repos/acme/rocket", false));
883 assert!(!super::pending_may("POST", "/user/emails/confirm", true));
884 assert!(!super::pending_may("POST", "/", true));
885 }
886
887 #[test]
Actions: OIDC tokens, the toolkit's cache and artifact services, and artifacts in R2888 fn a_job_spec_gets_the_toolkits_variables() {
889 // As the actions service sends it, converted as the API does.
890 let sent = json!({ "variables": { "GITHUB_SHA": "abc" }, "runtime": { "token": "h.p.s", "idToken": true } });
891 let mut spec = g1t_kit::wire::snake_case_keeping(sent.clone(), super::JOB_SPEC_AS_GIVEN);
892 super::with_runtime(&mut spec, "https://api.g1t.sh", true);
893 assert!(spec.get("runtime").is_none(), "the runner never sees it");
894 let vars = &spec["variables"];
895 assert_eq!(vars["GITHUB_SHA"], "abc");
896 assert_eq!(vars["ACTIONS_RUNTIME_TOKEN"], "h.p.s");
897 assert_eq!(vars["ACTIONS_CACHE_URL"], "https://api.g1t.sh/actions/toolkit/");
898 assert_eq!(vars["ACTIONS_ID_TOKEN_REQUEST_TOKEN"], "h.p.s");
899 // No OIDC key here: no OIDC variables, whatever the job may do.
900 let mut spec = g1t_kit::wire::snake_case_keeping(sent, super::JOB_SPEC_AS_GIVEN);
901 super::with_runtime(&mut spec, "https://api.g1t.sh", false);
902 assert!(spec["variables"].get("ACTIONS_ID_TOKEN_REQUEST_URL").is_none());
903 assert_eq!(spec["variables"]["ACTIONS_RESULTS_URL"], "https://api.g1t.sh/");
904 }
905
906 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell907 fn camel_case_keys_are_accepted() {
908 assert_eq!(
909 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
910 json!({ "count_agent_approvals": false, "title": "x" })
911 );
912 }
913
914 #[test]
915 fn snake_case_wins_when_both_are_given() {
916 assert_eq!(
917 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
918 json!({ "keep_issue_open": true })
919 );
920 }
921}
922
API and MCP server in Rust; a public index at the API root923// The API is called from browsers too: the reference's explorer, and apps
924// built on g1t. It carries no cookies, so any origin may call it.
925#[event(fetch)]
926async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
927 let mut response = respond(request, &env).await?;
928 let headers = response.headers_mut();
929 headers.set("access-control-allow-origin", "*")?;
930 headers.set(
931 "access-control-allow-headers",
932 "authorization, content-type",
933 )?;
934 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
935 headers.set("access-control-expose-headers", "www-authenticate")?;
936 Ok(response)
937}

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