API route conventions — Kindgi platform
Source in the repository.
Status: normative — every /v1/* route follows these conventions.
Related: ADDING-A-ROUTE.md (authoring checklist), packages/api/openapi.json (generated from the route registry; exported as @kindgi/api/openapi.json).
This document fixes the on-wire conventions — URL shapes, authentication, request and response envelopes, pagination, streaming, signed exports, and error propagation — so the API, the generated OpenAPI document, and client SDKs agree. The OpenAPI document is their executable form; drift tests keep routes, the OpenAPI registry, and the TypeScript client in sync.
1. URL structure
Section titled “1. URL structure”1.1 Base + versioning
Section titled “1.1 Base + versioning”- Base path:
/v1/. All routes are versioned. Breaking changes ship at/v2/— never mutate/v1/shapes. - No trailing slash on canonical URLs (e.g.
/v1/runs, not/v1/runs/). Requests with trailing slash 301-redirect to the canonical form. - Version bump policy: additive changes stay in
/v1/. Renames, removed fields, or changed semantics require/v2/.
1.2 Resource layout
Section titled “1.2 Resource layout”Resources are plural, kebab-case, singular resource ID at the tail:
- Collection:
POST /v1/runs,GET /v1/runs,GET /v1/runs/:runId,DELETE /v1/runs/:runId. - Sub-collection:
GET /v1/runs/:runId/journal,POST /v1/runs/:runId/cancel. - Cross-cutting stream:
GET /v1/runs/:runId/stream(SSE).
Verb suffixes are used sparingly for non-CRUD actions where a resource-shaped route would be misleading (e.g. cancel, resume, dry-run). Prefer plain CRUD when possible.
1.2.1 Removing catalog resources
Section titled “1.2.1 Removing catalog resources”Catalog resources (agents, flows, tools, guardrails, policies, schedules, triggers, webhook endpoints, …) are not hard-deleted. They are removed with POST /v1/<resource>/:id/unregister:
- the row is kept, marked unregistered, and hidden from every read (a later
GETanswers 404); - the response is
{ <idField>: string, unregistered: boolean }, whereunregisteredisfalsewhen the resource was unknown or already unregistered, so the call is idempotent; - the runtime removes unregistered rows later, under its retention policy.
1.3 Path parameter naming
Section titled “1.3 Path parameter naming”:runId,:agentId,:flowId,:approvalId,:conversationId. Camel-case withIdsuffix. Matches TypeScript type names one-to-one.- Always the branded id type on the wire (opaque strings; UUIDs today but the SDK / server never assume format).
2. Authentication
Section titled “2. Authentication”2.1 Bearer token
Section titled “2.1 Bearer token”Every non-public request carries:
Authorization: Bearer <api-token>API keys are minted server-side (POST /v1/tokens, tenant admins only) and return a plain string, once. A key is a service account in its tenant (service_account:<tokenId>) and carries:
- Its tenant.
- A role:
admin(administers the tenant, manages keys) ormember. - Explicit capabilities (
env:write,secrets:write, …): a caller can only grant capabilities it holds. - An optional project scope and expiration.
GET /v1/tokens lists keys and GET /v1/tokens/{tokenId} reads one; neither returns a secret. POST /v1/tokens/{tokenId}/revoke takes effect on the next request.
The SDK's AuthConfig (sdks/typescript/src/auth.ts) already emits this header via its apiToken mode. No SDK change needed.
2.2 Public routes
Section titled “2.2 Public routes”The only fully-public routes are:
GET /health— liveness. No auth. Returns{ ok: true }.GET /v1/openapi.json— the OpenAPI document.- Inbound webhook receivers, when a deployment turns them on — authenticated by an HMAC signature header, not a Bearer token. There's no receiver route yet:
/v1/webhooksonly manages the webhook triggers. POST /v1/wait-tokens/:token/complete— another system's answer to a run's wait, at the link a pausing tool handed on. The token in the path is the credential: no Bearer token, and an unknown token and a wrong one both answer404 wait-token-not-found. The route logs the path as/v1/wait-tokens/:token, never the token. On a server that pauses no run, every token answers that 404.
2.3 Tenant scoping
Section titled “2.3 Tenant scoping”The server derives tenantId from the token; callers never pass it explicitly on requests. Every DB read/write inside a route handler flows through withTenantConnection(client, tenantId, ...).
2.4 Failure modes
Section titled “2.4 Failure modes”- Missing/malformed
Authorization→401 unauthorizedwith errorcode: 'auth-missing'. - Expired or revoked token →
401 unauthorizedwith errorcode: 'auth-expired'or'auth-revoked'. - Valid token, resource is out of scope for its tenant →
404 not-found, never403 forbidden(avoid leaking resource existence across tenants).
3. Request body shape
Section titled “3. Request body shape”- All bodies are JSON.
Content-Type: application/json; charset=utf-8is required on POST/PUT/PATCH. - Empty body accepted where semantically appropriate (
POST /v1/runs/:runId/canceltakes no body). - Field names are camelCase, matching the SDK's TypeScript types verbatim. No wire-format renames.
- Unknown top-level fields →
400 bad-requestwith errorcode: 'unknown-field'. Strict validation on the request; permissive on the response (for forward compatibility).
3.1 Idempotency
Section titled “3.1 Idempotency”Any mutating request may include:
Idempotency-Key: <caller-supplied-uuid>Semantics:
- Server stores
(tenantId, route, key) → responsefor 24h, for a response that took effect (a status below 400). A refusal (4xx) or a failure (5xx) isn't stored, so a retry after fixing the cause runs again. - Retries with the same key return the stored response byte-identical (including status code), marked
X-Idempotent-Replay: true. - Retries with the same key but a different body →
409 conflictwith errorcode: 'idempotency-key-body-mismatch'. - A retry sent while the first request still runs →
409 conflictwith errorcode: 'idempotency-key-in-flight'andRetry-After, when the store holds keys (IdempotencyStore.holds; the runtime's does from 0.1.5). It doesn't run the operation again; retry after it, and you get the first request's answer. The hold lasts 30 s and is renewed while the request runs, so a crashed request's key frees within 30 s. - A store that can't be read before the request runs (its stored answer or its hold) →
503with errorcode: 'idempotency-store-unavailable'andRetry-After(5 seconds), from 0.3.0. Nothing ran, so a retry with the same key is safe. - A store that can't keep the answer after the request ran: the request's own answer stands, though it can't be replayed, and the failure is logged. Its hold isn't released, so a retry within the hold's 30 s gets
idempotency-key-in-flight, as for a crashed request, and one after that runs again. - Applies to
POST,PUT,PATCH,DELETE.
@kindgi/client sends the Idempotency-Key header on mutating calls when the caller passes idempotencyKey.
4. Response shape
Section titled “4. Response shape”4.1 Success
Section titled “4.1 Success”2xx status codes carry the resource / operation result as the JSON body directly. No wrapper envelope for success.
{ "id": "run-abc123", "status": "running", "flowId": "agent.turn", "flowVersion": "1.0.0", "startedAt": "2026-09-18T12:34:56.789Z"}4.2 Error
Section titled “4.2 Error”4xx and 5xx responses carry a discriminated error envelope:
{ "error": { "code": "unresolved-tool", "message": "Tool \"acme.citation-lookup\" is not registered for agent \"acme.drafting\"", "details": { "toolId": "acme.citation-lookup" }, "requestId": "req-01H8XYZ..." }}codeis a stable machine-readable discriminant. Values match existing domain error codes (unresolved-tool,guardrail-violation,hitl-required,agent-turn-aborted, etc.). New codes only add.messageis human-readable, not part of the API contract.detailsis optional, kind-specific.requestIdis server-assigned; always present.
The SDK's fromWire(json) (sdks/typescript/src/errors.ts) matches on code.
4.3 Status code mapping
Section titled “4.3 Status code mapping”Domain error code |
HTTP status |
|---|---|
not-found, run-not-found, agent-not-found |
404 |
already-terminal, run-already-terminal |
409 |
idempotency-key-body-mismatch |
409 |
idempotency-key-in-flight |
409 |
duplicate-* |
409 |
slug-conflict, project-default-already-exists |
409 |
validation-failed, unknown-field, bad-input |
400 |
unresolved-tool, unresolved-guardrail |
400 |
hitl-required |
409 |
guardrail-violation |
422 |
agent-turn-aborted, budget-exceeded |
422 |
flow-unbound, flow-runs-not-supported, flow-resume-not-supported |
422 |
auth-missing, auth-expired, auth-revoked |
401 |
permission-denied |
403 |
rate-limit-exceeded |
429 |
database-busy (before the handler, or a GET or HEAD) |
503 |
idempotency-store-unavailable (a keyed write, before it runs) |
503 |
authz-backend-unavailable (before the handler, or a GET or HEAD) |
503 |
| Anything else server-caused | 500 |
A 429 rate-limit-exceeded carries Retry-After, in whole seconds, when the limit is over a time window, as schema-compile-time, template-render-time and the request rate limits are; a limit that counts what's waiting, not time, carries none. When a tenant's limit refused the request, details.limit names it. schema-compile-time is the time the tenant's schemas spent compiling in the last 60 seconds, against details.budgetMs. It counts every compile in a request that publishes schemas, and a schema compiled again in any other request. A publish it refuses stores nothing. template-render-time is the time the tenant's instructions templates spent rendering in the last 60 seconds, against details.budgetMs. An agent turn whose work either budget refuses fails with rate-limit-exceeded and the same details: POST /v1/runs answers it as this 429, with Retry-After and details.runId, and the run reads as failed with that code.
A 503 database-busy answers a GET or HEAD that the database was too busy to answer in time: a lock or statement timeout ended its query, or no pooled connection came free within the wait. It carries Retry-After (5 seconds). A request with any other method that the database was too busy for answers a 500 (internal-server-error, or the code of the binding error that stopped it, such as persistence-error): a write can have saved part of its work before the timeout, and clients retry a 503 as an answer that nothing ran. Before the handler runs, nothing has, so a read there answers the 503 on any method (beforeHandlerAnswer, middleware/error-mapper.ts): the read a check in the authorize middleware makes (the runtime reads the tenant's store id from the database before it asks the store), the read in its resource getter, and the read a route's middleware makes to find what it checks, such as a run's project or the projects an item is served in. A handler that runs the middleware itself (deniedBy) gets the same answer, before its first write. Any other read in a middleware keeps the 500 on a write, such as the expert queue's read, after its check, of whether the project exists. A keyed write whose Idempotency-Key store couldn't be read before it ran is the same: nothing ran, so it answers 503 idempotency-store-unavailable (§3.1).
The storage failure is marked code: 'database-busy', on the error or down its cause chain. A thrown error reaches mapThrownError, which checks for the mark. A route that answers a binding's Result error at its code's status asks databaseBusyAnswer(error, c) (middleware/error-mapper.ts) first and returns its answer when it gives one. A binding that re-codes a storage failure under its own code keeps the failure as the error's cause, so the read answers the same whether the binding threw the failure or returned it.
A 503 authz-backend-unavailable answers a request whose authorization check couldn't reach the store that holds permissions: no answer (or no credential to call it with), a 5xx other than 501, or a 429, after the runtime's own retry. It carries Retry-After (5 seconds) and a fixed message; the store's error is logged at error, never in the body. The runtime's binding marks the failure code: 'authz-backend-unavailable', on the error or down its cause chain (AuthzCheckBinding's contract, @kindgi/authz). A check in the authorize middleware runs before the handler, so nothing ran, and it answers the 503 on any method (authzUnavailableAnswer, middleware/error-mapper.ts). A check inside a handler (can, check, filterByCan and the rest) throws the mark on to mapThrownError, which answers the 503 on a GET or HEAD and the 500 on any other method: the handler may have written before its check. A handler that runs the middleware itself (deniedBy, routes/denied.ts, and a route's own denied) gets its answer, the 503 on any method, so it runs it before its first write. One that has to ask after a write, as a promotion that pins what it moved does (the pin checks in item-rights.ts), throws on any answer but a 403, so it answers the 500. A route that reads that answer as yes or no takes only a 403 as a no (refuses) and returns any other answer as is: a 404 or a 403 of the route's own in its place would tell a client that retries a 503 not to. The authorizer's 403, this 503 and the 503 database-busy of a check's read carry their status and Retry-After on the answer, not on the request, so a handler that goes on past a refusal, as one for an Improve schedule its project's admin stops, answers with its own. Any other failure of a check is a 500, as any thrown error. GET /v1/identity/me/permissions answers its own 503 authz-backend-unavailable for any failure to read the caller's access, with the same Retry-After.
The OpenAPI document declares this 503 on every served GET and HEAD, injected once where the spec is built (openapi/generate.ts), so a new read is covered without a per-route edit. The exceptions are the reads that never reach storage, and so can never answer database-busy: they're listed in READS_WITHOUT_STORAGE (openapi/operations.ts) — the liveness probe and the spec document today — and a new read of that kind goes there too. A read that declares its own 503 keeps it in place of the shared one, so its description has to name database-busy as well, the way GET /v1/identity/me/permissions names both authz-backend-unavailable and database-busy.
A write that takes an Idempotency-Key (§3.1) gets the same treatment for its 503 idempotency-store-unavailable: the generator injects it on every served POST, PUT, PATCH or DELETE that declares the Idempotency-Key header (takesIdempotencyKey), and one that declares its own 503 names idempotency-store-unavailable in it as well.
Every operation that declares a 401 can answer 503 authz-backend-unavailable (answersAuthzUnavailable): the spec can't tell which handlers check, and any authenticated request can be checked when the runtime runs with an authorization store. So for these the generator's shared 503 names it beside database-busy or idempotency-store-unavailable, an operation with neither gets a shared 503 of its own for it, and one that declares its own 503 names authz-backend-unavailable in it as well. The check's own read can answer 503 database-busy before the handler in the same way, so each of these 503s names database-busy too, an operation's own included. An operation that declares no 401, such as GET /v1/auth/sign-in-options, keeps the shared 503 without it.
Two more answers come from middleware on a runtime serving many workspaces, so the generator declares them from the middleware's own rules. Any request of a workspace's key or session can answer 429 rate-limit-exceeded with details.limit: "api-requests" when the workspace's requests a minute are spent (answersRequestLimit): an operation with no 429 of its own gets a shared one (with no body on a HEAD, as the shared 503s have none there), and one that declares its own names it there too. A write the frozen-workspace gate checks can answer 503 tenant-state-unavailable when the workspace's state can't be read (answersTenantStateUnavailable, which reads the gate's own list in middleware/tenant-state-rules.ts): the shared 503 names it, and an operation's own 503 names it as well. And a keyed write's 409 names idempotency-key-in-flight, which idempotencyMiddleware answers while the same key's first request still runs; the generator adds it to the write's own 409, or declares one.
An answer that sends Retry-After, or whose codes include one that does, is marked retryAfter (RetryAfterResponse in openapi/operations.ts; the generator's shared answers are marked where they're declared). The document then gives it the Retry-After header (components.headers.RetryAfter: whole seconds, at least 1), and its text names the codes that send it. Every 429 and 503 is marked, except one whose codes never send Retry-After; tests/openapi.test.ts lists those with why (503 connection-notice-unavailable: the app may send the notice again, and there's no wait to give it).
5. Pagination
Section titled “5. Pagination”Every list endpoint accepts:
?limit=<int>— 1..100, default 25.?cursor=<opaque-string>— server-issued from a prior response.
Response body:
{ "data": [ … ], "nextCursor": "cursor-abc123", "hasMore": true}nextCursoris absent whenhasMore: false.- Cursors are opaque — SDKs treat them as strings. Server encodes whatever it needs (page number, last-id, whatever).
- A runtime with a cursor sealer (
cursorSealer) seals everynextCursorat the edge (AES-256-GCM,k1.<kid>.<nonce>.<body>): it shows nothing of the row it points after, even one the list hid. A sealed cursor opens only for the same tenant, caller, list (the path) and filters (the query parameters other thancursorandlimit, so the page size may change mid-scan), within a day; otherwise400 bad-input, and the client starts again without it. A plain cursor still passes as it is. - A page may be empty while
hasMoreis true (every row of a window was one the caller can't read): continue withnextCursor. - Filters go as query params:
?status=running&agentId=.... - A list of extras is
include: an array of known values, sent as one comma-separated key (include=output,waitingFor; in the spec,style: formandexplode: false). The server reads repeated keys too. An unknown value is400 bad-input, with a message that startsUnknown `include` value(s). - Sort order is fixed per endpoint (documented per route); no
?sort=unless explicitly supported.
Matches the SDK's Filter<TStatus> + Cursor types verbatim.
6. Streaming (SSE)
Section titled “6. Streaming (SSE)”GET /v1/runs/:runId/stream returns Server-Sent Events. Each event is one RunEvent (the union defined by @kindgi/specs/run-event.schema.json).
6.1 Event format
Section titled “6.1 Event format”id: <eventId>event: run.step-completeddata: {"eventId":"...","runId":"...","tenantId":"...","kind":"run.step-completed",...}idline: monotonic per run, used asLast-Event-Idon reconnect.eventline: theRunEvent.kindvalue.dataline: the full serializedRunEventJSON. Callers using EventSource-compatible parsers can ignore theeventline and switch ondata.kind.
6.2 Reconnection
Section titled “6.2 Reconnection”The SDK's readSse<T>() sends Last-Event-Id: <lastSeenEventId> on reconnect. Server resumes from that id + 1 exclusive; missed events are replayed from the journal.
6.3 Termination
Section titled “6.3 Termination”Server closes the SSE connection cleanly after emitting run.completed / run.failed / run.cancelled (whichever is the terminal event for that run). Callers observe end-of-stream normally.
7. Verb → Kernel mapping
Section titled “7. Verb → Kernel mapping”For the runs resource specifically (the largest surface):
| Verb + path | Kernel op | Notes |
|---|---|---|
POST /v1/runs |
runGraph(...) |
Body: { agent | flow, input, options?: { dryRun?: boolean, wait?: boolean } }. Returns the run row with its output: 201 once the run completes, fails or suspends, or with it still running when a read failed part-way; 202 right away with wait: false. |
GET /v1/runs/:runId |
Load row from kernel_runs |
Returns the run row, with output once completed and parentRunId / parentNodeId on a child run. |
GET /v1/runs |
List with pagination | Filters: parentRunId (a run's children), topLevel=true. include=output adds each run's output; include=waitingFor adds what each suspended run waits for, as GET /v1/runs/:runId gives it, and holds a page to 25 runs (either or both, comma-separated). |
POST /v1/runs/:runId/cancel |
cancelRun(...) |
Empty body. Returns updated RunResult. |
POST /v1/runs/:runId/resume |
The wait token binding's complete(...), then the host's resumeRun(...) |
Body: { waitpointId, value? }. Answers a pause: waitpoint (a run paused until another system answers), with write access and execute on the run's agent or flow; value is the tool's output. Every other id (child: and approvals' among them) is 422 run-resume-not-supported. Returns the run as GET /v1/runs/:runId does. |
GET /v1/runs/:runId/journal |
readJournal(...) |
Paginated: ?since=<sequence>, or ?limit=<int> and ?cursor= (the page before's nextCursor). |
GET /v1/runs/:runId/stream |
SSE from journal + in-process bus | See §6. |
The other resources (agents, flows, tools, guardrails, approvals, etc.) follow the same shape — CRUD verbs map to package-level functions; non-CRUD actions map to specific ops.
8. Error propagation across the boundary
Section titled “8. Error propagation across the boundary”Kernel / package-level Result<T, E> errors are translated at the route layer:
- Success
ok→ serializeTas JSON body with 2xx status. - Failure
err→ look up the errorcodein the mapping table (§4.3), serialize as{ error: {...} }with the mapped HTTP status.
Every err.code known to packages/* must have a status mapping. New error codes require adding a row to §4.3 (in this doc) + the route layer's mapping table.
Domain errors are the ONLY response body shape for 4xx/5xx. Framework crashes (thrown exceptions, uncaught DB errors) get caught by a top-level middleware that produces { error: { code: 'internal-server-error', message: '...', requestId: '...' } } with 500.
9. Non-goals
Section titled “9. Non-goals”- GraphQL / gRPC / other transports. REST + SSE only.
- Batching endpoints. No
POST /v1/runs/batch— clients send N requests.
10. Signed bundle canonicalization
Section titled “10. Signed bundle canonicalization”Signed export routes (POST /v1/provenance/:runId/export, POST /v1/approvals/:approvalId/audit-bundle, any future signed export) MUST return the same wire envelope so SDK clients can share a single verification helper:
{ "<resourceId>": "...", // e.g. "runId" or "approvalId" "bundle": "base64-of-canonical-json", "bundleSchemaVersion": <version>, // semver string OR integer; kind-specific "algorithm": "ed25519", "signingKeyId": "...", "signature": "base64-signature-bytes", "publicKey": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n", "canonicalization": "sorted-key-json", "exportedAt": "2026-09-19T12:34:56.789Z"}Canonicalization algorithm (canonicalization: "sorted-key-json") is provided by canonicalize from @kindgi/schema: JSON with object keys sorted lexicographically at every level, no whitespace, UTF-8 bytes. Arrays preserve declaration order. This algorithm is stable across resources — provenance and audit bundles share it verbatim so verification code is identical.
Verifier flow (client-side, no server round trip):
- Base64-decode
bundle→ canonical bytes. - Base64-decode
signature→ 64 signature bytes. parsePublicKeyPem(publicKey)from@kindgi/crypto.verifyEd25519(publicKey, bundleBytes, signatureBytes).- If needed,
JSON.parse(bundleBytes.toString('utf8'))for structured inspection — the canonical form is regular JSON.
Deployments without a signingKey binding mounted return 404 signing-not-configured on every signed-export route; unknown signingKeyId returns 404 signing-key-not-found. Both error codes are shared across resources.
Response envelope shape is guardrail across resources; the bundle body schema is per-resource (see ExportProvenanceResult / ExportAuditBundleResult in the OpenAPI document). New signed exports MUST reuse this envelope.