Skip to main content

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​

RouteMethodAuthEnabled bySuccessPurpose
/healthGETpublicalways200 {status: "ok"}liveness; skips auth and rate limiting
/v1/modelsGETAPI keyalways200 {models: string[]}the MODELS allowlist
/v1/usageGETAPI key, admin clientalways200 UsageResponsetoday's spend per client, stale ledger reservations; non-admin clients get 404
/v1/agentPOSTAPI keyalways200 AgentHttpResponseone synchronous run, JSON reply
/v1/agent/streamPOSTAPI keyalways200 text/event-streamthe same run as server-sent events
/v1/sessionsPOSTAPI keyalways (503 without Temporal)201 SessionCreatedopen a durable session
/v1/sessions/:id/messagesPOSTAPI keyalways (503 without Temporal)202 MessageAcceptedqueue one turn
/v1/sessions/:idGETAPI keyalways200 SessionViewpoll session and turns (Postgres only)
/v1/sessions/:idDELETEAPI keyalways202 {status: "cancelling"}cancel the session
/v1/factory/jobsPOSTAPI key in FACTORY_CLIENTSFACTORY_ENABLED202 new, 200 replaysubmit a factory job
/v1/factory/jobs/:idGETAPI key in FACTORY_CLIENTS or FACTORY_APPROVERSFACTORY_ENABLED200 FactoryJobViewpoll a job
/v1/factory/jobs/:id/eventsGETas aboveFACTORY_ENABLED200 FactoryEventsjob event log
/v1/factory/jobs/:id/artifacts/:kindGETas aboveFACTORY_ENABLED200 text/plainexact artifact bytes
/v1/factory/jobs/:id/approvalsPOSTAPI key in FACTORY_APPROVERSFACTORY_ENABLED200 ApprovalRecordeddecide a gate
/v1/factory/jobs/:idDELETEas for GETFACTORY_ENABLED202 {status: "cancelling"}cancel a job
/v1/quality/runsPOSTAPI key in QUALITY_CLIENTSQUALITY_ENABLED202 new, 200 replaysubmit a CodeCrucible assessment
/v1/quality/verifyPOSTAPI key in QUALITY_CLIENTSQUALITY_ENABLED202 new, 200 replaysubmit a CodeCrucible verify run
/v1/quality/runs/:idGETAPI key in QUALITY_CLIENTSQUALITY_ENABLED200 QualityRunViewpoll a run
/v1/quality/runs/:id/survivorsGETAPI key in QUALITY_CLIENTSQUALITY_ENABLED200 QualitySurvivorsPagepage 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 /health is public.
  • The per-client counter increments on every authenticated request, including requests that later fail validation.
  • Both counters are in-memory fixed windows (WindowCounter in apps/api/src/limits.ts, window WINDOW_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_KEYS is 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 Authorization header 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 with crypto.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_KEYS is 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 in API_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​

LimitEnv varDefaultEffect
Authenticated requests per client per minuteRATE_LIMIT_PER_MIN30429 rate_limited, Retry-After = seconds to the next window
Failed authentications per IP per minuteAUTH_FAIL_LIMIT_PER_MIN10429 rate_limited before the key is even checked
Concurrent synchronous runs (both /v1/agent routes)MAX_CONCURRENCY2429 busy, Retry-After: 5
Request body sizeconstant BODY_LIMIT_BYTES65536 bytes413 payload_too_large
Open sessions per clientSESSION_MAX_OPEN_PER_CLIENT5409 conflict
Session turnsSESSION_MAX_TURNS50409 conflict
Active factory jobs per clientFACTORY_MAX_ACTIVE_PER_CLIENT2 (max 100)429 rate_limited
Submitted quality runs waiting for admissionQUALITY_MAX_PENDING_PER_CLIENT4 (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"):

CodeHTTPTypical cause
invalid_request400schema mismatch, invalid JSON, model not in MODELS, bad header or id
unsupported_capability400declared; a runtime refusal is mapped to 500 before it reaches HTTP
unauthorized401missing, malformed or unknown API key
forbidden403authenticated client outside the factory or quality list, non-approver on approvals
not_found404unknown path, unknown id, another client's id, admin route for a non-admin, disabled route group
conflict409session state conflicts, idempotency key reuse with another body, approval refused
payload_too_large413body over 64 KiB, factory task over 16 KiB
rate_limited429window limits, active factory job cap
busy429all MAX_CONCURRENCY slots in use
budget_exhausted429ledger refused the reservation, quality daily sandbox-second limit
too_many_pending429pending quality submissions cap
internal_error500unhandled error, runtime invalid_request or unsupported_capability
agent_failed502the runtime failed the turn
agent_limit502max turns or budget reached
disabled503kill switch (AGENTS_DISABLED or the settings flag)
unavailable503shutdown, Temporal unreachable
timeout504run 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 statusCauseResponse
successany200
agent_limit, timeout, agent_failed, disabled, budget_exhausted, internal_erroranysame-named code and status
invalid_request, unsupported_capabilityany500 internal_error (input was already validated, so this is a server fault)
abortedshutdown503 unavailable, Retry-After: 5
abortedclient_closedno reply: the API sends 204 with no body (nobody is listening)
abortednone500 internal_error
unavailableshutdown503, Retry-After: 5
unavailabletemporal_unreachable503, Retry-After: 30
busyany429, Retry-After: 5
rate_limitedwindow429 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):

FieldRule
promptstring, 1 to 20000 characters
modelstring, 1 to 200 characters; must be listed in MODELS or the answer is 400
maxTurnsoptional integer 1 to 10
timeoutMsoptional integer 1000 to 300000
maxBudgetUsdoptional 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:

ResourcePoll routeTerminal states
SessionGET /v1/sessions/:id (Postgres only, works without Temporal)session closed, cancelled, failed; turn completed, failed, aborted
Factory jobGET /v1/factory/jobs/:idpr_opened, failed, cancelled
Quality runGET /v1/quality/runs/:idsee Quality status and limits

Sessions​

RouteRequestResponses
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/:idnone200 SessionView; 404
DELETE /v1/sessions/:idnone202 {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):

FieldRule
repocatesworks/<name>, must be listed in FACTORY_REPOS
baseRefmust be a 40-hex commit SHA at the API (see the contradiction note below)
taskstring, 1 to 16384 characters; over 16 KiB by byte length answers 413
budgetUsdgreater than 0, at most 2, at most FACTORY_MAX_JOB_USD (default 0.5)
maxIterationsinteger 1 to 5, default 3
policyoptional {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.

OutcomeResponse
new job, workflow started202 {jobId, status: "queued"}
replay with the same key and body, job past queued200 {jobId, status} without a new start
replay of a job still queuedstart is re-issued (REJECT_DUPLICATE, already-started counts as success), 200
Temporal unreachablejob 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/:id returns FactoryJobView {id, status, repo, baseSha, errorCode, steps[], costUsd, pendingGate?, pr?, degradedContext}. Stored factory error codes that are also ErrorCode values pass through Table S; job outcome codes such as max_iterations pass unchanged.
  • GET /v1/factory/jobs/:id/events returns {events: [{kind, detail, at}]}.
  • GET /v1/factory/jobs/:id/artifacts/:kind takes kind in plan, patch, test-log, review and optional ?i= (a single digit 0 to 5). It answers text/plain; charset=utf-8 with headers x-artifact-id, x-artifact-sha256 (digest of the stored bytes) and x-artifact-redacted (true when 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/approvals takes {gate, digest, decision}. A non-approver gets 403 and no signal is sent. A refusal is 409 conflict with the message approval refused: <reason>, reason one of not_awaiting, no_pending_gate, digest_mismatch, expired. Success is 200 {gate, decision, signalled}; signalled: false means 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/:id answers 409 conflict ("job is closed") for pr_opened, failed or cancelled. 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​

VariableDefaultNotes
API_KEYSnoneJSON client-to-key map, required
API_ADMIN_CLIENTSemptycomma list, each must be in API_KEYS
MODELSnonecomma list, required, non-empty
DATABASE_URLnonerequired
GATEWAY_URL, GATEWAY_CONTROL_URL, GATEWAY_CONTROL_TOKEN_API_FILEnonerequired; see Gateway
GATEWAY_MAX_OUTPUT_TOKENS8192must not exceed the gateway cap
HOST, PORTall interfaces (wildcard bind), 3000listener
TRUST_PROXY_HOPS00 to 5
MAX_CONCURRENCY2synchronous runs
RATE_LIMIT_PER_MIN, AUTH_FAIL_LIMIT_PER_MIN30, 10
WORKSPACE_DIR/workspacemust be a directory at startup
SSE_PING_MS15000minimum 1000
SHUTDOWN_GRACE_MS8000
AGENTS_DISABLEDofffail closed: any value other than 0 or false disables
CLIENT_DAILY_LIMIT_USD, GLOBAL_DAILY_LIMIT_USD1, 2ledger limits
PER_REQUEST_CAP_USD, BUDGET_FLOOR_USD, SONNET_MIN_RESERVATION_USD, BUDGET_MARGIN0.5, 0.02, 0.5, 0.2see decorators page
SESSION_*, TEMPORAL_*see Sessions and workflows
FACTORY_*, QUALITY_*see Factory overview

The full configuration reference is on Configuration.

Contradictions between sources​

  • FactoryJobRequest.baseRef in packages/agent-types/src/factory.ts accepts a branch name or a 40-hex SHA (BaseRef). The API handler rejects anything but a 40-hex SHA with 400 invalid_request, because the API holds no GitHub credential and cannot resolve a branch. The handler (code in apps/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)