flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/api/src/lib.rs

712 lines29,053 bytesCodeBlame
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
7mod audit;
8mod blobs;
9mod mcp;
10mod oauth;
11mod openapi;
12mod operations;
13mod renamed;
14#[cfg(test)]
15mod responses;
16mod rest;
17
18use g1t_contracts::billing::FinishRunArgs;
19use g1t_contracts::identity::{
20 DeviceClaim, DeviceClaimArgs, DeviceStart, DeviceStartArgs, TokenArgs,
21};
22use g1t_contracts::work::{
23 CheckRun, Mergeable, QueueState, ReportChecksArgs, ReportMergecheckArgs, ReportPlanArgs,
24 ReportQueueArgs, ReportReviewArgs,
25};
26use g1t_contracts::identity::AgentScope;
27use g1t_contracts::{Failure, FailureCode, Outcome, PrincipalKind, Viewer};
28use g1t_kit::wire;
29use serde_json::{Value, json};
30use worker::{Context, Env, Method, Request, Response, Result, event};
31
32use operations::Services;
33
34const API: &str = "https://api.g1t.sh";
35
36fn method_name(method: Method) -> &'static str {
37 match method {
38 Method::Get => "GET",
39 Method::Post => "POST",
40 Method::Patch => "PATCH",
41 Method::Put => "PUT",
42 Method::Delete => "DELETE",
43 Method::Options => "OPTIONS",
44 Method::Head => "HEAD",
45 _ => "OTHER",
46 }
47}
48
49/// A JSON response. Every body the API sends has its keys in `snake_case`;
50/// the contracts it passes through are `camelCase`, so they are converted
51/// here, on the way out (see [`g1t_kit::wire`]). The OpenAPI document and
52/// the MCP protocol's own envelope keep the spelling their standards use.
53pub(crate) fn reply<T: serde::Serialize>(value: &T) -> Result<Response> {
54 Response::from_json(&wire::snake_case(serde_json::to_value(value)?))
55}
56
57/// The parts of a job's spec (`POST /actions/jobs/{job}/spec`) that are the
58/// workflow file, GitHub's contexts and event, and where to check out, all
59/// passed through as they are.
60const JOB_SPEC_AS_GIVEN: &[&str] = &[
61 "spec", "workflow", "github", "event", "contexts", "checkout",
62];
63
64/// An error in the shape every endpoint uses.
65fn failure(failure: &Failure) -> Result<Response> {
66 Ok(reply(&json!({ "error": failure }))?.with_status(failure.code.http_status()))
67}
68
69fn fail(code: FailureCode, message: &str) -> Result<Response> {
70 failure(&Failure {
71 code,
72 message: message.to_owned(),
73 })
74}
75
76/// A request body as JSON. An empty or malformed body is no input.
77async fn json_body(request: &mut Request) -> Value {
78 request.json().await.unwrap_or(Value::Null)
79}
80
81/// Who a request's `Authorization: Bearer g1t_…` names. A missing token is
82/// an anonymous viewer; a wrong one is refused, so that a typo does not
83/// silently look signed out.
84async fn authenticate(
85 request: &Request,
86 services: &Services,
87) -> Result<std::result::Result<Viewer, Response>> {
88 let header = request.headers().get("authorization")?.unwrap_or_default();
89 let token = match header.split_once(' ') {
90 Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") && !token.is_empty() => {
91 token.trim()
92 }
93 _ => return Ok(Ok(None)),
94 };
95 let viewer: Viewer = g1t_kit::call(
96 &services.identity,
97 "user_for_access_token",
98 &TokenArgs {
99 token: token.to_owned(),
100 },
101 )
102 .await?;
103 if viewer.is_some() {
104 return Ok(Ok(viewer));
105 }
106 let mut response = fail(FailureCode::Unauthenticated, "Invalid access token.")?;
107 // Tells an MCP client where to sign in again.
108 response.headers_mut().set(
109 "www-authenticate",
110 &format!("{}, error=\"invalid_token\"", oauth::MCP_CHALLENGE),
111 )?;
112 Ok(Err(response))
113}
114
115/// Where everything is, for someone or something exploring the API.
116fn index() -> Value {
117 let repo = format!("{API}/repos/{{owner}}/{{name}}");
118 json!({
119 "documentation_url": "https://docs.g1t.sh/reference/api/",
120 "openapi_url": format!("{API}/openapi.json"),
121 "mcp_url": "https://mcp.g1t.sh",
122 "current_user_url": format!("{API}/user"),
123 "workspaces_url": format!("{API}/workspaces"),
124 "repositories_url": format!("{API}/repos{{?q}}"),
125 "search_url": format!("{API}/search{{?q,type,page,per_page}}"),
126 "repository_url": repo,
127 "repository_events_url": format!("{repo}/events{{?before}}"),
128 "labels_url": format!("{repo}/labels"),
129 "issues_url": format!("{repo}/issues{{?state,label}}"),
130 "issue_url": format!("{repo}/issues/{{number}}"),
131 "issue_comments_url": format!("{repo}/issues/{{number}}/comments"),
132 "pulls_url": format!("{repo}/pulls{{?state}}"),
133 "pull_url": format!("{repo}/pulls/{{number}}"),
134 "pull_changes_url": format!("{repo}/pulls/{{number}}/changes"),
135 "pull_reviews_url": format!("{repo}/pulls/{{number}}/reviews"),
136 "pull_session_url": format!("{repo}/pulls/{{number}}/session{{?after}}"),
137 "device_code_url": format!("{API}/device/code"),
138 "device_token_url": format!("{API}/device/token"),
139 "oauth_metadata_url": format!("{API}/.well-known/oauth-authorization-server"),
140 "git_url": "https://g1t.sh/{owner}/{name}.git",
141 "integrations_url": format!("{API}/workspaces/{{workspace}}/integrations"),
142 "context_url": format!("{repo}/context{{?reference}}"),
143 "import_issue_url": format!("{repo}/issues/import"),
144 "hooks_url": format!("{API}/hooks/{{integration}}"),
145 })
146}
147
148// Signing in from a tool. Accounts are created, and passwords typed, only
149// in a browser; a tool gets its token by having a person approve a code.
150
151/// Passes a request from an outside system to its connection, as it came:
152/// its signature covers the exact bytes of the body.
153async fn receive_hook(request: &mut Request, services: &Services, id: &str) -> Result<Response> {
154 let headers: std::collections::HashMap<String, String> = request
155 .headers()
156 .entries()
157 .map(|(name, value)| (name.to_lowercase(), value))
158 .collect();
159 let body = request.text().await.unwrap_or_default();
160 // A push to GitHub with many commits makes a large payload.
161 let limit = if id == "github" { 10_000_000 } else { 1_000_000 };
162 if body.len() > limit {
163 return Ok(reply(&json!({ "message": "The body is too large." }))?.with_status(413));
164 }
165 // g1t's GitHub App has one webhook for every installation; it is
166 // checked against the app's own secret.
167 let (method, args) = if id == "github" {
168 ("github_receive", json!({ "headers": headers, "body": body }))
169 } else {
170 ("receive", json!({ "id": id, "headers": headers, "body": body }))
171 };
172 let received: g1t_contracts::integrations::Received =
173 g1t_kit::call(&services.integrations, method, &args).await?;
174 Ok(reply(&json!({ "message": received.message }))?.with_status(received.status))
175}
176
177async fn receive_stripe(request: &mut Request, env: &Env) -> Result<Response> {
178 let signature = request.headers().get("stripe-signature")?.unwrap_or_default();
179 let payload = request.text().await.unwrap_or_default();
180 if payload.len() > 1_000_000 || signature.is_empty() {
181 return Ok(reply(&json!({ "message": "Not a Stripe event." }))?.with_status(400));
182 }
183 let handled: g1t_contracts::Outcome<bool> = g1t_kit::call(
184 &env.service("BILLING")?,
185 "stripe_webhook",
186 &g1t_contracts::billing::StripeWebhookArgs { payload, signature },
187 )
188 .await?;
189 // A refusal is a 400, so Stripe shows it as failed; anything handled,
190 // or already handled, is a 200, so Stripe stops sending it.
191 Ok(match handled {
192 g1t_contracts::Outcome::Ok(_) => reply(&json!({ "received": true }))?,
193 g1t_contracts::Outcome::Fail(failure) => {
194 reply(&json!({ "message": failure.message }))?.with_status(400)
195 }
196 })
197}
198
199async fn device_code(request: &mut Request, services: &Services) -> Result<Response> {
200 let body = json_body(request).await;
201 let started: DeviceStart = g1t_kit::call(
202 &services.identity,
203 "device_start",
204 &DeviceStartArgs {
205 client_name: body["client_name"].as_str().unwrap_or_default().to_owned(),
206 },
207 )
208 .await?;
209 reply(&json!({
210 "device_code": started.device_code,
211 "user_code": started.user_code,
212 "verification_uri": "https://g1t.sh/device",
213 "verification_uri_complete": format!("https://g1t.sh/device?code={}", started.user_code),
214 "expires_in": started.expires_in,
215 "interval": started.interval,
216 }))
217}
218
219async fn device_token(request: &mut Request, services: &Services) -> Result<Response> {
220 let body = json_body(request).await;
221 let claim: DeviceClaim = g1t_kit::call(
222 &services.identity,
223 "device_claim",
224 &DeviceClaimArgs {
225 device_code: body["device_code"].as_str().unwrap_or_default().to_owned(),
226 },
227 )
228 .await?;
229 reply(&match claim {
230 DeviceClaim::Approved { token, user } => json!({
231 "status": "approved",
232 "token": token,
233 "username": user.username,
234 "verified": user.verified,
235 }),
236 DeviceClaim::Pending => json!({ "status": "pending" }),
237 DeviceClaim::Denied => json!({ "status": "denied" }),
238 DeviceClaim::Expired => json!({ "status": "expired" }),
239 })
240}
241
242/// A sandbox reporting on its run of a pull request's acceptance checks.
243/// The run's own token, in the body, is the credential: it was given to
244/// that sandbox and to nothing else.
245async fn report_checks(
246 request: &mut Request,
247 services: &Services,
248 run_id: &str,
249) -> Result<Response> {
250 let body = json_body(request).await;
251 let reported: Outcome<CheckRun> = g1t_kit::call(
252 &services.work,
253 "report_checks",
254 &ReportChecksArgs {
255 run_id: run_id.to_owned(),
256 token: body["token"].as_str().unwrap_or_default().to_owned(),
257 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
258 error: body["error"].as_str().map(str::to_owned),
259 skip: false,
260 },
261 )
262 .await?;
263 match reported {
264 Outcome::Ok(run) => reply(&json!({ "status": run.status })),
265 Outcome::Fail(refused) => failure(&refused),
266 }
267}
268
269/// A sandbox reporting one tested state of a merge queue. As with checks,
270/// the entry's own token is the credential.
271async fn report_queue(
272 request: &mut Request,
273 services: &Services,
274 entry_id: &str,
275) -> Result<Response> {
276 let body = json_body(request).await;
277 let reported: Outcome<QueueState> = g1t_kit::call(
278 &services.work,
279 "report_queue",
280 &ReportQueueArgs {
281 entry_id: entry_id.to_owned(),
282 token: body["token"].as_str().unwrap_or_default().to_owned(),
283 combined_commit: body["combinedCommit"].as_str().map(str::to_owned),
284 results: serde_json::from_value(body["results"].clone()).unwrap_or_default(),
285 error: body["error"].as_str().map(str::to_owned),
286 conflict_with: body["conflictWith"].as_u64().map(|n| n as u32),
287 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
288 },
289 )
290 .await?;
291 match reported {
292 Outcome::Ok(state) => reply(&json!({ "state": state })),
293 Outcome::Fail(refused) => failure(&refused),
294 }
295}
296
297/// A sandbox reporting whether a pull request merges cleanly. As with
298/// checks, the probe's own token is the credential.
299async fn report_mergecheck(
300 request: &mut Request,
301 services: &Services,
302 pull_id: &str,
303) -> Result<Response> {
304 let body = json_body(request).await;
305 let reported: Outcome<Mergeable> = g1t_kit::call(
306 &services.work,
307 "report_mergecheck",
308 &ReportMergecheckArgs {
309 pull_id: pull_id.to_owned(),
310 token: body["token"].as_str().unwrap_or_default().to_owned(),
311 conflicts: serde_json::from_value(body["conflicts"].clone()).unwrap_or_default(),
312 error: body["error"].as_str().map(str::to_owned),
313 },
314 )
315 .await?;
316 match reported {
317 Outcome::Ok(state) => reply(&json!({ "mergeable": state })),
318 Outcome::Fail(refused) => failure(&refused),
319 }
320}
321
322/// A sandbox reporting the review its agent wrote. As with checks, the
323/// run's own token is the credential.
324async fn report_review(
325 request: &mut Request,
326 services: &Services,
327 run_id: &str,
328) -> Result<Response> {
329 let body = json_body(request).await;
330 let reported: Outcome<bool> = g1t_kit::call(
331 &services.work,
332 "report_review",
333 &ReportReviewArgs {
334 run_id: run_id.to_owned(),
335 token: body["token"].as_str().unwrap_or_default().to_owned(),
336 verdict: serde_json::from_value(body["verdict"].clone()).unwrap_or(None),
337 body: body["body"].as_str().unwrap_or_default().to_owned(),
338 comments: serde_json::from_value(body["comments"].clone()).unwrap_or_default(),
339 model: body["model"].as_str().map(str::to_owned),
340 error: body["error"].as_str().map(str::to_owned),
341 },
342 )
343 .await?;
344 match reported {
345 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
346 Outcome::Fail(refused) => failure(&refused),
347 }
348}
349
350/// A sandbox reporting the plan its agent wrote. As with checks, the
351/// plan's own token is the credential.
352async fn report_plan(
353 request: &mut Request,
354 services: &Services,
355 plan_id: &str,
356) -> Result<Response> {
357 let body = json_body(request).await;
358 let reported: Outcome<bool> = g1t_kit::call(
359 &services.work,
360 "report_plan",
361 &ReportPlanArgs {
362 plan_id: plan_id.to_owned(),
363 token: body["token"].as_str().unwrap_or_default().to_owned(),
364 summary: body["summary"].as_str().unwrap_or_default().to_owned(),
365 issues: serde_json::from_value(body["issues"].clone()).unwrap_or_default(),
366 error: body["error"].as_str().map(str::to_owned),
367 },
368 )
369 .await?;
370 match reported {
371 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
372 Outcome::Fail(refused) => failure(&refused),
373 }
374}
375
376/// A sandbox reporting what its agent's run cost, so that the workspace
377/// it worked for is charged. As with checks, the run's own token is the
378/// credential.
379async fn report_usage(
380 request: &mut Request,
381 services: &Services,
382 run_id: &str,
383) -> Result<Response> {
384 let body = json_body(request).await;
385 let charged: Outcome<bool> = g1t_kit::call(
386 &services.billing,
387 "finish_run",
388 &FinishRunArgs {
389 run_id: run_id.to_owned(),
390 token: body["token"].as_str().unwrap_or_default().to_owned(),
391 cost_usd: body["cost_usd"].as_f64().unwrap_or_default(),
392 turns: body["turns"].as_u64().unwrap_or_default() as u32,
393 },
394 )
395 .await?;
396 match charged {
397 Outcome::Ok(_) => reply(&json!({ "recorded": true })),
398 Outcome::Fail(refused) => failure(&refused),
399 }
400}
401
402async fn respond(mut request: Request, env: &Env) -> Result<Response> {
403 let method = method_name(request.method());
404 if method == "OPTIONS" {
405 return Ok(Response::empty()?.with_status(204));
406 }
407 let url = request.url()?;
408 // Paths carry no version. An earlier form began with `/v1`, which is
409 // still accepted so that nothing already written against it breaks.
410 let path = match url.path().strip_prefix("/v1") {
411 Some(rest) if rest.is_empty() || rest.starts_with('/') => rest.to_owned(),
412 _ => url.path().to_owned(),
413 };
414 let on_mcp = url.host_str().is_some_and(|host| host.starts_with("mcp."));
415 let mut services = Services::new(env)?;
416
417 // Stripe reporting to billing. Signed with the secret of the endpoint
418 // billing registered; the body goes through exactly as received, since
419 // the signature covers its bytes.
420 if method == "POST" && !on_mcp && path == "/stripe/webhook" {
421 return receive_stripe(&mut request, env).await;
422 }
423
424 // Outside systems reporting to a connection. They sign what they send
425 // with the connection's own secret, which is not a g1t token, so this
426 // comes before anything that would read one.
427 if method == "POST" && !on_mcp
428 && let Some(id) = path.strip_prefix("/hooks/").filter(|id| !id.is_empty() && !id.contains('/')) {
429 return receive_hook(&mut request, &services, id).await;
430 }
431
432 // A sandbox building a deployment, reporting with its build's token,
433 // which is not a g1t token. The body goes through as it is: it can
434 // carry a Worker's bundled code.
435 if method == "POST" && !on_mcp
436 && let Some(rest) = path.strip_prefix("/deployments/jobs/")
437 {
438 let target = format!("https://deployments/jobs/{rest}");
439 let body = request.bytes().await?;
440 let headers = worker::Headers::new();
441 headers.set("content-type", "application/json")?;
442 let mut init = worker::RequestInit::new();
443 init.with_method(Method::Post)
444 .with_headers(headers)
445 .with_body(Some(worker::js_sys::Uint8Array::from(body.as_slice()).into()));
446 let mut answer = env
447 .service("DEPLOYMENTS")?
448 .fetch_request(Request::new_with_init(&target, &init)?)
449 .await?;
450 // A fresh response: a fetched one's headers cannot be changed, and
451 // every response gets the API's own on the way out.
452 let status = answer.status_code();
453 let bytes = answer.bytes().await?;
454 let bytes = match serde_json::from_slice::<Value>(&bytes) {
455 Ok(body) => serde_json::to_vec(&wire::snake_case(body))?,
456 Err(_) => bytes,
457 };
458 return Ok(Response::from_bytes(bytes)?
459 .with_status(status)
460 .with_headers({
461 let headers = worker::Headers::new();
462 headers.set("content-type", "application/json")?;
463 headers
464 }));
465 }
466
467 // A sandbox's artifacts and cache, with its job's token, which is not a
468 // g1t token either.
469 if !on_mcp
470 && let Some(rest) = path.strip_prefix("/actions/jobs/")
471 && (rest.contains("/artifacts") || rest.ends_with("/cache"))
472 {
473 let rest = rest.to_owned();
474 return blobs::for_job(request, env, &services, method, &rest).await;
475 }
476
477 let viewer = match authenticate(&request, &services).await? {
478 Ok(viewer) => viewer,
479 Err(refused) => return Ok(refused),
480 };
481 services.audit = audit::AuditContext::of(&request, on_mcp);
482 // An agent's token: what it may do comes with it, on the composite
483 // identity identity resolved it to.
484 if let Some(acting) = viewer.as_ref().and_then(|viewer| viewer.acting.as_ref()) {
485 services.scope = Some(acting.scope.clone());
486 } else if viewer.as_ref().is_some_and(|viewer| viewer.kind == PrincipalKind::Agent) {
487 let header = request.headers().get("authorization")?.unwrap_or_default();
488 let token = header.split_once(' ').map(|(_, token)| token.trim()).unwrap_or_default();
489 let scope: Option<AgentScope> = g1t_kit::call(
490 &services.identity,
491 "agent_scope",
492 &TokenArgs {
493 token: token.to_owned(),
494 },
495 )
496 .await?;
497 // A scope is what lets an agent's token do anything at all.
498 let Some(scope) = scope else {
499 return fail(FailureCode::Unauthenticated, "Invalid access token.");
500 };
501 services.scope = Some(scope);
502 }
503 if let Some(response) = oauth::handle(&mut request, &services, method, &path).await? {
504 return Ok(response);
505 }
506 if on_mcp {
507 return mcp::handle(request, &services, &viewer).await;
508 }
509
510 match (method, path.trim_end_matches('/')) {
511 ("GET", "") => return reply(&index()),
512 ("GET", "/openapi.json") => return Response::from_json(&openapi::document()),
513 // A run's artifacts: listed, or one downloaded.
514 ("GET", path) if path.starts_with("/repos/") && path.contains("/actions/runs/") && path.contains("/artifacts") => {
515 let parts: Vec<&str> = path.trim_start_matches("/repos/").split('/').collect();
516 if let [owner, repo, "actions", "runs", run, "artifacts", rest @ ..] = parts.as_slice() {
517 return match rest {
518 [] => {
519 let seen: Outcome<Value> = g1t_kit::call(
520 &services.actions,
521 "run",
522 &json!({ "repo": { "namespace": owner, "name": repo }, "viewer": viewer, "id": run }),
523 )
524 .await?;
525 match seen {
526 Outcome::Ok(_) => reply(&blobs::of_run(env, run).await?),
527 Outcome::Fail(refused) => failure(&refused),
528 }
529 }
530 [name] => blobs::download(env, &services, &viewer, owner, repo, run, name).await,
531 _ => fail(FailureCode::NotFound, "No such endpoint."),
532 };
533 }
534 }
535 ("POST", "/device/code") => return device_code(&mut request, &services).await,
536 ("POST", "/device/token") => return device_token(&mut request, &services).await,
537 // Where a pull request lives, for a tool that knows only its fork.
538 ("GET", path) if path.starts_with("/pulls/") && !path[7..].contains('/') => {
539 let located: Outcome<Value> = g1t_kit::call(
540 &services.work,
541 "locate_pull",
542 &json!({ "id": &path[7..], "viewer": viewer }),
543 )
544 .await?;
545 return match located {
546 Outcome::Ok(value) => reply(&value),
547 Outcome::Fail(refused) => failure(&refused),
548 };
549 }
550 ("POST", path) if path.starts_with("/mergechecks/") => {
551 let pull_id = path.trim_start_matches("/mergechecks/").to_owned();
552 return report_mergecheck(&mut request, &services, &pull_id).await;
553 }
554 ("POST", path) if path.starts_with("/queue/") => {
555 let entry_id = path.trim_start_matches("/queue/").to_owned();
556 return report_queue(&mut request, &services, &entry_id).await;
557 }
558 // A sandbox running a GitHub Actions job: fetching the job, and
559 // reporting how it goes. The job's own token is the credential.
560 ("POST", path) if path.starts_with("/actions/jobs/") => {
561 let rest = path.trim_start_matches("/actions/jobs/");
562 let (job, method) = match rest.strip_suffix("/spec") {
563 Some(job) => (job.to_owned(), "job_spec"),
564 None => (rest.to_owned(), "job_report"),
565 };
566 let body = json_body(&mut request).await;
567 let answered: Outcome<Value> = g1t_kit::call(
568 &services.actions,
569 method,
570 &json!({ "job": job, "token": body["token"], "report": body["report"] }),
571 )
572 .await?;
573 return match answered {
574 // A job's spec is the workflow and its contexts as GitHub
575 // has them; only g1t's own keys around them are converted.
576 Outcome::Ok(value) => Response::from_json(&wire::snake_case_keeping(value, JOB_SPEC_AS_GIVEN)),
577 Outcome::Fail(refused) => failure(&refused),
578 };
579 }
580 // A sandbox reporting its agent run's steps, cost and end. As with
581 // checks, the run's own token, in the body, is the credential.
582 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/report") => {
583 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/report");
584 let mut body = json_body(&mut request).await;
585 if !body.is_object() {
586 body = json!({});
587 }
588 body["runId"] = json!(run_id);
589 let reported: Outcome<Value> = g1t_kit::call(&services.work, "report_run", &body).await?;
590 return match reported {
591 Outcome::Ok(status) => reply(&json!({ "status": status })),
592 Outcome::Fail(refused) => failure(&refused),
593 };
594 }
595 // What a run's agent learned, as memory candidates; the same token.
596 ("POST", path) if path.starts_with("/agent-runs/") && path.ends_with("/learned") => {
597 let run_id = path.trim_start_matches("/agent-runs/").trim_end_matches("/learned");
598 let body = json_body(&mut request).await;
599 let learned = json!({
600 "runId": run_id,
601 "token": body["token"].as_str().unwrap_or_default(),
602 "items": body["items"].as_array().cloned().unwrap_or_default(),
603 });
604 let captured: Outcome<Value> = g1t_kit::call(&services.work, "report_learned", &learned).await?;
605 return match captured {
606 Outcome::Ok(captured) => reply(&captured),
607 Outcome::Fail(refused) => failure(&refused),
608 };
609 }
610 ("POST", path) if path.starts_with("/checks/") => {
611 let run_id = path.trim_start_matches("/checks/").to_owned();
612 return report_checks(&mut request, &services, &run_id).await;
613 }
614 ("POST", path) if path.starts_with("/runs/") && path.ends_with("/usage") => {
615 let run_id = path
616 .trim_start_matches("/runs/")
617 .trim_end_matches("/usage")
618 .to_owned();
619 return report_usage(&mut request, &services, &run_id).await;
620 }
621 ("POST", path) if path.starts_with("/plans/") => {
622 let plan_id = path.trim_start_matches("/plans/").to_owned();
623 return report_plan(&mut request, &services, &plan_id).await;
624 }
625 ("POST", path) if path.starts_with("/reviews/") => {
626 let run_id = path.trim_start_matches("/reviews/").to_owned();
627 return report_review(&mut request, &services, &run_id).await;
628 }
629 _ => {}
630 }
631
632 let query: Vec<(String, String)> = url
633 .query_pairs()
634 .map(|(name, value)| (name.into_owned(), value.into_owned()))
635 .collect();
636 let body = if method == "GET" {
637 Value::Null
638 } else {
639 snake_case_keys(json_body(&mut request).await)
640 };
641 let Some((route, input)) = rest::resolve(method, &path, &query, body) else {
642 return fail(FailureCode::NotFound, "No such endpoint.");
643 };
644 match audit::run(route.op, &services, &viewer, &input).await? {
645 Outcome::Ok(value) => reply(&value),
646 Outcome::Fail(refused) => failure(&refused),
647 }
648}
649
650/// Request bodies take the same keys as the MCP tools, `snake_case`, as
651/// responses use; the `camelCase` spelling is accepted too.
652fn snake_case_keys(body: Value) -> Value {
653 let Value::Object(fields) = body else {
654 return body;
655 };
656 let mut out = serde_json::Map::new();
657 for (key, value) in fields {
658 let mut snake = String::with_capacity(key.len() + 4);
659 for c in key.chars() {
660 if c.is_ascii_uppercase() {
661 snake.push('_');
662 snake.push(c.to_ascii_lowercase());
663 } else {
664 snake.push(c);
665 }
666 }
667 // A key given in both spellings keeps the snake_case one.
668 if snake != key && out.contains_key(&snake) {
669 continue;
670 }
671 out.insert(snake, value);
672 }
673 Value::Object(out)
674}
675
676#[cfg(test)]
677mod tests {
678 use super::snake_case_keys;
679 use serde_json::json;
680
681 #[test]
682 fn camel_case_keys_are_accepted() {
683 assert_eq!(
684 snake_case_keys(json!({ "countAgentApprovals": false, "title": "x" })),
685 json!({ "count_agent_approvals": false, "title": "x" })
686 );
687 }
688
689 #[test]
690 fn snake_case_wins_when_both_are_given() {
691 assert_eq!(
692 snake_case_keys(json!({ "keep_issue_open": true, "keepIssueOpen": false })),
693 json!({ "keep_issue_open": true })
694 );
695 }
696}
697
698// The API is called from browsers too: the reference's explorer, and apps
699// built on g1t. It carries no cookies, so any origin may call it.
700#[event(fetch)]
701async fn fetch(request: Request, env: Env, _ctx: Context) -> Result<Response> {
702 let mut response = respond(request, &env).await?;
703 let headers = response.headers_mut();
704 headers.set("access-control-allow-origin", "*")?;
705 headers.set(
706 "access-control-allow-headers",
707 "authorization, content-type",
708 )?;
709 headers.set("access-control-allow-methods", "GET, POST, PATCH, OPTIONS")?;
710 headers.set("access-control-expose-headers", "www-authenticate")?;
711 Ok(response)
712}