REST API
apps/api is a Hono server (@hono/node-server). It exposes the synchronous agent routes, durable session routes, the factory intake routes and the CodeCrucible routes. The route table lives in packages/agent-types/src/http.ts (routes), the typed client in packages/agent-client derives its methods from that table, and the server registers only those routes plus two byte-oriented routes that the table cannot express (the factory artifact bytes and the quality survivors page).
Route catalogue
| Route | Method | Auth | Enabled by | Success | Purpose |
|---|---|---|---|---|---|
/health | GET | public | always | 200 {status: "ok"} | liveness; skips auth and rate limiting |
/v1/models | GET | API key | always | 200 {models: string[]} | the MODELS allowlist |
/v1/usage | GET | API key, admin client | always | 200 UsageResponse | today's spend per client, stale ledger reservations; non-admin clients get 404 |
/v1/agent | POST | API key | always | 200 AgentHttpResponse | one synchronous run, JSON reply |
/v1/agent/stream | POST | API key | always | 200 text/event-stream | the same run as server-sent events |
/v1/sessions | POST | API key | always (503 without Temporal) | 201 SessionCreated | open a durable session |
/v1/sessions/:id/messages | POST | API key | always (503 without Temporal) | 202 MessageAccepted | queue one turn |
/v1/sessions/:id | GET | API key | always | 200 SessionView | poll session and turns (Postgres only) |
/v1/sessions/:id | DELETE | API key | always | 202 {status: "cancelling"} | cancel the session |
/v1/factory/jobs | POST | API key in FACTORY_CLIENTS | FACTORY_ENABLED | 202 new, 200 replay | submit a factory job |
/v1/factory/jobs/:id | GET | API key in FACTORY_CLIENTS or FACTORY_APPROVERS | FACTORY_ENABLED | 200 FactoryJobView | poll a job |
/v1/factory/jobs/:id/events | GET | as above | FACTORY_ENABLED | 200 FactoryEvents | job event log |
/v1/factory/jobs/:id/artifacts/:kind | GET | as above | FACTORY_ENABLED | 200 text/plain | exact artifact bytes |
/v1/factory/jobs/:id/approvals | POST | API key in FACTORY_APPROVERS | FACTORY_ENABLED | 200 ApprovalRecorded | decide a gate |
/v1/factory/jobs/:id | DELETE | as for GET | FACTORY_ENABLED | 202 {status: "cancelling"} | cancel a job |
/v1/quality/runs | POST | API key in QUALITY_CLIENTS | QUALITY_ENABLED | 202 new, 200 replay | submit a CodeCrucible assessment |
/v1/quality/verify | POST | API key in QUALITY_CLIENTS | QUALITY_ENABLED | 202 new, 200 replay | submit a CodeCrucible verify run |
/v1/quality/runs/:id | GET | API key in QUALITY_CLIENTS | QUALITY_ENABLED | 200 QualityRunView | poll a run |
/v1/quality/runs/:id/survivors | GET | API key in QUALITY_CLIENTS | QUALITY_ENABLED | 200 QualitySurvivorsPage | page of surviving mutants (?cursor=, 200 per page) |
When FACTORY_ENABLED or QUALITY_ENABLED is not set, the route group is not registered at all. A request that passes authentication then falls through to the not-found handler and answers 404 not_found. The quality routes are specified in Quality REST and limits; the factory routes are explained in Factory job lifecycle and Gates and approvals.
The typed client (createAgentClient) has one method per entry of routes. It does not expose the artifact route or the survivors route. It does no retries and no polling; callers read AgentApiError.retryAfterSec.
Request pipeline
Every request passes the same middleware chain in the order registered by buildApp (apps/api/src/app.ts).
Properties worth knowing:
- Unknown paths are authenticated first. An unauthenticated request to a path that does not exist answers 401, not 404. Only
GET /healthis public. - The per-client counter increments on every authenticated request, including requests that later fail validation.
- Both counters are in-memory fixed windows (
WindowCounterinapps/api/src/limits.ts, windowWINDOW_MS = 60000, cleared when the UTC minute changes). Source comment: "in-memory, so replicas = 1 (plan P2a-2); a shared store is needed before scaling out."
Authentication and clients
API_KEYSis a JSON object mapping a client id to its key. A client id matches^[a-z0-9-]{1,64}$. A key has at least 32 characters. The map must hold at least one client and no two clients may share a key value. Invalid JSON or a violated rule stops startup.- The caller sends the key in the
Authorizationheader using the bearer scheme (Bearer, one space, the key). Any other form never matches. createAuthenticator(apps/api/src/auth.ts) hashes the presented key with SHA-256 and compares it against the stored digest of every client withcrypto.timingSafeEqual, with no early exit. Raw keys are never logged or kept after the digests are computed. The comment in the file records that these per-client service keys are "P2 only; P2.G replaces them with OBO".API_KEYSis a flat map with no scopes. Authorization is by membership in env lists:API_ADMIN_CLIENTS(usage route),FACTORY_CLIENTS,FACTORY_APPROVERS,QUALITY_CLIENTS. Startup fails when a name in any of those lists is not inAPI_KEYS.- The request's client id is the ownership scope. Session and quality routes answer 404 for another client's id. Factory submitters see their own jobs; approvers see every job.
Client IP and TRUST_PROXY_HOPS
The IP failure throttle needs the real client IP. clientIp (apps/api/src/client-ip.ts) takes the socket address and, when TRUST_PROXY_HOPS (0 to 5, default 0) is above zero, the entry hops places left of the socket peer in X-Forwarded-For. It canonicalises IPv4, IPv6 and IPv4-mapped IPv6 forms, and fails closed to the socket address when the header is short or malformed. At startup serve.ts logs a warning when TRUST_PROXY_HOPS=0 and either NODE_ENV=production or the host is not loopback, because behind a reverse proxy every client then shares one IP.
Rate limits and concurrency
| Limit | Env var | Default | Effect |
|---|---|---|---|
| Authenticated requests per client per minute | RATE_LIMIT_PER_MIN | 30 | 429 rate_limited, Retry-After = seconds to the next window |
| Failed authentications per IP per minute | AUTH_FAIL_LIMIT_PER_MIN | 10 | 429 rate_limited before the key is even checked |
Concurrent synchronous runs (both /v1/agent routes) | MAX_CONCURRENCY | 2 | 429 busy, Retry-After: 5 |
| Request body size | constant BODY_LIMIT_BYTES | 65536 bytes | 413 payload_too_large |
| Open sessions per client | SESSION_MAX_OPEN_PER_CLIENT | 5 | 409 conflict |
| Session turns | SESSION_MAX_TURNS | 50 | 409 conflict |
| Active factory jobs per client | FACTORY_MAX_ACTIVE_PER_CLIENT | 2 (max 100) | 429 rate_limited |
| Submitted quality runs waiting for admission | QUALITY_MAX_PENDING_PER_CLIENT | 4 (max 100) | 429 too_many_pending |
The Retry-After value for a window limit is ceil((60000 - (now mod 60000)) / 1000) seconds.
Error contract
Every non-2xx response is an ApiError JSON body, built by sendOutcome (apps/api/src/errors.ts):
{
"error": { "code": "rate_limited", "message": "rate limited" },
"requestId": "api/00000000-0000-0000-0000-000000000000"
}
message defaults to the code with underscores replaced by spaces. For internal_error it is always internal error; details are logged, never returned. The x-request-id response header carries the same id.
Status codes by error code (HTTP_STATUS, "Table E"):
| Code | HTTP | Typical cause |
|---|---|---|
invalid_request | 400 | schema mismatch, invalid JSON, model not in MODELS, bad header or id |
unsupported_capability | 400 | declared; a runtime refusal is mapped to 500 before it reaches HTTP |
unauthorized | 401 | missing, malformed or unknown API key |
forbidden | 403 | authenticated client outside the factory or quality list, non-approver on approvals |
not_found | 404 | unknown path, unknown id, another client's id, admin route for a non-admin, disabled route group |
conflict | 409 | session state conflicts, idempotency key reuse with another body, approval refused |
payload_too_large | 413 | body over 64 KiB, factory task over 16 KiB |
rate_limited | 429 | window limits, active factory job cap |
busy | 429 | all MAX_CONCURRENCY slots in use |
budget_exhausted | 429 | ledger refused the reservation, quality daily sandbox-second limit |
too_many_pending | 429 | pending quality submissions cap |
internal_error | 500 | unhandled error, runtime invalid_request or unsupported_capability |
agent_failed | 502 | the runtime failed the turn |
agent_limit | 502 | max turns or budget reached |
disabled | 503 | kill switch (AGENTS_DISABLED or the settings flag) |
unavailable | 503 | shutdown, Temporal unreachable |
timeout | 504 | run exceeded its timeout |
Table S: runtime status to response
toResponse(input, cause, now) is the only status-to-response mapping. A run's RuntimeStatus becomes:
| Runtime status | Cause | Response |
|---|---|---|
success | any | 200 |
agent_limit, timeout, agent_failed, disabled, budget_exhausted, internal_error | any | same-named code and status |
invalid_request, unsupported_capability | any | 500 internal_error (input was already validated, so this is a server fault) |
aborted | shutdown | 503 unavailable, Retry-After: 5 |
aborted | client_closed | no reply: the API sends 204 with no body (nobody is listening) |
aborted | none | 500 internal_error |
unavailable | shutdown | 503, Retry-After: 5 |
unavailable | temporal_unreachable | 503, Retry-After: 30 |
busy | any | 429, Retry-After: 5 |
rate_limited | window | 429 with the window Retry-After; other causes: 429 without it |
The HTTP layer's own 400 (validation) never goes through this table. Run failure text (which can name server paths, for example a refused workspace) is logged and never returned.
Synchronous runs
POST /v1/agent and POST /v1/agent/stream share the body schema AgentHttpRequest (a strict object: unknown fields are rejected):
| Field | Rule |
|---|---|
prompt | string, 1 to 20000 characters |
model | string, 1 to 200 characters; must be listed in MODELS or the answer is 400 |
maxTurns | optional integer 1 to 10 |
timeoutMs | optional integer 1000 to 300000 |
maxBudgetUsd | optional number greater than 0, at most 2 |
The handler runs admit (model check, then a semaphore slot), then runtime.run(...) from composeRuntime with profile: 'readonly' and workspace: WORKSPACE_DIR (default /workspace). Absent limits are sent as 0, which means "use the configured default" in withLimits and withBudget. See Agent core decorators.
A successful POST /v1/agent answers {requestId, status: "success", text, usage} with usage holding inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens and optional costUsd. On a non-success status the API logs a warning (with the result text) and returns the Table S mapping.
Streaming model
POST /v1/agent/stream answers 200 with these response headers: content-type: text/event-stream; charset=utf-8, cache-control: no-cache, no-transform, x-accel-buffering: no.
All rejections that can happen before the stream (auth, rate limit, body limit, validation, model check, busy) are plain JSON ApiError responses. After the stream starts the status is 200 and every failure is an error event.
Stream event contract (StreamEvent): zero or more message events (data: {text}), then exactly one done (data: {requestId, text, usage}) or error (data: {code, message, requestId}). Tool events and raw SDK data never appear. An exception inside the stream is logged and becomes error with code internal_error.
Polling model
Only the synchronous routes stream. Everything durable is polled:
| Resource | Poll route | Terminal states |
|---|---|---|
| Session | GET /v1/sessions/:id (Postgres only, works without Temporal) | session closed, cancelled, failed; turn completed, failed, aborted |
| Factory job | GET /v1/factory/jobs/:id | pr_opened, failed, cancelled |
| Quality run | GET /v1/quality/runs/:id | see Quality status and limits |
Sessions
| Route | Request | Responses |
|---|---|---|
POST /v1/sessions | {model} (strict; model must be in MODELS) | 201 {id, status: "open"}; 400; 409 conflict "too many open sessions"; 503 unavailable (Retry-After 30) |
POST /v1/sessions/:id/messages | {prompt} (1 to 20000 characters; per-turn limits cannot be sent) | 202 {messageId, seq, status: "pending"}; 404; 409 with a message below; 503 |
GET /v1/sessions/:id | none | 200 SessionView; 404 |
DELETE /v1/sessions/:id | none | 202 {status: "cancelling"}; 404; 503 |
The 409 messages on POST .../messages are: session not open, session max turns, a turn is already open, session closed (a stale running turn whose workflow is gone) and session workflow is closed (the signal found no workflow).
SessionView is {id, model, status, createdAt, closedAt, messages[]} where each message is {id, seq, prompt, reply, status, errorCode, costUsd}. errorCode is the stored code mapped through Table S with cause none (a code unknown to the table shows as internal_error). costUsd sums every attempt's usage row.
The session route handlers never call runtime.run or the ledger admit: only the worker does, so a Temporal outage writes no ledger row. Every Temporal call of one request shares one budget of TEMPORAL_CALL_TIMEOUT_MS (default 5000, minimum 100). Session logic is detailed in Sessions and workflows.
Orphan repair constants: SESSION_RESIGNAL_AFTER_MS default 30000; STALE_RUNNING_MS = 4 * 360000 + 35000 = 1,475,000 ms (four attempts times the 360 s activity timeout plus the 5 + 10 + 20 s backoff).
Factory routes
Registered only when FACTORY_ENABLED is 1 or true. A route guard on /v1/factory/* answers 403 forbidden to any client in neither FACTORY_CLIENTS nor FACTORY_APPROVERS.
POST /v1/factory/jobs
Header Idempotency-Key (1 to 128 characters, required). Body FactoryJobRequest (strict):
| Field | Rule |
|---|---|
repo | catesworks/<name>, must be listed in FACTORY_REPOS |
baseRef | must be a 40-hex commit SHA at the API (see the contradiction note below) |
task | string, 1 to 16384 characters; over 16 KiB by byte length answers 413 |
budgetUsd | greater than 0, at most 2, at most FACTORY_MAX_JOB_USD (default 0.5) |
maxIterations | integer 1 to 5, default 3 |
policy | optional {app?, role?}, each 1 to 100 characters |
Only clients in FACTORY_CLIENTS may submit; an approver-only client gets 403. Flow, by order of checks: 403, header (400), JSON (400), task bytes (413), schema (400), repo allowlist (400), budget (400), SHA (400), then store.createJob (409 conflict for a key reused with another body, 429 rate_limited for too many active jobs), then the Temporal start.
| Outcome | Response |
|---|---|
| new job, workflow started | 202 {jobId, status: "queued"} |
replay with the same key and body, job past queued | 200 {jobId, status} without a new start |
replay of a job still queued | start is re-issued (REJECT_DUPLICATE, already-started counts as success), 200 |
| Temporal unreachable | job is closed failed with internal_error, ledger prefix factory-<jobId>/ abandoned, 503 unavailable (Retry-After 30) |
The request body hash used for idempotency is sha256(JSON.stringify(parsed body)). The workflow id is factory-<jobId>.
Read routes
GET /v1/factory/jobs/:idreturnsFactoryJobView {id, status, repo, baseSha, errorCode, steps[], costUsd, pendingGate?, pr?, degradedContext}. Stored factory error codes that are alsoErrorCodevalues pass through Table S; job outcome codes such asmax_iterationspass unchanged.GET /v1/factory/jobs/:id/eventsreturns{events: [{kind, detail, at}]}.GET /v1/factory/jobs/:id/artifacts/:kindtakeskindinplan,patch,test-log,reviewand optional?i=(a single digit 0 to 5). It answerstext/plain; charset=utf-8with headersx-artifact-id,x-artifact-sha256(digest of the stored bytes) andx-artifact-redacted(truewhen the response text was scrubbed and so no longer hashes to the digest). Redaction uses the agent-core secret patterns plus GitHub token shapes.
Approvals and cancel
POST /v1/factory/jobs/:id/approvalstakes{gate, digest, decision}. A non-approver gets 403 and no signal is sent. A refusal is 409conflictwith the messageapproval refused: <reason>, reason one ofnot_awaiting,no_pending_gate,digest_mismatch,expired. Success is 200{gate, decision, signalled};signalled: falsemeans the decision is stored but the wake-up signal failed, and the workflow also reads Postgres when its gate timer fires. See Gates and approvals.DELETE /v1/factory/jobs/:idanswers 409conflict("job is closed") forpr_opened,failedorcancelled. Otherwise it sets the Postgres cancel flag first, then cancels the workflow; 202{status: "cancelling"}. A cancel that finds no workflow closes the job directly.
Quality routes
Registered only when QUALITY_ENABLED is 1 or true; the app refuses to build when it is set without a qualityStarter. A guard on /v1/quality/* answers 403 to clients outside QUALITY_CLIENTS. Submit routes require Idempotency-Key (1 to 128 characters), return 202 for a new run and 200 for a replay, 403 for a repo outside FACTORY_REPOS, and 429 budget_exhausted when the client's or the global daily sandbox-second limit is used up, or 429 too_many_pending. Bodies and responses are in Quality REST and limits.
Usage
GET /v1/usage is limited to API_ADMIN_CLIENTS (others get 404). It returns {day, clients[], globalSpentUsd, staleReservations[]} where each client row has client, spentUsd, inputTokens, cacheReadTokens, cacheWriteTokens and cacheHitRate (cacheRead / (input + cacheRead + cacheWrite), null when the denominator is 0). Stale reservations are ledger rows still reserved after STALE_RESERVATION_SEC (default 900, minimum 600). A background check (startStaleCheck) logs one warning every STALE_CHECK_INTERVAL_MS (default 300000) while any exist; it never releases rows.
Shutdown
On SIGTERM or SIGINT the server stops admitting (503 unavailable, Retry-After: 5), aborts in-flight runs with reason shutdown, waits up to SHUTDOWN_GRACE_MS (default 8000), closes the server, the Temporal connection and the pool, and exits 0 if drained, otherwise 1.
API environment
| Variable | Default | Notes |
|---|---|---|
API_KEYS | none | JSON client-to-key map, required |
API_ADMIN_CLIENTS | empty | comma list, each must be in API_KEYS |
MODELS | none | comma list, required, non-empty |
DATABASE_URL | none | required |
GATEWAY_URL, GATEWAY_CONTROL_URL, GATEWAY_CONTROL_TOKEN_API_FILE | none | required; see Gateway |
GATEWAY_MAX_OUTPUT_TOKENS | 8192 | must not exceed the gateway cap |
HOST, PORT | all interfaces (wildcard bind), 3000 | listener |
TRUST_PROXY_HOPS | 0 | 0 to 5 |
MAX_CONCURRENCY | 2 | synchronous runs |
RATE_LIMIT_PER_MIN, AUTH_FAIL_LIMIT_PER_MIN | 30, 10 | |
WORKSPACE_DIR | /workspace | must be a directory at startup |
SSE_PING_MS | 15000 | minimum 1000 |
SHUTDOWN_GRACE_MS | 8000 | |
AGENTS_DISABLED | off | fail closed: any value other than 0 or false disables |
CLIENT_DAILY_LIMIT_USD, GLOBAL_DAILY_LIMIT_USD | 1, 2 | ledger limits |
PER_REQUEST_CAP_USD, BUDGET_FLOOR_USD, SONNET_MIN_RESERVATION_USD, BUDGET_MARGIN | 0.5, 0.02, 0.5, 0.2 | see decorators page |
SESSION_*, TEMPORAL_* | see Sessions and workflows | |
FACTORY_*, QUALITY_* | see Factory overview |
The full configuration reference is on Configuration.
Contradictions between sources
FactoryJobRequest.baseRefinpackages/agent-types/src/factory.tsaccepts a branch name or a 40-hex SHA (BaseRef). The API handler rejects anything but a 40-hex SHA with 400invalid_request, because the API holds no GitHub credential and cannot resolve a branch. The handler (code inapps/api/src/factory.ts) is what runs; the plan text was amended to match (v2.2).- The plan lists the approval route as the place where "four-eyes" (submitter differs from approver) is checked. The code does not check it; see Gates and approvals.
Not verified
The request and response shapes above come from reading the code; no route was called while writing this page.
Sources
apps/api/src/app.ts(buildApp, gate middleware,admit, SSE handler,BODY_LIMIT_BYTES, shutdown)apps/api/src/auth.ts(createAuthenticator)apps/api/src/client-ip.ts(clientIp)apps/api/src/limits.ts(WindowCounter,Semaphore)apps/api/src/errors.ts(sendOutcome,invalidRequest,errorMessage)apps/api/src/sessions.ts(registerSessionRoutes,STALE_RUNNING_MS)apps/api/src/factory.ts(registerFactoryRoutes, artifact route)apps/api/src/quality.ts(guard, submit, survivors)apps/api/src/config.ts(ApiEnv,loadConfig)apps/api/src/serve.ts,apps/api/src/stale.ts,apps/api/src/temporal.ts(callTemporal)packages/agent-types/src/http.ts(routes,HTTP_STATUS,toResponse,WINDOW_MS, schemas,IDEMPOTENCY_HEADER)packages/agent-types/src/factory.ts(FactoryJobRequest,FACTORY_LIMITS,ApprovalRequest)packages/agent-client/src/index.ts(createAgentClient)