docs · reference
Control API#
Unreleased: after 0.11.0. The Control API is part of
hekma serve, the Service Host, which is on Hekma's main branch and ships in the next release; Hekma 0.11.0 does not have it.
Every hekma serve serves a small HTTP and JSON API for the agents it supervises: register and remove agents; start, stop, pause, resume and drain them; send them input; read and set config, memory and restart policy; read the fleet; list, open and close Runs, change their labels and limits, and act on a Selector's set of them; manage Policies; and receive events live or from a durable journal. The hekma agent commands use it themselves: every write is one call to it. Every route needs a bearer token, and it is version v0, marked unstable, so fields and messages can still change.
Where it listens#
The API is always on, in two places:
- The local endpoint. Every host binds
127.0.0.1on a port the OS picks, with a fresh token, and records both incontrol.jsonin the state directory. This is how the CLI reaches the host. The local endpoint has the file's fields and rules. - The operator listener, if you ask for one. Pass both
--listenand--bearer-secrettohekma serve(orhekma-host):
export CONTROL_BEARER="use-a-long-random-value"
hekma serve --listen 127.0.0.1:8477 --bearer-secret CONTROL_BEARER[hekma] host started; state root /Users/you/Library/Application Support/ktesio — supervising agents until SIGTERM/SIGINT
[hekma] local control endpoint on 127.0.0.1:49402 (loopback, for the hekma CLI; recorded in /Users/you/Library/Application Support/ktesio/control.json)
[hekma] control api listening on 127.0.0.1:8477 (v0, unstable — bearer required; http)--listentakes an address and port. With port0, the OS picks a port and thecontrol api listeningline shows it.--bearer-secrettakes the name of a secret, not the token itself. Hekma reads the environment variable with that name first, then the same key in the state directory'ssecrets.toml, like any secret.
One flag without the other is a usage error (exit code 2). A name that resolves to nothing, or to an empty value, stops the host before it binds anything:
✗ the host could not start: the control API's bearer secret could not be resolved: secret 'CONTROL_BEARER' could not be resolved (tried: environment, secrets file); set the environment variable CONTROL_BEARER, or add CONTROL_BEARER to the engine secrets file (mode 0600)An address other than loopback, such as 0.0.0.0:8477, requires --tls-cert and --tls-key; without them the host refuses to start with exit code 2, and with them the listener answers HTTPS only, and its startup line ends in https. TLS beyond loopback has the rules, and Run Hekma as a service a container setup.
Authentication#
Every route on both listeners, /v0/version included, needs Authorization: Bearer <token>. Credentials go through one credential resolver: it holds the SHA-256 hash of each credential with its class, hashes the presented value and compares it in constant time against every entry, then checks the class against the authority matrix for the route's family. Two credentials form the operator/Host bearer class — the local endpoint's token from control.json, and the --bearer-secret value — and both work on both listeners, on every route but POST /v0/runs/refresh, which takes a refresh credential. Run Keys and refresh credentials are issued by the engine and resolved by their hash; a credential whose class a route does not allow answers a typed 403 forbidden. Announce and Node credentials arrive later.
A missing or wrong credential — several Authorization fields, a scheme other than Bearer, or an empty value — answers 401 unauthorized with a WWW-Authenticate: Bearer header and a static refusal body that never echoes the presented token, before any handler runs; a revoked one answers 401 credential-revoked:
curl -s http://127.0.0.1:8477/v0/version{"schema_version":1,"error":{"kind":"unauthorized","message":"missing or invalid bearer token"}}Unrecognised presentations are counted, never logged: the host writes at most one diagnostic line a minute with the counts by class prefix, and no value. An engine-issued credential is recognised from an in-memory index or one read-only database lookup before anything is locked or written, so a flood of made-up tokens costs reads only and never delays the engine's own writes. If that lookup itself fails, the request answers 500 with code store and a fixed message; the cause goes to the host's diagnostics, never to the client. The same is true one layer in: a store failure under an authenticated Run Key's or refresh credential's request answers the same fixed store 500 — the store's text is the Operator's — while the operator bearer's own requests keep the surfaced reason.
A credential in a path or query is refused before authentication; see Never in a URL. Secret config values are masked in every response, as they are in the CLI; the API has no way to reveal them.
Anyone with an operator token can make the host run programs: registering an agent from a manifest path and starting it launches whatever that manifest names. Treat either operator token like a login to the machine.
Routes#
All paths start with /v0. {name} is an agent's name and {id} a run id.
| Method | Path | What it does | Success |
|---|---|---|---|
| GET | /v0/version | Describe the API, the host version and the engine's document versions. | 200 |
| GET | /v0/fleet | The whole fleet: the list --json document. | 200 |
| POST | /v0/instances | Register an agent. Body: {"name": ..., "kind": ...} or {"name": ..., "manifest": "/absolute/path"}, never both. | 201, with Location and the new agent |
| GET | /v0/instances/{name} | One agent: the show --json document. | 200 |
| DELETE | /v0/instances/{name}?disposition=...&force=... | Remove an agent. disposition is retain (the default: the Agent Home stays on disk) or delete. A running agent is a 409 unless force=true, which first stops it with the 30-second stop window, so the request can take that long. | 204 |
| GET | /v0/instances/{name}/status | State, restart policy, restart count and failure cause. | 200 |
| GET | /v0/instances/{name}/capabilities | The agent's capability declaration for this OS. | 200 |
| GET | /v0/instances/{name}/config | The resolved config, secrets masked: the config get --json document. | 200 |
| PUT | /v0/instances/{name}/config | Set one key. Body: {"key": ..., "value": ...}. Returns the key as written, plus any warnings. | 200 |
| POST | /v0/instances/{name}/start | Start the agent. Optional body {"detach": true} also unties the agent from the host's lifetime, like start --detach; it is refused for an engine-observed agent. A body, when sent, must be a JSON object: a bare array such as [true] is a 400. | 200, with the agent |
| POST | /v0/instances/{name}/stop | Stop it. Optional body {"window_secs": N}, 1 to 86400; without a body, the 30-second default. A body must be a JSON object ([30] is a 400). | 200, with the agent |
| POST | /v0/instances/{name}/pause | Pause it. | 200, with the agent |
| POST | /v0/instances/{name}/resume | Resume it. | 200, with the agent |
| POST | /v0/instances/{name}/drain | Drain it: run its pause command, wait for it to go idle, then stop it. Optional body {"timeout_ms": N}, 1 to 600000; without a body, the manifest's bound, else the engine's default. A body must be a JSON object ([1500] is a 400). | 200, with the agent, completed and waited_ms |
| POST | /v0/instances/{name}/send | Send {"text": "..."} to the running agent's input. The host holds the input of every agent it started, so this reaches an agent another client started. | 204 |
| PUT | /v0/instances/{name}/memory | Attach a memory backing: {"kind": "filesystem"} or {"kind": "native"}, while the agent is registered, stopped or failed. | 200, with the folder, kind and guarantee |
| DELETE | /v0/instances/{name}/memory | Detach it. The folder stays on disk. | 204 |
| PUT | /v0/instances/{name}/restart-policy | Set the restart policy: {"policy": "never"} or {"policy": "on-failure"}. | 200, with the status |
| GET | /v0/instances/{name}/events | One agent's committed events after a cursor. See events. | 200 |
| GET | /v0/events | Live events for all agents, as server-sent events. | 200, stays open |
| GET | /v0/export | A batch from the global event journal. See export. | 200 |
| POST | /v0/export/ack | Mark the journal consumed up to a position. Body: {"seq": N}. | 200 |
| POST | /v0/runs | Open a child Run. See Runs. | 201, with Location and the Run |
| POST | /v0/runs/refresh | Trade a refresh credential — the only credential the route accepts — for a new Run Key and refresh credential, once. See Run Keys. | 200, with the new pair |
| POST | /v0/runs/{id}/revoke-keys | Revoke a Run's credentials and, by default, every credential issued under them. Body: {"cascade": false} keeps it to the Run's own. See Run Keys. | 200, with the revoked list |
| GET | /v0/runs/{id}/keys | A Run's credentials — token id, class, state, launch generation, times; never a value. See Run Keys. | 200 |
| GET | /v0/runs | The Run listing, as hekma ps --json: ?selector=&view=exceptions|all&limit=&cursor=. See the Run listing. | 200 |
| GET | /v0/runs/{id} | One Run: its state, labels, limits, usage over its subtree and open children. | 200 |
| POST | /v0/runs/{id}/close | Close a child Run. Closing it again changes nothing. | 200, with the Run |
| GET | /v0/runs/{id}/labels | A Run's labels, each with its source. | 200 |
| PATCH | /v0/runs/{id}/labels | Bind and unbind labels. See bound labels. | 200, with the labels before and after |
| POST | /v0/runs/{id}/stop, /pause, /resume, /drain | A lifecycle verb on one Run: the agent's own verb on the Run that owns its process (stop takes {"window_secs"}, drain {"timeout_ms"}, as on the instance routes). Any other Run is a 409 naming its depth. | 200, with {"schema_version", "run_id", "instance"}; drain adds completed and waited_ms |
| GET | /v0/runs/{id}/limits | One Run's budget read: the limits set on it, the resolved limits with their sources, usage, headroom and latches. | 200 |
| PATCH | /v0/runs/{id}/limits | Set or clear limits on one Run: {"tokens_per_run"?, "tokens_cumulative"?, "dollars_per_run"?, "dollars_cumulative"?, "breach_action"?, "clear": [...], "dry_run": bool}. See limits on a Run. | 200, with the outcome |
| POST | /v0/runs/select | Resolve a Selector into a set to act on: {"selector": "team=core"}. See Selector sets. | 200, with {"schema_version", "token", "runs", "matched", "expires_at"} |
| POST | /v0/runs/stop, /pause, /resume, /drain, /close | Act on a selected set: {"set_token": ...}, plus window_secs on stop and timeout_ms on drain. | 200, with one result per Run |
| PATCH | /v0/runs/labels | Bind and unbind labels on a selected set: {"set_token", "set", "remove"}. | 200, with one result per Run |
| POST | /v0/runs/limits | Set or clear limits on a selected set: {"set_token", ...the limit fields}. | 200, with one result per Run |
| GET | /v0/policies | Every Policy, default included, ordered by name. | 200 |
| GET | /v0/policies/{name} | One Policy: its Selector, limits and, on default, its model-keyed Rate table. | 200 |
| POST | /v0/policies | Create a Policy: {"name", "selector", "tokens_per_run"?, "tokens_cumulative"?, "dollars_per_run_micros"?, "dollars_cumulative_micros"?, "breach_action"?, "rate"?}. The answer carries the matched and fallback counts. | 201, with Location: /v0/policies/{name} |
| PATCH | /v0/policies/{name} | Change a Policy: {"selector"?, "set": {limits}, "clear": [...], "rates": {"set": {model: rate}, "remove": [models]}, "dry_run": bool}. | 200, with the Policy after (or as planned) |
| DELETE | /v0/policies/{name} | Delete a Policy. Its matched Runs re-resolve under what remains; default is refused. | 204 |
Starting an agent and reading it back:
curl -s -X POST -H "Authorization: Bearer $CONTROL_BEARER" \
http://127.0.0.1:8477/v0/instances/worker/start{"schema_version":2,"instance":{"name":"worker","kind":"ticker","state":"running","restart_count":0,"restart_policy":"on-failure","budget":{"cumulative_limit":6000,"cumulative_remaining":4800,"breach_action":"pause"},"usage":{"cumulative_input_tokens":1000,"cumulative_output_tokens":200,"current_run_input_tokens":1000,"current_run_output_tokens":200,"cumulative_cached_tokens":0,"current_run_cached_tokens":0},"metering_source":"self-reported","supervision":"session","agent_home":"/Users/you/Library/Application Support/ktesio/agents/worker"}}Each lifecycle route answers with the agent as it is after the action, so you see what happened without a second request. An agent started through the API, or by a hekma agent start command, belongs to the host and is supervised until it stops or the host shuts down. Budgets are ordinary config keys, so you set them with PUT .../config and read their state in the fleet documents; when this agent crossed its 6000-token budget, the host paused it at once, and the next read showed "state":"paused".
Runs#
Every started agent owns a Run. A Host opens child Runs under it for units of its own work, each with its own ceilings:
curl -s -H "Authorization: Bearer $CONTROL_BEARER" -H "Content-Type: application/json" \
-d '{"parent_instance":"worker","labels":{"task":"review"},"token_budget":20000,"external_id":"job-42"}' \
http://127.0.0.1:8477/v0/runs{"schema_version":1,"run":{"run_id":"run_01M76G3Y142MH0VPNTTKXAH54P","control_depth":"announced","wire_path":false,"status":"active","anomalies":[],"parent_run_id":"run_01M76G3Y0387QSP9DQ19Q3DF0P","instance":"worker","process_owner":false,"created_at":"2026-11-11T23:47:00Z","updated_at":"2026-11-11T23:47:00Z","labels":[{"key":"task","value":"review","source":"caller"}],"limits":{"token_per_run":20000,"breach_action":"warn"},"policy":{"tokens":{"per_run":20000,"cumulative":null},"dollars":{"per_run":null,"cumulative":null},"action":"warn","effective_action":"warn","scent_check":"off","rate":null,"sources":{"tokens_per_run":"run","tokens_cumulative":"unset","dollars_per_run":"unset","dollars_cumulative":"unset","breach_action":"run","scent_check":"default","rate":"unset"}},"usage":{"input_tokens":0,"output_tokens":0,"cached_tokens":0,"cost_micros":0,"estimate":"estimated"},"open_children":0}}- Name the parent with exactly one of
parent_instance(that agent's open Run) orparent_run_id(any open Run). labelsare caller labels.token_budgetanddollar_cap(a dollar string such as"1.50") are per-run ceilings over the child and its own children. They take thewarnbreach action, the default;pause,stopandblockare refused for a child Run for now.- The
201also carries the child'scredentials, once, unless the request sets"issue_credentials": false; the example above leaves them out, and Run Keys shows them. - A retried request with the same
external_idanswers201with the same Run. External ids are scoped by who opens: the operator bearer and Hosts share one namespace, and each Run's keys have their own, so a Run Key can neither take over nor discover an id the Operator or a Host uses. - The answer, and
GET /v0/runs/{id}, is{"schema_version":1,"run":{...}}: the run id,control_depth,wire_path,status,anomalies,parent_run_id,instance,process_owner,end_causeonce it has ended, timestamps,labelswith theirsource,limits,policy(the limits as resolved, with the source of each),usageover the Run's subtree (labelledestimated) andopen_children.
POST /v0/runs/{id}/close ends a child Run with end_cause closed. A Run that owns an agent's process cannot be closed; stop the agent instead.
The Run routes add a stable code to the error, beside its kind.
code | Status | When |
|---|---|---|
run-not-found | 404 | No Run has the id. |
instance-not-found | 404 | No agent has the name given as a label target. |
no-open-run | 409 | parent_instance has no open Run; start it first. |
parent-ended | 409 | The parent Run has ended. |
owns-process | 409 | close on a Run that owns an agent's process. |
nesting-too-deep | 400 | The child would nest more than 8 levels deep. |
action-unavailable | 400 | The breach action cannot work at the child's depth; the message names the depth and the metering source. |
invalid-request | 400 | A malformed label or field. |
run-ended | 409 | The Run has ended, so it cannot change. |
verb-unavailable | 409 | A lifecycle verb the Run's depth does not serve yet, since a child Run's verbs act on its calls. The message names the depth, or the parent that holds a held child. |
scope-unavailable | 400 | A cumulative ceiling on a child Run, since the cumulative scope is the agent's lifetime usage. |
raise-forbidden | 403 | A Caller loosening a limit; a Caller may only tighten. |
too-many-runs | 400 | A Selector matches more than 1000 Runs. |
set-token-not-found | 404 | No pending set has the token: never issued, evicted, or issued before the host restarted. Select again. |
set-token-expired | 409 | The set's 10 minutes have run out. |
set-token-used | 409 | The set was already acted on; one act consumes it. |
set-token-foreign | 403 | The token was issued to another credential. |
label-from-config | 409 | remove names a label the agent's labels.<key> config binds; the message names the key and how to change it. |
label-not-bound | 409 | remove names a label the Run set about itself (a caller label). |
label-bound | 409 | A caller label names a key already bound on the Run. |
run-out-of-scope | 403 | A Run Key acting on a Run outside its own Run's subtree. |
forbidden | 403 | A credential class the route's family does not allow. |
unauthorized | 401 | An unknown credential. |
credential-revoked | 401 | A revoked credential, a used refresh credential, or a key revoked while its request waited. |
too-many-children | 409 | A Run Key opening a 1001st open child under one parent. |
credential-unavailable | 503 | The operating system's random source failed, so no credential was issued and nothing changed. |
credential-in-url | 400 | A credential in the path or query (it is revoked). |
{"schema_version":1,"error":{"kind":"conflict","message":"Run `run_01M76G3Y0387QSP9DQ19Q3DF0P` owns the supervised process of `worker` — stop the instance instead of closing the Run","code":"owns-process"}}Run Keys#
A Run Key (hk_run_…) is a Run's own credential (see Run Keys). Every supervised launch gets one in HEKMA_RUN_KEY; POST /v0/runs returns one for the child it opens, with a refresh credential (hk_ref_…), unless the body sets "issue_credentials": false:
{
"schema_version": 1,
"run": { "run_id": "run_…", "…": "…" },
"credentials": {
"run_key": "hk_run_…",
"refresh_credential": "hk_ref_…",
"token_id": "3f9a1c0b7d2e",
"refresh_token_id": "a81b44c90f13"
}
}The credentials object appears in that 201 only (and the refresh 200, both with Cache-Control: no-store); no other route, event, SSE frame or export row ever carries a value. A retried external_id returns the existing Run with no credentials.
The authority matrix. Every route belongs to one family, and every credential class is allowed on some families only:
| Class | Operator routes | POST /v0/runs | POST /v0/runs/{id}/close | PATCH /v0/runs/{id}/limits | POST /v0/runs/refresh |
|---|---|---|---|---|---|
| Operator/Host bearer | yes | yes | yes | yes | 403 forbidden |
| Run Key | 403 forbidden | within its subtree | within its subtree | tighten only, within its subtree | 403 forbidden |
| Refresh credential | 403 forbidden | 403 forbidden | 403 forbidden | 403 forbidden | yes |
| Announce credential | 403 forbidden | 403 forbidden | 403 forbidden | 403 forbidden | 403 forbidden |
"Operator routes" is everything else: the fleet, instances, configuration, labels, Policies, the listing, GET /v0/runs/{id}, events, export, the lifecycle and Selector-set routes, revoke-keys and keys. A Run Key acts as its Run's Caller: it may open a child under its own Run or a descendant (the child's labels are caller labels, and its own pair comes back once), close a descendant, and tighten limits on its subtree — never raise one (403 raise-forbidden). Any other Run is 403 run-out-of-scope. A Run Key may keep at most 1000 open children under one parent (409 too-many-children); the operator bearer is not capped. A supervised agent's key, and its refresh credential, are refused (401 unauthorized) on a --listen listener that is not loopback; a listener bound to 0.0.0.0 counts as beyond loopback, whatever address a request arrives from. Every Run Key request re-checks the key inside its own write, so a request that arrives just after a revocation is refused and changes nothing, whatever it names: a child open whose parent does not resolve, or that retries an external_id, is refused too.
POST /v0/runs/refresh Authorization: Bearer hk_ref_…
POST /v0/runs/{id}/revoke-keys {"cascade": true} (operator bearer)
GET /v0/runs/{id}/keys (operator bearer)POST /v0/runs/refresh trades the presented refresh credential for a new pair once ({"schema_version":1,"run_id":…,"credentials":{…}}); the old Run Key is refused from the next request on. A used refresh credential presented again revokes the current pair of its own launch (for a Run opened over the Control API, the Run's current pair) and every used refresh credential of the Run, raises the credential-reuse Anomaly and answers 401 credential-revoked. A later launch's key is never revoked by an earlier launch's credential. A used refresh credential also leaves service wherever the credentials it belonged to do: at its launch's exit, at its Run's end, and under a revoke-keys cascade. Seen in a URL it is reuse evidence — only a holder of the value can put it there — and takes the same response as presenting it (see Never in a URL). revoke-keys revokes the Run's active credentials and its used refresh credentials, so none of them can trigger a reuse later, and, unless "cascade": false, every credential issued under any credential the Run held; it answers {"schema_version":1,"run_id":…,"cascade":true,"revoked":[{"run_id":…,"class":"run-key","token_id":…,"cascaded":false},…],"reuse_cleared":false} once the revocation is committed, and clears credential-reuse. keys lists a Run's credentials — token id, class (run-key, refresh, announce), state (active, retired, revoked), launch generation, issued_by (a token id), times and the revocation cause — never a value or a hash.
Never in a URL#
A request whose path or query carries an hk_run_, hk_ref_ or hk_ann_ token, raw or percent-encoded, answers 400 credential-in-url with a static body before it is authenticated, and a complete active token so exposed is revoked (cause exposed-in-url). A used refresh credential so exposed is reuse evidence — only a holder of the value can put it there — so it takes the same response as presenting it on the refresh route: the current pair of its own launch is revoked, every used refresh credential of the Run is revoked, a reuse-detected credential event is written and the credential-reuse Anomaly is raised while the Run is open; one unauthenticated request cannot quietly disarm the detection. A token-shaped value that was never issued, or is already revoked, is refused and changes nothing. The scan keeps at most 16 distinct tokens per URL; a request carrying more is refused all the same, and the host writes a rate-limited diagnostic saying how many it could not revoke. The per-agent metering listener applies the same rule: it answers a typed hekma_credential_in_url error, forwards nothing, and the engine revokes the exposed credential within a moment (on its next poll, about a quarter of a second). Between two polls the listener holds at most 64 distinct exposed values (and 16 per URL, the scan's own cap); past that it still refuses the request, and the next poll writes a diagnostic saying how many it could not revoke.
Bound labels#
PATCH /v0/runs/{id}/labels binds and unbinds labels on one Run. It is the same change as hekma label, for one Run at a time:
curl -s -X PATCH -H "Authorization: Bearer $CONTROL_BEARER" -H "Content-Type: application/json" \
-d '{"set":{"team":"core"},"dry_run":false}' \
http://127.0.0.1:8477/v0/runs/run_01M76G3Y0387QSP9DQ19Q3DF0P/labels{"schema_version":1,"run_id":"run_01M76G3Y0387QSP9DQ19Q3DF0P","labels":[{"key":"team","value":"core","source":"bound","origin":"label-verb"}],"prior_labels":[{"key":"team","value":"payments","source":"bound","origin":"config"}],"changed":true,"dry_run":false}- A key in
setis bound with originlabel-verb. It outranks the agent'slabels.<key>config (originconfig) and any caller label on the same key. - A key in
removetakes back a label set this way. If the agent's config binds the same key, its value comes back in the same change, as"remove":["team"]would here. A key that is not there is left alone. - The change is all or nothing. With
"dry_run": true, the answer shows the labels the change would leave and nothing is written. - An empty change, a malformed key or value, or a key both set and removed is
400 invalid_body. Unlike the other routes, an unknown field is refused, with422 invalid_body, so a misspelleddry_runnever becomes a real write. - A change records one
labels-changedRun event; repeating it changes nothing and records nothing.
GET /v0/runs/{id}/labels answers {"schema_version":1,"run_id":...,"labels":[...]}, bound and caller labels alike.
The Run listing#
GET /v0/runs is hekma ps's read: every filter, Selector and page parameter of the CLI has its equivalent here. Query parameters:
| Parameter | Meaning |
|---|---|
view | exceptions (the default) or all. |
selector | key=value[,key=value...], bound and caller labels alike. |
limit | Page size, default 50, at most 1000. 0 means the maximum; above the cap it clamps. |
cursor | The opaque cursor a previous page's next_cursor carried. |
The answer is {"schema_version": 1, "view", "selector", "items", "next_cursor", "counts"}, with items shaped as the CLI's --json items (JSON output). counts carries listed (what the active view matches) and healthy_open. next_cursor is null exactly when the read is exhausted; a final page that is exactly full carries none. The cursor names only the last Run read, so send the next page's request with the same view, selector and limit.
Malformed parameters are typed 400s with their own error.code: invalid-selector, invalid-cursor (a cursor this listing never minted, including one from a future format), invalid-limit and invalid-view.
Lifecycle verbs on a Run#
POST /v0/runs/{id}/stop, /pause, /resume and /drain act on the Run that owns an agent's supervised process exactly as the instance routes do, with the same ladder, bounds and refusals, and answer with the run id and the instance's read-back. A child Run's lifecycle verbs act on its model calls, which Hekma cannot hold or reject yet, so they are a 409 verb-unavailable naming the Run's depth (a held child's resume names the parent that holds it). An ended Run is a 409 run-ended.
Limits on a Run#
PATCH /v0/runs/{id}/limits sets limits on the Run itself, the same job as hekma budget set; GET reads them back.
PATCH /v0/runs/run_01JZ6Q9G3S8V2X7K4M1N5P0R2T/limits
{"tokens_per_run": 500000, "dollars_per_run": "3.00", "breach_action": "pause"}A limit set here outranks the agent's configuration and every Policy for that limit and belongs to the Run: it ends with the Run, and the agent's next start opens a new Run without it. The answer always carries "run_scoped": true. clear takes tokens-per-run, tokens-cumulative, dollars-per-run, dollars-cumulative and breach-action.
The answer is the outcome: direction (raised, lowered, cleared, set, unchanged), prior_limits and limits (the Run's own), resolution (the resolved limits, each with its source), and what the change fired, re_armed and lifted from the fence (fence_cleared). A ceiling raised above the usage re-arms its latch and lifts the matching block fence reason on the live Run. One lowered to or below the usage breaches at once and applies the Breach Action before the answer. dry_run plans and writes nothing. An unknown field is refused (422), so a typo on a money field is never silently dropped.
This bearer is the Operator's. A Caller presenting a Run Key may only tighten (403 raise-forbidden), and its limits are kept apart from the Operator's: each applies only while it is tighter than the limit the Operator, the Host or a Policy sets, so a later tightening below it wins again. The resolution then names the source caller where the Caller's limit is the one that applies, and the read carries them as caller_limits.
Selector sets#
To act on a set, select it once, then act on exactly that set:
POST /v0/runs/select
{"selector": "team=core"}
→ {"schema_version": 1, "token": "hkset_…", "runs": [{…}, {…}],
"matched": 2, "expires_at": "2026-11-12T10:20:00Z"}
POST /v0/runs/stop
{"set_token": "hkset_…", "window_secs": 30}
→ {"schema_version": 1, "verb": "stop", "dry_run": false, "matched": 2,
"results": [{"run_id": "…", "outcome": "stopped", "instance": {…}},
{"run_id": "…", "outcome": "refused", "error": {"kind", "code", "message"}}]}The selection matches every non-ended Run carrying all the Selector's terms, bound or caller, at most 1000 (400 too-many-runs beyond, never cut). Each entry in runs is the Run's listing row, the same item GET /v0/runs serves. Listing Runs is a different, paged read; a set to act on never pages.
The token rides the request body, never a URL, since URLs land in logs. It is 256 random bits, stored by the host only as a hash, and bound to the credential that selected it (another credential's use is 403 set-token-foreign). It is single-use (409 set-token-used after one act: select again, since the set may have changed) and expires after 10 minutes (409 set-token-expired). The host keeps at most 64 pending sets in memory, the oldest evicted, and a host restart forgets them (404 set-token-not-found: select again).
The results document is the CLI's --json shape. verb names the verb as the CLI does (stop, pause, resume, drain, close, label, and budget for POST /v0/runs/limits), and dry_run is always false: a set act acts, so plan with a single Run's dry_run or the CLI's --dry-run. Each Run of the set answers on its own, in set order: the verb's past tense (stopped, paused, resumed, drained, closed, labeled, a limits direction), unchanged, or refused with the error object a single-Run route would have answered, including engine_error when the agent's own verb refused. A Run that ended since the selection is its own run-ended refusal; the rest act. A Run whose verb committed is never reported as refused: if its Fleet row cannot be read back, its result carries no instance. Stops and drains run their windows one after another, so a set's worst case is the sum of its windows.
Policies#
The /v0/policies routes manage Policies as hekma policy does (the command reference), with the Operator bearer. Create answers 201 with Location: /v0/policies/{name} and the counts of matched Runs and Runs that fall back to warn at their depth. PATCH takes selector, set, clear, rates and dry_run; with dry_run it answers the Policy as planned and writes nothing. Deleting a Policy re-resolves its matched Runs under what remains, and the default Policy cannot be deleted.
A change applies at once to every matched open Run, and each one is a policy event on the bus, the SSE stream and the export. An unknown body field is refused at every level of a PATCH (422), and an unknown clear name is a 400, so a typo never reports success while changing nothing.
Documents and versions#
Every response body is JSON with a schema_version. Responses that carry an engine document (the fleet, one agent, config, events, Runs) use the same document and version as the CLI's --json output, so one parser serves both. Documents that exist only in the API (version, status, capabilities, errors, export) are version 1 of their own family.
GET /v0/version tells a client what it is talking to:
{"api":"hekma-control-api","version":"v0","stability":"unstable","schema_version":1,"host_version":"0.1.0","engine":{"event":1,"fleet":2,"usage":1,"budget":1,"log":1,"run":1},"log_capture":"full"}stability stays unstable for v0: fields are added, not removed, but names and messages may still change before the API is declared stable. log_capture is the host's log capture mode, which tells you whether agent output can be read.
Errors#
Every error, including an unknown path or a wrong method, is a JSON body with a kind and a message:
{"schema_version":1,"error":{"kind":"conflict","message":"Agent Instance 'worker' is running; stop it first or pass --force","engine_error":{"family":"registry","fields":{"name":"worker"},"schema_version":1,"variant":"RunningRequiresForce"}}}When the failure comes from the engine, error also carries engine_error, the engine's own typed error: its family (engine, registry or config), its variant and its fields. A client that links the engine, as the hekma CLI does, rebuilds the engine's error from it and prints exactly what it would have printed in-process; that is why CLI messages read the same whether or not a host is involved. A client that does not know a variant falls back to kind and message. The Run routes also add a code.
kind | Status | When |
|---|---|---|
unauthorized | 401 | Missing, wrong or repeated bearer token, or an unknown credential. |
forbidden | 403 | A valid credential whose class the route's family does not allow (a Run Key or refresh credential on an Operator route, the operator bearer on POST /v0/runs/refresh), or a Run Key outside its subtree (run-out-of-scope). |
unavailable | 503 | No credential could be issued: the operating system's random source failed (credential-unavailable). |
invalid_body | 400 | Malformed JSON, a start, stop or drain body that is not a JSON object, both kind and manifest, a relative manifest path, window_secs or timeout_ms out of range, an unknown config key or bad value, an unknown memory kind or restart policy, a disposition or force outside its values, a malformed cursor, limit=0. |
invalid_body | 415, 422 | No usable Content-Type (415), or JSON of the wrong shape for the route (422). |
invalid_name | 400 | The agent name is not valid. |
not_found | 404 | No such agent or Run, or no such route. |
method_not_allowed | 405 | The path exists, the method does not. |
conflict | 409 | The action does not fit the agent's state, such as stopping a stopped agent, removing a running one, or sending input to an agent that does not read it. Also when the adapter's own pause, resume or drain command fails or runs too long: the agent is left as it was and the message names the command. |
cursor_invalid | 409 | A cursor beyond what the journal or log holds, or below what the journal still keeps. The message names both positions. |
internal | 500 | Something failed in the host; the message says what. |
Events#
Two routes deliver events. Use them together: subscribe to the live stream first, then pull from the durable record to fill any gap. This is the pattern on Events, resync and diagnostics.
Live: GET /v0/events. A server-sent event stream for all agents. Each event is one data: line holding the engine's own event JSON (see JSON output):
data: {"kind":"transition","schema_version":1,"instance":"worker","prior_state":"paused","new_state":"running","cause":{"kind":"command","command":"resume"},"at":"2026-10-22T19:40:10Z"}
data: {"kind":"usage_update","schema_version":1,"event":{"instance":"worker","run_id":"run-1792697966380900000-0","input_tokens":1000,"output_tokens":200,"cached_tokens":0,"metering_source":"self-reported","sequence":8,"occurred_at":"2026-10-22T19:40:10Z"}}A run event reports a Run created, ended or changed: its Control Depth, status, Anomalies or labels. It is published right after the event that caused it, so a breach is followed by its Run's breach Anomaly and a transition by its Run's status change:
id: 10
data: {"kind":"run","schema_version":1,"change":"labels-changed","run_id":"run_01M7TNWGBAAWM4SGFEREKJ6SVC","parent_run_id":"run_01M7TNWFB3R4XCC0T3XWD5PN8M","instance":"worker","control_depth":"announced","wire_path":false,"status":"active","anomalies":[],"labels":[{"key":"tier","value":"gold","source":"bound","origin":"label-verb"}],"prior_labels":[],"cause":"label-verb","policies":["default"],"at":"2026-11-19T19:52:49Z"}If a client falls more than 1024 events behind, it gets {"kind":"lagged","skipped":N} and the stream continues with newer events. The stream closes when the host shuts down; reconnect when it is back.
Every event frame also carries id: <seq>, as the frame above does, the event's position in the global outbox, the same seq GET /v0/export serves. The lagged frame carries no id: it is a gap, not an event.
Resume with Last-Event-ID: <seq>. A reconnect that presents the last id it saw is validated before streaming: a seq below the outbox's retained floor answers 409 cursor-below-retention, and one past the committed tail 409 cursor-past-tail. Both are typed and never clamped. The server subscribes to the live bus first, then replays the outbox rows with seq > N through the active filter, reading them in bounded batches as the client drains them, and hands over to live delivery dropping live seqs the replay already read: no duplicate and no gap at the seam. If a later replay batch can no longer be read (the outbox's floor moved past it mid-replay), the stream sends one {"kind":"replay-error",…} frame (no id) and closes; reconnecting with the last id received then gets the typed 409. Without Last-Event-ID nothing is replayed or deduplicated: every live event is delivered as published.
Filter with ?selector=key=value[,…]. With a Selector, only events whose subject Run currently carries every term (bound or caller labels alike) are delivered: Run and credential events by their run id, usage and breach events by theirs, and a transition by its instance's process-owning Run (the newest one, so the stopped transition that follows a Run's end still matches). Events that name no Run (policy, breach_default_upgraded) are delivered only without a Selector. The filter reads the subject Run's current labels: the in-memory snapshot first, one read-only store read when the Run has ended (ended Runs keep matching until compaction). By design, the labels at event time are stored nowhere, so the filter cannot see them. A failed filter read surfaces a {"kind":"filter-error",…} frame (no id) and drops that one event, so it is never a silent skip. A malformed selector is the 400 invalid-selector error.
Durable: GET /v0/instances/{name}/events?cursor=.... One agent's committed events after a cursor, exactly as resync_events returns them: transitions, then breaches, then usage, with the cursor for the next call and torn_tail_skipped (always false now that the records live in the state database). Leave out cursor to start from the beginning; pass the returned cursor, URL-encoded, to continue:
curl -s -H "Authorization: Bearer $CONTROL_BEARER" \
"http://127.0.0.1:8477/v0/instances/worker/events?cursor=%7B%22transitions%22%3A2%2C%22breaches%22%3A0%2C%22usage%22%3A1%7D"Repeating a cursor returns the same events, never more. A cursor beyond what the logs hold is a 409 cursor_invalid.
Export#
The export journal is one durable list of every committed event across all agents (transitions, breaches, usage updates, Run changes, Policy changes, the breach-default upgrade and credential changes, by token id and never by value), in commit order, for a client that must not miss anything even across host restarts. It is a table in state.db, written in the same transaction as the event itself, so it never holds an event that did not happen and never misses one that did. Each entry has a seq that only grows, across restarts and across every engine process that shares the state directory. You pull batches and acknowledge what you have processed; the acknowledgement is saved in state.db too.
Pull: GET /v0/export?cursor=...&limit=....
{
"schema_version": 1,
"events": [
{"schema_version": 1, "seq": 1, "event": {"kind": "transition", "schema_version": 1, "instance": "worker", "prior_state": "registered", "new_state": "starting", "cause": {"kind": "command", "command": "start"}, "at": "2026-11-11T23:47:00Z"}},
{"schema_version": 1, "seq": 2, "event": {"kind": "run", "schema_version": 1, "change": "created", "run_id": "run_01M76G3Y0387QSP9DQ19Q3DF0P", "instance": "worker", "control_depth": "supervised", "wire_path": false, "status": "active", "anomalies": [], "labels": [{"key": "team", "value": "payments", "source": "bound", "origin": "config"}], "at": "2026-11-11T23:47:00Z"}},
{"schema_version": 1, "seq": 3, "event": {"kind": "transition", "schema_version": 1, "instance": "worker", "prior_state": "starting", "new_state": "running", "cause": {"kind": "adapter-ready"}, "at": "2026-11-11T23:47:00Z"}}
],
"cursor": {"seq": 3},
"torn_tail_skipped": false,
"blank_lines_skipped": 0,
"retained_from": 1
}- Without
cursor, you get everything after your last acknowledgement. To read from the start, passcursor={"seq":0}, URL-encoded. limitdefaults to 500 and is capped at 10,000. It must be 1 or more.- An empty
eventslist means you are caught up. retained_fromis the oldestseqstill in the journal. The journal is kept to a bounded size: acknowledged entries are dropped first, and unacknowledged ones only if it is still too big, with a note on the host's stderr. Pull and acknowledge regularly.torn_tail_skippedandblank_lines_skippedare kept for clients written against the earlier file-based journal. They are alwaysfalseand0.
Acknowledge: POST /v0/export/ack with {"seq": N} marks everything up to N as processed and returns the saved position, {"schema_version":1,"seq":N}. Acknowledging a lower number than before changes nothing. Acknowledging past the newest entry, or pulling with a cursor below retained_from or past the newest entry, is a 409 cursor_invalid.
A usage update and the breaches it causes commit together, so they take consecutive seq values, followed by the state change a pause or stop breach causes.
Upgrading from the file-based journal. Builds of hekma serve before the journal moved into the database kept it in outbox.jsonl and outbox-ack.json. The first open of a newer engine imports both once, keeping every seq and the acknowledged position, and renames them *.migrated, so a cursor you held across the upgrade stays valid. If it finds an outbox.jsonl it cannot verify, the engine refuses to open rather than guess. Rename the file aside, open the engine again, and use the per-agent events route to recover.
Limits#
The API runs inside the host process, next to supervision. It is meant for a trusted operator or a local tool on the same machine:
- TLS is required beyond loopback, but there is no rate limiting and no CORS headers. A browser page on another origin cannot call it; put it behind a proxy on the same origin. Do not expose it on a public interface.
- A slow client holds a request on the host. A
stopwith a long window keeps its connection open until the stop finishes, andDELETEwithforce=truecan take as long as the 30-second stop window. - On shutdown, the API stops first and open event streams close; requests still open after one second are dropped, with a note on stderr.
- There is no health route; every route needs a token.
Read next#
- Run Hekma as a service: the host the API runs in, and how the CLI uses it.
- Runs, Control Depth, ps and top: the Runs the
/v0/runsroutes open and label. - JSON output: the documents the API returns.
- Events, resync and diagnostics: the same events from inside a Rust program.