> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hexagon.autos/llms.txt
> Use this file to discover all available pages before exploring further.

# Runs HTTP contract

Use these operations to submit one task to a Session, recover its result, observe persisted events and request cancellation. All paths below include `/v1`. Owner and application tokens may use these routes, subject to tenant ownership and state checks. This reference describes the current source contract. The scoped HTTP reviews below cover submission, observation and cancellation using an isolated database; they do not establish model or cloud execution.

## Submit a Run

`POST /v1/sessions/{session_id}/runs` returns **202** and a Run object. `{session_id}` must be a UUID belonging to the authenticated tenant.

| Input | Type / requirement | Meaning |
| - | - | - |
| `Idempotency-Key` header | Required string, 1–256 characters | Identifies one submission within the tenant and Session |
| `input` | Required string, 1–100,000 JavaScript string code units; cannot be whitespace-only | Task text; preserved as submitted |
| `origin` | Optional strict object | Caller-supplied correlation metadata, not authorization |
| `origin.message_id` | Optional string, 1–256 characters | Your original message identifier |
| `origin.request_id` | Optional string, 1–256 characters | Your request identifier |
| `origin.channel` | Optional string, 1–100 characters | Your source-channel label |

Unknown body or origin properties are rejected. Input plus compiled initialization context must also fit the 120,000-byte UTF-8 submission bound; the string-length limit alone is insufficient. An omitted or empty origin becomes `{}`.

Persist the Session ID, exact body and key before sending. With an existing Session and trusted backend token, prepare a request file containing:

```json theme={null}
{
  "input": "Read the uploaded project and explain its entry point.",
  "origin": {"message_id": "message-001", "request_id": "request-001", "channel": "project-ui"}
}
```

Save it as `run-request.json`, then send it using a previously saved key:

```sh theme={null}
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $HEXAGON_RUN_KEY" \
  --data-binary @run-request.json \
  "$HEXAGON_API_URL/v1/sessions/$HEXAGON_SESSION_ID/runs"
```

`HEXAGON_API_URL` is the origin without `/v1`. These shell variables are example inputs, not server settings. Do not expose tokens in recorded shell traces. Save the response ID before starting observation. A 202 response establishes acceptance, not execution completion, a working Sandbox, passing tests or exported artifacts.

### Idempotency and state rules

The lookup key is tenant + Session + key. The stored request hash covers the submitted text and nonempty parsed origin. Replay the saved body unchanged; changing input or origin with the same key produces `409 idempotency_conflict`. A matching prior submission returns its current Run even if the Session subsequently closed, because the prior-request lookup precedes new-submission state checks. This is not permission to create new work in a closed Session.

For a new key, accepted Session states are `open`, `paused`, `pausing` and `resuming`; the worker handles wake/reconciliation. Only one nonterminal Run may exist per Session. Busy submission is rejected rather than queued behind it. Both bound Sandbox and model connections must still be enabled, ready and not deleted. Context-file references are checked against uploaded bytes before acceptance. The Run and initial `run.queued` event commit together.

