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