The [submission HTTP record](https://github.com/NexusFox88/docs/blob/main/resources/testing/evidence/2026-11-20-run-submission-http-review.json) checks 27 cases over real loopback HTTP and PostgreSQL. Two concurrent identical submissions returned one Run with one queued event; two different keys competing for an idle Session produced one accepted Run and one `session_busy`. A matching replay after Session closure and connection disablement still returned the original completed Run with HTTP 202. These observations exercise the submission transaction, not worker execution or all possible concurrency schedules.

Input limits apply at two levels. For example, 40,001 copies of `界` fit the 100,000 JavaScript code-unit limit but occupy 120,003 UTF-8 bytes and fail with `413 input_too_large` even without extra context. Keep the exact intended text in your submission record; do not silently truncate it during retry. Context-file and compiled-context branches have their own requirements above and are outside this particular HTTP record.

| Failure | Status | Response action |
| - | - | - |
| Malformed UUID/body/header | 400, `invalid_request` | Correct validation errors before resubmitting |
| Whitespace-only input | 400, `invalid_submission` | Supply meaningful input |
| Missing or foreign Session | 404, `session_not_found` | Check tenant and ID; do not infer another tenant's resources |
| Key reused with changed content | 409, `idempotency_conflict` | Recover the original request; use a new key only for an intentional new task |
| Another nonterminal Run | 409, `session_busy` | Observe or cancel the existing Run before another task |
| Session closing/closed | 409, `session_closed` | Query history; use a new Session for new work |
| Control-plane expiry detected | 409, `sandbox_expired` | Inspect lifecycle/resource status |
| Bound connection unavailable | 409, `connection_not_ready` | Diagnose connection state; do not swap immutable Session bindings |
| Referenced context absent/changed | 409, `context_file_missing` / `context_file_changed` | Correct the initial context contract before execution |
| Context file exceeds bound | 413, `context_file_too_large` | Reduce the referenced file within supported limits |
| Invalid context text | 400, `context_file_encoding` | Supply valid UTF-8 text without NUL |
| Combined UTF-8 input/context too large | 413, `input_too_large` | Reduce input/context, not just character count |

A lost response is different from any confirmed error above. Repeat the original submit with the same body/key to recover its Run. Do not generate a fresh key as a transport retry. See the common [error envelope](https://docs.hexagon.autos/en/reference/errors.md).

## Recover a submission without creating another task

The submit handler returns **202 for both a new Run and a matching replay**. A replay can therefore return `state: completed`, `failed` or `cancelled`. HTTP status alone cannot tell you whether this request created work; compare the returned Run ID with your durable submission record and interpret its current state.

| What you observe | What to send or query next | What you must preserve |
| - | - | - |
| Timeout or connection loss before receiving a submit response | Repeat the original POST with its saved key and body | Tenant, Session, key, exact input and origin |
| Matching replay returns a terminal Run | Consume that Run's result and exports; submit again only for an intentional new task | Original Run ID and its business-request association |
| `session_busy` for a new key | Observe the active Run; when it becomes terminal, retry this intended submission if still wanted | The pending request's key and body; do not continually generate keys |
| `idempotency_conflict` | Recover your original submission record and investigate the mismatch | The original request; changing only the key can create unwanted work |
| Replay after credentials rotate | Authenticate with a currently valid token authorized for the same tenant and Session | Stored submission identity; the replay does not rewrite the original execution principal |
| Cancellation response is lost | GET the same Run, then repeat cancellation if it is still active and cancellation is wanted | The Run ID; cancellation has no `Idempotency-Key` requirement |

Idempotency is defined on parsed request values, not raw JSON-file bytes. JSON indentation and property order do not create a new task; omitted `origin` and `{}` are equivalent. Input text is preserved, so adding a trailing newline to `input` changes the request. An `origin.request_id` is hashed correlation metadata, **not a substitute for the header key**. Changing that field while keeping the key conflicts. Keep the saved request unchanged to avoid depending on normalization details.

The lookup is scoped to tenant and Session, not to an individual application user or token. A same-tenant replay does not establish your application's end-user ownership: enforce that mapping in your backend before forwarding requests. Submission deduplication also does not guarantee exactly-once execution of an external Tool write; uncertain external outcomes follow the [Tool reconciliation contract](https://docs.hexagon.autos/en/build/recovery.md).

## Run response

Submit, `GET /v1/runs/{id}`, cancellation and the per-Session Run list use this public representation:

| Field | Shape | Interpretation |
| - | - | - |
| `id`, `session_id` | UUID strings | Stable Run and parent Session identifiers |
| `state` | String | One of the Run states below |
| `input` | String | Original submitted task |
| `output` | Nullable JSON object | Current successful worker output is `{role:"assistant", text, artifacts}`; not a substitute for state or separate artifact queries |
| `error` | Nullable JSON object | Execution/recovery diagnostic, commonly with `code`; inspect even when a Run is nonterminal |
| `origin` | Object | Parsed caller-supplied correlation fields, or `{}` |
| `execution_identity` | Object | Persisted execution context; see below |
| `created_at`, `updated_at` | Timestamp strings | Server record timestamps |

`execution_identity` on new submissions includes `tenant_id`, `session_id`, `agent_id`, `agent_revision` and, when supplied by authentication, `principal` with optional `key_id` and `role`. Direct Sessions may have no saved Agent identity. Historical rows can contain `{}`. Do not use caller-provided origin metadata as proof of identity or treat this snapshot as an independent access credential. Worker lease fields, request hash, idempotency key and Runtime cursor are not part of `publicRun`.

Run states are `queued`, `provisioning`, `running`, `waiting_authorization`, `waiting_approval`, `cancelling`, `completed`, `failed` and `cancelled`. Only the last three are terminal. Session and Runtime states are separate; see [events and states](https://docs.hexagon.autos/en/reference/events-and-states.md).

Retrieve one Run with no body or query parameters:

```sh theme={null}
curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  "$HEXAGON_API_URL/v1/runs/$HEXAGON_RUN_ID"
```

Success is **200**. A missing/foreign Run returns `404 run_not_found`.

## Example public response and interpretation

The following response was produced by the actual GET handler using a deterministic database fixture. The IDs, timestamps and assistant greeting are illustrative; this is not a model execution receipt. The [handler check](https://github.com/NexusFox88/docs/blob/main/resources/testing/evidence/2026-11-20-runs-http-reference-review.json) also covered missing Run, invalid UUID and missing identity responses.

```json theme={null}
{
  "id": "00000000-0000-4000-8000-000000000010",
  "session_id": "00000000-0000-4000-8000-000000000001",
  "state": "completed",
  "input": "Return a short greeting.",
  "output": {
    "role": "assistant",
    "text": "Hello.",
    "artifacts": []
  },
  "error": null,
  "created_at": "2026-11-20T00:00:00.000Z",
  "updated_at": "2026-11-20T00:00:02.000Z",
  "origin": {
    "request_id": "example-request"
  },
  "execution_identity": {
    "tenant_id": "example-tenant",
    "session_id": "00000000-0000-4000-8000-000000000001",
    "agent_id": null,
    "agent_revision": null,
    "principal": {
      "key_id": "example-key-id",
      "role": "application"
    }
  }
}
```

Interpret the fields together:

* `state: completed` settles this Run; it does not close the parent Session.
* `output.artifacts: []` describes this fixture's result. It is not an exported file or evidence that arbitrary workspace files are downloadable; use the artifact endpoint for recorded exports.
* `agent_id: null` and `agent_revision: null` are valid for direct Sessions; do not require every Run to have a template.
* `origin.request_id` is caller metadata, whereas `execution_identity.principal` is the stored authenticated context. Neither is a reusable credential.
* The response omits `Idempotency-Key`, request hash, lease and Runtime cursor. Keep your original submission record; GET cannot reconstruct its key for you.

A nonterminal response can contain recovery diagnostics in `error`; classify terminality from `state`, not from the presence of `error` or `output` alone. If polling races a new event, continue observing the same Run rather than manufacturing a new submission.

## List Runs: two different contracts

### Runs in one Session

`GET /v1/sessions/{session_id}/runs` returns **200** with `{ "runs": [...] }`, where entries are full public Run objects. Optional `before` is a schema-validated datetime; the comparison is strictly `created_at < before`. The page is bounded at 100 and ordered by creation time descending. There is no `next_offset` or `has_more` field on this route.

```sh theme={null}
curl --fail-with-body --silent --show-error --get \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  --data-urlencode "before=$HEXAGON_BEFORE_TIMESTAMP" \
  "$HEXAGON_API_URL/v1/sessions/$HEXAGON_SESSION_ID/runs"
```

Omit `before` for the first page. The current timestamp-only cursor has no ID tie-breaker; equal timestamps at a page boundary can be skipped. Do not promise lossless exhaustive export using this cursor. Missing/foreign Session returns `404 session_not_found`.

### Tenant-wide Run summaries

`GET /v1/runs` returns **200** with `{ "runs": [...], "offset": 0, "next_offset": null }` or a numeric next offset.

| Query | Default and constraints |
| - | - |
| `limit` | 25; integer 1–100 |
| `offset` | 0; nonnegative integer |
| `search` | Empty string; at most 200 characters |
| `state` | Empty string; at most 40 characters; exact state filter when nonempty |

Search is a case-insensitive substring match across Run ID, Session ID, input and Session definition name. Results sort by `created_at DESC, id DESC`. Entries contain `id`, `session_id`, `state`, `created_at`, `updated_at`, `error`, `input_preview` (first 240 database text characters) and `agent_name`. They are summaries, not the full Run response. Concurrent insertions can shift offsets; this is not a snapshot export.

```sh theme={null}
curl --fail-with-body --silent --show-error --get \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  --data-urlencode 'limit=25' --data-urlencode 'offset=0' \
  --data-urlencode 'state=failed' \
  "$HEXAGON_API_URL/v1/runs"
```

## Choose the correct pagination cursor

| What you are reading | Continuation | What completion means |
| - | - | - |
| Tenant-wide Run summaries | Pass the returned numeric `next_offset` as `offset`; stop when it is `null` | End of this changing collection, not a consistent export snapshot |
| Full Runs in one Session | Pass the last row’s `created_at` as `before`; the server uses a strict earlier-than comparison | An empty page ends the scan, but equal timestamps at the boundary can leave rows unseen |
| Persisted events for one Run | Pass the last successfully processed string event ID as `after` | An empty page means caught up for now; read Run state and drain again after observing a terminal state |

These cursors are not interchangeable. For example, 101 Runs sharing a timestamp can yield a 100-row Session page followed by an empty page when that timestamp is used as `before`. By contrast, 501 persisted events are read as a 500-entry page and then one entry using the last event ID. Save application request and Run IDs when submitting work; do not depend on a later collection scan to reconstruct a complete business ledger.

## Read or stream persisted events

`GET /v1/runs/{id}/events?after=0` returns **200** and `{ "events": [...] }`. Each entry contains string `id`, string `type`, JSON `data` and `created_at`. `after` defaults to `"0"`, must contain only decimal digits and is exclusive. A page contains at most 500 entries ordered by increasing sequence. Save the last processed ID; gaps are valid. Query again until no entries remain, and continue if the Run is active. Absence of events alone is not completion.

Keep each server-returned cursor as a decimal string associated with its Run. Start with `"0"`; do not convert IDs to JavaScript `Number`, increment them yourself or derive them from timestamps. The current query uses PostgreSQL’s signed 64-bit sequence range even though request validation accepts any digits-only string. A numeric cursor outside that range currently produces `500 internal_error` on the JSON events endpoint; it is not guaranteed to produce a clean 400 validation error. Correct a corrupt cursor from your durable checkpoint instead of repeatedly retrying the same oversized value.

```sh theme={null}
curl --fail-with-body --silent --show-error --get \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  --data-urlencode "after=$HEXAGON_EVENT_CURSOR" \
  "$HEXAGON_API_URL/v1/runs/$HEXAGON_RUN_ID/events"
```

`GET /v1/runs/{id}/stream` returns **200** `text/event-stream`. Cursor precedence is explicit `after`, then `Last-Event-ID`, then `"0"`. It emits persisted events as SSE `id`, `event` and JSON `data`; the stream does not include the JSON-list timestamp field. Heartbeats are comment frames (`: keepalive`) after approximately 15 seconds without heartbeat emission. The server checks for new data at 500 ms intervals when no page is available.

```sh theme={null}
curl --fail-with-body --silent --show-error --no-buffer --get \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  --data-urlencode "after=$HEXAGON_EVENT_CURSOR" \
  "$HEXAGON_API_URL/v1/runs/$HEXAGON_RUN_ID/stream"
```

After observing a terminal Run, the server rechecks persisted events before emitting unnumbered `stream.end` with `{ "state": "completed" }` (or failed/cancelled). This example is a shape, not an execution receipt. Do not store `stream.end` as a new event cursor. Unexpected EOF requires re-query/reconnect using the last committed cursor; closing the client stream does not cancel the Run. Missing/foreign Run returns 404 before opening the stream; failure after headers may instead appear as a disconnected stream.

## Cancel a Run

`POST /v1/runs/{id}/cancel` takes no required body and returns **200** with a public Run object:

```sh theme={null}
curl --fail-with-body --silent --show-error --request POST \
  -H "Authorization: Bearer $HEXAGON_API_TOKEN" \
  "$HEXAGON_API_URL/v1/runs/$HEXAGON_RUN_ID/cancel"
```

A queued Run becomes `cancelled`; another nonterminal Run becomes `cancelling`. Pending approvals expire in the same transaction, and the corresponding state event is persisted. Already terminal or cancelling Runs return their current representation without another cancellation transition. Continue querying until terminal. This operation does not promise immediate process termination, rollback of dispatched Tool writes or Session resource cleanup. Close the Session separately when finished. Missing/foreign Run returns `404 run_not_found`.

### Cancellation can race completion

The returned object is the state observed under the Run lock. If completion committed first, cancellation returns `completed`; it does not convert the result to `cancelled`. If cancellation acquired the lock while queued, it returns `cancelled`; for another active state it requests `cancelling`, and you must wait for worker settlement. A 200 response confirms that the cancellation endpoint handled your request, not that the final state must be `cancelled`.

Repeated cancellation of a `cancelling` or terminal Run does not append another cancellation event. It also does not re-run cleanup of pending approvals on that early-return path. Treat approval expiry, process settlement, external write reconciliation and Session closure as their respective contracts; do not infer them all from the cancellation HTTP status.

## Verification scope

The [Run observation HTTP review](https://github.com/NexusFox88/docs/blob/main/resources/testing/evidence/2026-11-20-run-observation-http-contract-review.json) records 40 checks using the current server over loopback HTTP, real PostgreSQL and an isolated migrated schema. It covers the two list routes, single-Run retrieval, JSON events, SSE and cancellation: tenant boundaries, application-token access, pagination, cursor precedence, a real client disconnect and reconnect, and cancellation state/event/approval transactions. The temporary schema was removed afterward.

Run completion in that review was a controlled database transition. It did not run a model, Harness or cancellation worker, exercise a browser/proxy, or submit a real task. Use the [first Session tutorial](https://docs.hexagon.autos/en/start/first-session.md) for the separate cloud execution journey; these HTTP checks do not extend its verified provider/model scope.

Sources: [HTTP routes and public projection](https://github.com/NexusFox88/docs/blob/main/resources/apps/control-plane/server.ts), [submission/events/cancellation](https://github.com/NexusFox88/docs/blob/main/resources/modules/execution/runs.ts), [collection queries](https://github.com/NexusFox88/docs/blob/main/resources/modules/execution/queries.ts). Next: [HTTP inventory](https://docs.hexagon.autos/en/reference/http.md), [events](https://docs.hexagon.autos/en/reference/events-and-states.md), [recovery](https://docs.hexagon.autos/en/build/recovery.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.