# Agents & runs — reference

A **stored agent** is a named, versioned definition: a model, a system prompt, a list of the
tools it may use, per-run limits and a spending cap. It lives in one app context. A **run**
executes one stored agent on one input and streams what it does. The run's tool calls act as the
caller who started it, with that caller's own permissions.

This page lists every field, limit, event and error code, and ends with a *Notes & limits*
section. For a guided walk-through, see the [how-to](./how-to.md). For the endpoint-level wire
shapes, see the generated **API reference**.

> **Version note.** Stored agents and runs are part of API and SDK `0.49.0`. In the SDKs, all ten
> operations sit on the `agents` sub-client: `createAgent`, `listAgents`, `getAgent`, `updateAgent`,
> `deleteAgent`, `listAgentVersions`, `createRun`, `getRun`, `cancelRun` and `listRuns` (SDK 0.50.0), each spelled in its
> language's convention (`client.agents.createRun` in TypeScript, `client.agents.create_run` in
> Python, `client.agents().createRun(...)` in Java). Agents can also be managed with the CLI's
> `vectros agents` commands ([CLI](../clients/cli.md#command-catalog)) and declared in a blueprint's
> `agents` section ([blueprints](../clients/blueprints.md#agents)). The MCP server runs stored agents
> with its `agent_list`, `agent_run` and `run_get` tools ([MCP](../clients/mcp.md#the-26-tools)).

---

## Before you start: the tenant switch

Agent runs are **off** for every tenant until an account owner turns them on. The switch is per
tenant, so your live and your test environment are switched separately. Until it is on,
`POST /v1/runs` answers `403` with `errorCode` `AGENT_RUNS_NOT_ENABLED`. Turning it off stops new
runs from starting; a run already in progress is not stopped.

An account owner turns it on in the developer portal, under **Settings → Agent runs**: choose
**Test** or **Live**, then turn on **Agent runs**. The same switch is a developer-portal API call,
open to account owners only, with a developer-portal session token (an owner whose own access to
the account is not active is refused with `403` `OWNER_ACCESS_INACTIVE`):

| Operation | Method / path | Body and answer |
|---|---|---|
| Read | `GET /developer/agent-runs?tenant=live\|test` | `{ "tenant": "live", "enabled": false }`. `tenant` defaults to `test`. |
| Change | `PATCH /developer/agent-runs?tenant=live\|test` | Body `{ "enabled": true }` (only `enabled`, a boolean); answers with the new state. |

Every change is recorded in the tenant's version history.

Storing agents does not need the switch: you can create and version agents before runs are on.

---

## Scopes

| Scope | Grants |
|---|---|
| `agents:c` | `POST /v1/agents` (create). |
| `agents:r` | `GET /v1/agents`, `GET /v1/agents/{id}`, `GET /v1/agents/{id}/versions`. |
| `agents:u` | `PUT /v1/agents/{id}`, and `POST /v1/agents?upsert=true` when the agent already exists. |
| `agents:d` | `DELETE /v1/agents/{id}` (retire and purge). |
| `runs:c` | `POST /v1/runs` and `POST /v1/runs/{id}/cancel`. Also admits `GET /v1/agents` (the collection only), which then returns a [summary](#the-summary-view) of each agent the grant covers. |
| `runs:r` | `GET /v1/runs` and `GET /v1/runs/{id}`. |

A `runs` grant may [name one agent](#naming-the-agents-a-grant-reaches): `runs:c:<agent>`, `runs:r:<agent>`. A bare `runs:c` or `runs:r` covers every agent in the context.

### Naming the agents a grant reaches

The qualifier is an agent's name (1-64 letters, digits, `_` or `-`; no wildcard), on `c` and `r` only. It only narrows:

- `runs:c:<agent>` starts that agent and no other. Starting any other agent answers `403 FORBIDDEN`, the same answer
  whether or not that agent exists. It cancels only runs of that agent, and the summary view lists only that agent.
- `runs:r:<agent>` reads only runs of that agent.
- A run outside the grant answers `404`, as a missing run does. A grant naming an agent never shows you a run someone
  else started.

An agent's name never changes and is never reused, so a grant naming it cannot come to cover another agent. It decides
which agent a role may start, not what that agent does: whoever holds `agents:u` can write a new version of it, and a run
still acts with the caller's own rights.

A run is visible only to whoever started it: the key that started it, or, for a token bound to a
user, that user (a token bound to no user cannot start a run). The tenant's root key sees every run
in the tenant. To any other caller a run does not exist (`404`), whatever its scopes.
For the scope grammar, see [Identity and access](../identity-access/reference.md).

---

## Stored agents

### The app context

An agent belongs to one app context. Every `/v1/agents` operation takes an optional `contextId`
query parameter; without it, the credential's own context is used (`default` for the root key). A
credential confined to one context that names another gets `403`. The root key may name any
existing context in its tenant; a context that does not exist answers `404`.

### The definition

These are the fields you send to `POST /v1/agents` and `PUT /v1/agents/{id}`. Every optional field
you leave out takes its default; nothing is carried over from an earlier version.

| Field | Type | Default | Rules |
|---|---|---|---|
| `name` | string | — (required on create) | 1–64 letters, digits, `_` or `-`. Unique in the app context and never changes: a `PUT` that sends a different `name` is refused (`400`). |
| `model` | string | — (required) | A model that agents can run on (see [Models](#models)). An unknown model is refused (`400`); a model that agents cannot run on is refused with `400` `MODEL_NOT_SUPPORTED_IN_RUNS`. |
| `system` | string | `""` | The system prompt. At most 32,000 characters. |
| `description` | string | — | At most 500 characters. Shown in the summary view. |
| `authority` | string | `CALLER` | Whose authority the run's tool calls carry. `CALLER` is the only value accepted; any other value is refused (`400`). It is a plain string, not an enum. |
| `tools` | array of `{ name, allowWrites, script?, description? }` | `[]` | The tools the agent may use (see [Tools](#tools)). At most 50 entries, no duplicates. `allowWrites` (boolean, default `false`) must be `true` for a tool that changes data. `script` and `description` make the entry a [script tool](#script-tools). |
| `limits.maxSteps` | integer | `10` | Model calls per run, 1–25. |
| `limits.maxTokensPerCall` | integer | `2048` | Output tokens per model call, 16–8192. |
| `limits.maxToolCalls` | integer | `20` | Tool calls per run, 0–50. At least 1 when `tools` is not empty. |
| `limits.maxWrites` | integer | `0` | Data-changing tool calls per run, 0–1000. At least 1 when any tool has `allowWrites: true`. |
| `budget.maxInferenceCents` | integer | `100` | The most one run's model calls may cost, in cents, 1–500; a value outside that range is refused with a plain `400`. A value in range but below the platform's minimum for a run is refused with `400` `BUDGET_TOO_LOW`; the error's `minimumCents` field names the minimum. |
| `budget.ragMaxInferenceCents` | integer | none | Optional. The most the answers of one run's [`rag_ask`](#rag_ask) calls may cost together, in cents, from 1 to the per-run `budget.maxInferenceCents`. Without it, those answers are bounded only by the run's own budget. It is part of the definition: changing it stores a new version. |
| `budget.periods` | array of `{ period, maxInferenceCents }` | none | Optional caps on what **all** of the agent's runs may spend on model calls in a calendar period, at most one per period. `period` is `HOUR`, `DAY`, `WEEK` or `MONTH` (other values may be added); each cap is in cents, from the per-run `budget.maxInferenceCents` up to 10,000,000, and a longer period's cap may not be lower than a shorter one's. See [Period caps](#period-caps). |
| `expectedVersion` | integer | — | `PUT` only: the `latestVersion` you read (see [Versions](#versions)). |

An unknown field inside `tools[]`, `limits` or `budget` is refused (`400`), so a misspelt limit
cannot be stored as its default without you noticing. **An unknown top-level field is ignored**:
check the spelling of `system` in particular, because a misspelt prompt field stores an agent with
an empty prompt.

A definition is checked in full before anything is stored: a refused request writes nothing.

### The agent as returned

| Field | Meaning |
|---|---|
| `id` | The agent's id. Use it in every other `/v1/agents/{id}` call and as `agentId` in a run. |
| `name`, `description`, `model`, `system`, `authority`, `tools`, `limits`, `budget` | The definition of the version shown, with every default filled in. |
| `status` | `ACTIVE`, `RETIRED` or `PURGED`. |
| `version` | The version shown. |
| `latestVersion` | The agent's newest version. |
| `createdAt`, `createdBy` | When, and by whom, the version shown was written. |
| `periodUsage` | Only when one agent is read (`GET /v1/agents/{id}`): for each capped period and always the current month, `period`, `periodStart` and `resetsAt` (ISO-8601 at UTC-05:00), `maxInferenceCents` (the cap in force, absent for an uncapped month) and `spentCentsMilli` / `reservedCentsMilli` (thousandths of a cent: what ended runs spent, and what runs in progress hold). |
| `purgedAt`, `purgedBy` | On a purged agent or version: when, and by whom. |
| `provisionedBy` | A label marking which tool provisioned the agent (the CLI sets it for agents a blueprint declares). Set once; a different value is refused (`400`). |
| `created` | On `POST /v1/agents` only: `true` when this request created the agent. |

Fields with no value are left out. `provisionedBy` may also be sent in the definition.

### Operations

| Operation | Success | Notes |
|---|---|---|
| `POST /v1/agents` | `201` (`created: true`) | Creates the agent at version 1. If the name already exists and you can read that agent (`agents:r`), the stored agent is returned unchanged (`200`, `created: false`), even if your body differs; if you cannot read it, the answer is `400` (the name is already in use). With `?upsert=true` (which also needs `agents:u`), a new version is written only when the definition differs. A retired or purged name answers `409` `AGENT_RETIRED` when you can read the agent, and the same `400` (name in use) when you cannot. Your body is validated first in every case. |
| `GET /v1/agents` | `200` | A page of the agents in the context, each at its latest version: `{ data, nextCursor }`. Pass `nextCursor` as `startFrom` to read on; `limit` is 1–100 (default 20), and a page of full definitions holds at most 20. Retired and purged agents are left out unless `includeRetired=true`; because they are filtered after a page is read, a page can hold fewer agents than `limit`, or none, while `nextCursor` is set: keep paging until `nextCursor` is null. |
| `GET /v1/agents/{id}` | `200` | The latest version, or an earlier one with `?version=N`. |
| `GET /v1/agents/{id}/versions` | `200` | The agent's versions, newest first, without their content unless `includeContent=true`. Paged like the list. |
| `PUT /v1/agents/{id}` | `200` | A full replacement that writes the next version. With `?restore=true`, a retired agent becomes active again with this body as its next version; a purged agent cannot be restored (`409` `AGENT_RETIRED`). |
| `DELETE /v1/agents/{id}` | `200` | Retires the agent: it stays readable but can no longer run, and its name stays reserved. Retiring a retired agent changes nothing. With `?purge=true`, erases a **retired** agent's content (every version) and keeps its name reserved; purging an active agent answers `409` `AGENT_NOT_RETIRED`. `?purge=true&version=N` erases one version that is not the latest (`409` `AGENT_VERSION_IS_LATEST` for the latest). |

An agent you cannot read answers `404`, the same as one that does not exist.

### Versions

Every write of a definition (a create, an upsert that changes something, a `PUT`, a restore)
stores a new version, and the agent points at its newest one. A version is never edited
afterwards. Retiring changes only the agent's status; a purge erases the content of the versions
it covers and keeps their numbers, which then read `status: PURGED` with no content.

To avoid overwriting someone else's change, send the `latestVersion` you read as
`expectedVersion` on `PUT`: if the agent has a newer version, the update is refused with `409`
`VERSION_CONFLICT` and nothing is written.

A run uses the latest version unless it names one with `agentVersion`, so a new version changes
every run that does not pin a version.

### The summary view

A caller that holds `runs:c` but cannot read an agent's definition gets, from `GET /v1/agents`,
only `id`, `name`, `description`, `status` and `latestVersion` for that agent, and only for the agents its `runs:c`
grant covers (all of them for a bare `runs:c`). This lets a
credential that runs agents find them without seeing their prompts or tools.

### Models

A run needs a model that agents can run on. These are accepted today: `claude-haiku-4-5`,
`claude-haiku-5-5`, `claude-sonnet-5`, `claude-sonnet-5-5` and `claude-opus-5-5`. Any other model
in the catalog is refused with `MODEL_NOT_SUPPORTED_IN_RUNS`. Storing an agent does not check
whether your plan includes its model; starting a run does (`409` `MODEL_NOT_AVAILABLE`).

---

## Tools

A run can call only the tools its agent lists. Each tool call goes through the same authorization
as the equivalent API call made with the caller's own credential: a call the caller could not
make over the API (another app context, a scope outside the caller's, another user's `userId`) is
refused exactly as the API refuses it, and the agent sees the refusal.

| Tools | Changes data | What they do |
|---|---|---|
| `records_get`, `records_lookup`, `records_query` | no | Read records, as the `/v1/records` routes do. |
| `documents_get`, `documents_lookup`, `documents_query`, `documents_text` | no | Read documents. `documents_query` takes the `type` filter. `documents_text` returns a document's text in parts (`limit`, `offset`), with `totalLength` and `nextOffset`; each part is one tool call. |
| `entities_get`, `entities_lookup`, `entities_query` | no | Read identity entities. |
| `folders_get`, `folders_query` | no | Read folders. |
| `list_schemas` | no | List the schemas in the context. |
| `search_content` | no | Search the records and documents the caller can read, in `HYBRID`, `SEMANTIC` or `TEXT` mode, as `POST /v1/search` does. A caller whose access is limited to part of the content must pass the same `scope` filter its key needs on `POST /v1/search`. |
| `records_create`, `records_update`, `records_delete` | yes | Write records. |
| `documents_create`, `documents_update`, `documents_delete` | yes | Write documents. |
| `entities_create`, `entities_update`, `entities_delete` | yes | Write identity entities. |
| `folders_create`, `folders_update`, `folders_delete` | yes | Write folders. |
| `web_fetch` | no | Read one public web page and return its text (see [web_fetch](#web_fetch)). Off until an account owner turns it on for the tenant. |
| `rag_ask` | no | Ask a question of the content the caller can read and get back a generated answer with its sources (see [rag_ask](#rag_ask)). Its answers are model calls, paid from the run's budget. |

A tool that changes data must be listed with `allowWrites: true`, and the agent needs
`limits.maxWrites` of at least 1. A write tool may name `scopes`, `userId` and `folderId`, as you
could over the API. A run started with `readOnly: true` refuses every data-changing tool call.

A tool name that is not in the catalog, or a data-changing tool listed without `allowWrites`, is
refused when you store the agent (`400`).

#### Script tools

An entry with `script: { name, version }` offers a stored script as a tool. `version` is a version
number as a string (`"3"`) or `"latest"`, which is resolved once, when a run starts. `name` is what the
model sees (any name that is not a catalog tool's), and `description` (1 to 1,024 characters, optional)
is what the model is told; without one, a description is generated from the script's name and version.
The model is offered the script version's own `inputSchema` (see the data model reference), and the
arguments of every call are checked against it.

Storing the agent is refused (`400`) when your credential may not run the script (`scripts:x`; the
answer is the same whether or not the script exists), when the version does not exist, or when it
declares no `inputSchema`. A run executes the script under the run's caller's credential: a caller who
may not run the script is not offered the tool, and every call checks `scripts:x` again. Without
`allowWrites` the script can only read; with it, one call counts once against `limits.maxWrites`
however many rows it writes, in one transaction. Each call may run for 10 seconds, and a run may make
12 script-tool calls in total (each reserves its full 10 seconds, so 120 seconds of script time); a call past that is refused and
the run goes on. A call refused before it ran (a rate, credit or concurrency limit) is listed with the outcome `NOT_STARTED` and
does not count. Script
tools cannot make outbound HTTP calls. If the version is deleted, or a `latest` reference resolves to a
version with no `inputSchema`, a run of the agent is refused with `409` `AGENT_TOOL_UNAVAILABLE`.

The catalog also lists `web_search`. It has no account-owner switch: an agent that lists it can
always be stored, and a run of it while `web_search` is not enabled for the platform is refused
with `403` `AGENT_TOOL_NOT_ENABLED`.

### web_fetch

`web_fetch` takes one `url` (`http` or `https`, 8 to 2048 bytes, with a host and no user name or
password) and returns `{ url, text, truncated }`. The page is fetched by a third-party web-fetch
provider, not from the Vectros network. HTML (or a page with no content type) is converted to
text; other `text/*` types, JSON and XML are returned as they are; content that is not text is
refused. A page too long for one tool result is
cut, with `truncated: true` and a note saying so.

**Put only public addresses in it.** The address is sent to the provider and is kept in the run's
tool-call record; never put personal, patient or account information in it. Vectros does not
check what an address points to.

`web_fetch` is off until an account owner turns it on for the tenant: in the developer portal, the
**Web fetch tool** switch under **Settings → Agent runs**, or with a developer-portal API call
(owners only):

| Operation | Method / path | Body and answer |
|---|---|---|
| Read | `GET /developer/agent-tools?tenant=live\|test` | `{ "toolClasses": { "web_fetch": { "enabled", "usable", "state", "acceptanceRequired", "acceptanceType", "acceptance" } } }`. `state` is `ENABLED`, `OFF` or `ACCEPTANCE_REQUIRED`; `acceptance` carries the status of the web fetch enablement. |
| Change | `PATCH /developer/agent-tools?tenant=live\|test` | Body `{ "toolClasses": { "web_fetch": true } }`; a class you do not name keeps its value. Answers with the new state. |

An account under a business associate agreement must also have accepted the web fetch enablement,
shown under the switch in the developer portal, before `web_fetch` can be turned on: until then,
turning it on answers `409` `ACCEPTANCE_REQUIRED` and nothing changes. Turning it off needs no
acceptance. As for the agent-runs switch, an owner whose own access to the account is not active is
refused with `403` `OWNER_ACCESS_INACTIVE`, when reading the switch and when turning it on or off. A run
of an agent that lists `web_fetch` in a tenant where it is off is refused with `403`
`AGENT_TOOL_NOT_ENABLED`. Turned off during a run, the agent's next call to it is refused and the
run goes on.

### rag_ask

`rag_ask` answers a question from the content the run's caller can read: it searches it, as
`POST /v1/search` does in `HYBRID` mode, and has a model write an answer from the passages it found.
The agent gets the answer and the sources, not the passages. The answer is always written by
**Claude Haiku 5.5** (`claude-haiku-5-5`), whatever model the agent itself runs on; the call cannot
choose another.

| Argument | Type | Rules |
|---|---|---|
| `query` | string | Required. The question, 1 to 2,000 characters. |
| `scope` | string | The same `scope` filter `POST /v1/search` takes (`namespace:value`), 3 to 512 characters. A caller whose access is limited to part of the content must pass the one its key needs, as for `search_content`. |
| `scopeFilters` | array | Several scope filters at once, as `POST /v1/search` takes them: 1 to 16 `namespace:value` strings (for example `["org:acme", "client:c1"]`). For a caller whose access is limited along more than one namespace. Use either `scope` or `scopeFilters`, not both. |
| `userId` | string | Only content of this user, 1 to 128 characters, as `POST /v1/search` takes it. A caller whose access is limited to one user must pass that user. |
| `contentTypes` | array | `documents`, `records` or both. Both by default. |
| `typeName` | string | Only content of this type, 1 to 128 characters. |
| `limit` | integer | How many passages to retrieve, 1 to 10; `8` by default. |

Any other argument is refused before anything runs. It returns `{ answer, sources, note? }`.
`sources` lists the passages the answer was written from, each `{ ref, id, externalId?, sourceType }`:
`ref` is the number the answer cites, and `id` the record or document, to read with `GET /v1/records/{id}`
or `GET /v1/documents/{id}` depending on `sourceType`. When nothing the caller can read matches,
`answer` is `null` and a `note` says so: no answer is generated, and only the search is billed.
Passages that do not fit the answer's context (about 6,000 tokens) are left out, and a `note` says
how many.

- **The caller needs `inference:r`**, granted together with the read access the call names: when a
  key's grants are split into several, the one that gives `inference:r` must also cover the `userId`,
  `scope` or `scopeFilters` the call passes, as for `POST /v1/rag`. Otherwise the call is refused and
  the run goes on.
- **Cost.** Each call is billed as one search, plus its answer: one model call of at most 1,024 output
  tokens at Claude Haiku 5.5's price. The answer is paid from the run's budget like the run's own model
  calls (and from `budget.ragMaxInferenceCents` when the agent sets one), and it is included in the
  run's charge. Before the call, its largest possible cost is reserved; when it finishes normally, it is
  charged what it actually cost. If the run ends (cancelled, or stopped by the platform) while an answer
  is still running, or the answer's completion cannot be recorded, that answer stays charged at its
  largest possible cost, never above the run's budget. One answer costs well under one cent, so even a
  `ragMaxInferenceCents` of 1 leaves room for at least one answer. A call refused because the budget has
  no room for it is not run, and the run goes on.
- **Time.** A call, the search and the answer together, has up to 30 seconds. An answer that is not
  back by then is abandoned: the call ends with a tool error, and it is charged up to its maximum,
  because the model may still bill for it. The agent can call the tool again.
- One `rag_ask` call of a run runs at a time; a second one while the first is running is refused,
  and the agent can try it again.
- Reads it makes are recorded as reads by the run's caller, naming the run and `rag_ask`, like the
  reads of any other tool.

---

## Runs

### `POST /v1/runs` — start a run

| Field | Type | Notes |
|---|---|---|
| `agentId` | string | Required. The stored agent to run. |
| `agentVersion` | integer ≥ 1 | The version to run; the latest by default. |
| `input.text` | string | Required. What the run is asked, 1 to 100,000 characters. |
| `budget.maxInferenceCents` | integer | A lower budget for this run. It may only lower the agent's own: a higher value is refused (`400` `INVALID_REQUEST`), and so is one below the minimum (`400` `BUDGET_TOO_LOW`). |
| `readOnly` | boolean | When `true`, every data-changing tool call in this run is refused. Default `false`. |

A run takes a stored agent only: a body carrying a `definition` is refused with `400`
`INVALID_REQUEST`. A field name the run body does not know is ignored, so check the spelling of
`readOnly`, `agentVersion` and `budget`: a misspelt `readOnly` starts a run that is not read-only. The body may be at most 256 KB. A run acts in the credential's own app context;
a `contextId` query parameter naming any other context is refused.

Starting a run needs a key, or a token bound to a user: a token bound to no user is refused with
`403` `RUN_REQUIRES_BOUND_USER`.

**Idempotency.** Send an `Idempotency-Key` header (1 to 128 letters, digits, `.`, `_`, `:` or `-`)
to make a retried start safe. The same key with the same body (byte for byte) never starts a second
run: once a run was started under that key, and for as long as the key is remembered (at least as
long as a run can last), the retry is answered `409` `IDEMPOTENCY_IN_PROGRESS`, with the first
run's id in the body's `runId` and in the `X-Vectros-Run-Id` header. A start that was refused
before a run began stores nothing, so a retry of it is evaluated afresh. A key is never reused; send a new one to start again. The same key with
a different body is refused with `422` `IDEMPOTENCY_KEY_REUSED`.

### The stream

A started run answers `200` with `Content-Type: text/event-stream`, whatever `Accept` you send.
The `X-Vectros-Run-Id` response header names the run. Every Server-Sent Events frame is
`event: run.event` with a JSON `data` line. The stream also carries comment lines (such as
`: keepalive`) while the run works, every few seconds at first and then about every 15 seconds; a
parser you write yourself must skip them.

Every event carries `type`, `runId`, `seq` and `terminal`.

| `type` | Fields | Meaning |
|---|---|---|
| `run.started` | `agentId`, `agentVersion` | The run started, on this version. |
| `message.delta` | `text` | The next piece of the agent's answer. |
| `message.completed` | `step`, `text` | One model call's complete answer text. |
| `tool.completed` | `step`, `toolCallId`, `tool`, `outcome`, `code` | A tool call ended. `outcome` is `OK`, `TOOL_ERROR`, `DENIED` or `ERROR`; `code` gives a short reason when it did not succeed. Never the call's arguments or result. |
| `run.completed`, `run.failed`, `run.cancelled` | `status`, `reason`, `errorCode`, `settled`, `inferenceBalanceCentsChargedMilli`, `inferenceBalanceCentsRefundedMilli` | The one final event, with `terminal: true`. The two amounts are present only when `settled` is `true`. |

**Read the stream defensively.** Ignore event types and fields you do not know: new ones may be
added in any release. A new way for a run to end is a new `status` or `errorCode`, never a new
final event type. Stop reading at the event with `terminal: true`. If the stream ends without
one, read the outcome with `GET /v1/runs/{id}`. If the amounts are absent or `settled` is `false`,
read them with `GET /v1/runs/{id}`: a charge that could not be settled at once is settled within
several minutes.

The model's answer is delivered only in the stream; it is not stored.

### How a run ends

| `status` | When |
|---|---|
| `COMPLETED` | The agent finished (`reason: end_turn`), or the run reached its time limit and stopped cleanly (`reason: time`). |
| `FAILED` | The run stopped on a limit or a fault. `errorCode` names it. |
| `CANCELLED` | The run was cancelled (`errorCode: CANCELLED_BY_CALLER`), or its stream was closed (`errorCode: CLIENT_DISCONNECTED`, seen with `GET /v1/runs/{id}`). |
| `EXPIRED` | The platform ended a run that stopped reporting. |

The `errorCode` values that name a limit:

| `errorCode` | Meaning |
|---|---|
| `MAX_STEPS_REACHED` | The run used its `maxSteps` model calls. |
| `OUTPUT_LIMIT_REACHED` | A reply kept reaching the output limit of one model call. A reply cut off at that limit is first continued in a further model call, which counts toward `maxSteps`, a limited number of times per run. |
| `CONTEXT_WINDOW_EXCEEDED` | The conversation outgrew the model's context window. |
| `BUDGET_EXCEEDED` | The run's model calls would have passed its budget. |
| `TIME_LIMIT` | The run reached its hard wall-clock limit. |

On a model that reasons, a call's output limit is `maxTokensPerCall` plus an allowance for
reasoning, and reasoning counts against it. Other `errorCode` values name a fault (for example
`MODEL_ERROR` or `RUN_UNAVAILABLE`), and more may be added. The stream and `GET /v1/runs/{id}`
can name a fault differently for the same run; `GET` reports platform faults as
`RUN_UNAVAILABLE`.

### `GET /v1/runs/{id}` — read a run

Needs `runs:r` (a grant naming an agent reads only runs of that agent; any other run answers `404`). Returns `id`, `agentId`, `agentVersion`, `status`, `terminal`, `reason` (on a
completed run), `errorCode` (on any other ending), `createdAt`, `endedAt`, `steps` (the number of
model calls), `toolCalls` (each `{ toolCallId, tool, outcome, at }`, plus `script: { name, version }` naming the exact
version a script tool's call is bound to; never the arguments or result; `outcome` is
`OK`, `TOOL_ERROR`, `UNKNOWN` (a change whose result was lost: check before repeating it) or
`ABANDONED`; a call the run refused is not listed, and appears only in the stream)
and, once the run's charge is settled, `usage` with `inferenceBalanceCentsChargedMilli` and
`inferenceBalanceCentsRefundedMilli`.

A run's record is kept for at least 30 days after it ends; [`GET /v1/runs`](#get-v1runs--list-runs) lists them. A run is read in the app context it ran in: the root key reads a run in
another context by naming it with `?contextId=`, which `POST /v1/runs/{id}/cancel` also takes; a
credential confined to one context that names another gets `403`.

### `GET /v1/runs` — list runs

Needs `runs:r`. Returns a page of runs, newest first, as `{ data, nextCursor }`; each run is what
`GET /v1/runs/{id}` returns, without `usage` (read the run by its id for its charge). Pass `nextCursor`
back as `startFrom` for the next page; `limit` is 1 to 100 (default 20). A page never holds more than
`limit` runs. **A page may hold fewer runs than `limit`, or none, while `nextCursor` is present:** one
request reads only a bounded part of the runs it could list, so a filter that matches few of them (a
rare `status`, one agent of many, a grant naming one agent) returns a short page to go on from. Keep
reading until `nextCursor` is absent; do not treat a short or empty page as the end.

- **Whose runs.** A credential lists the runs it started; a token bound to a user lists that user's runs.
  It lists in its own app context (a credential not confined to one may name another with `?contextId=`).
- **The root key** sees every run, so it must name `contextId` (every run in that context), `userId`
  (the runs started by tokens bound to that user, not by keys, across your app contexts, grouped by context and newest
  first within each), or both (that user's runs in that context). Naming neither is `400`. A token
  bound to a user may name only that user; any other `userId`, or a `userId` from a credential that is
  not a token bound to a user (a key, even one tied to a user), is `403`.
- **Filters.** `status` (`RUNNING`, `COMPLETED`, `FAILED`, `CANCELLED` or `EXPIRED`; more may be added, an
  unknown value is `400`) and `agentId`.
- **A grant naming agents** (`runs:r:<agent>`) lists only runs of the agents it names.
- **Runs started before this route existed** are listed only by the root key with `?contextId=` until they
  expire, at most 30 days after they end; each can always be read by its id.

### `POST /v1/runs/{id}/cancel` — stop a run

Needs `runs:c` (a grant naming an agent reaches only runs of that agent; any other run answers `404`), and takes no body. The answer is `202` with the run still `RUNNING`. A model call
in progress is cut within a few seconds; a tool call in progress is first allowed to finish, for
up to about 45 seconds, so its change is recorded and billed, and the run stops as soon as it has.
The run then ends `CANCELLED` with `errorCode` `CANCELLED_BY_CALLER`, unless it had already
completed, in which case it stays `COMPLETED`.

A run that has ended, or had not started yet (the cancel ends it), answers `200` with its final
state, so a cancel can always be retried. A run that never started is charged nothing. A caller
with `runs:c` but not `runs:r` gets only `id`, `status`, `terminal`, `reason` and `errorCode`.

**Closing the stream is not a cancel.** The run stops on a best-effort basis when the platform next
writes to the stream and finds it closed, and ends `CANCELLED`; `GET /v1/runs/{id}` then shows
`errorCode` `CLIENT_DISCONNECTED`. If that is never noticed, the run's wall-clock limit is the hard
stop. To stop a run for certain, cancel it.

### Limits

| Limit | Value |
|---|---|
| Model calls | the agent's `limits.maxSteps` |
| Output tokens per model call | the agent's `limits.maxTokensPerCall` |
| Tool calls | the agent's `limits.maxToolCalls` |
| Data-changing tool calls | the agent's `limits.maxWrites` |
| Model spend | the agent's `budget.maxInferenceCents`, or the run's lower `budget` |
| Model spend per period, all runs of the agent | the agent's `budget.periods` (`402` `AGENT_BUDGET_EXHAUSTED`) |
| Wall clock | about 11 minutes |
| Input | 100,000 characters; a 256 KB body |
| Runs in progress | a cap per tenant and per starter (`429` `CONCURRENT_RUN_CAP`) |

### Spending

A run's budget bounds what its **model calls** cost; a run whose model calls would pass it stops
with `BUDGET_EXCEEDED`.

- **Prepaid account:** the run reserves its budget from your inference balance when it starts, is
  charged what its model calls actually cost, never more than the budget, and the rest is refunded
  when it ends.
- **Usage-billed account:** nothing is reserved, and the model calls are billed afterwards, never
  more than the budget. The stream's and the run's charged and refunded amounts read `0`.

Tool calls and run time are not part of the budget: a fixed fee per run, tool calls and run time
are billed separately, against your plan. The one exception is [`rag_ask`](#rag_ask): its answers are
model calls, so they are paid from the budget. A cancelled or interrupted model call is charged up to
its maximum. See [Pricing & usage](../pricing.md).

#### Period caps

`budget.periods` caps what all of an agent's runs together may spend on model calls per hour, day,
week or month. Periods follow the calendar at UTC-05:00, the clock of your monthly bill: an hour
starts on the hour, a day at 00:00, a week on Monday at 00:00 (ISO weeks), a month on its first day.

- A run counts in the periods it **starts** in. When it starts it reserves its whole budget against
  each of them; when it ends, what it did not spend is released. So the runs started in a period never
  commit more than the cap that was in force when each one started.
- A run that does not fit is refused before it starts with `402` `AGENT_BUDGET_EXHAUSTED`. The body's
  `period` names the full period that resets last and `resetsAt` says when; the room may also come back
  sooner, as the agent's runs in progress end. A run whose budget is larger than a cap can never fit and
  is refused with `BUDGET_EXCEEDS_PERIOD_CAP` (below).
- The caps of the agent's **newest** version apply to every run of it, including a run that names an
  older version. Lowering a cap stops new runs; it does not undo what was already spent or reserved.
- Spending is counted from the release that introduced period caps. An agent deleted with `purge` and
  created again under the same name in the same period continues that period's count.

### Errors before a run starts

Nothing is started and nothing is charged. The body is `{ message, errorCode, statusCode }`. Every
`429` and `503` carries `Retry-After`.

| Status | `errorCode` | Meaning |
|---|---|---|
| `400` | `INVALID_REQUEST` | Malformed body (including an `agentId` that is not 1 to 128 letters, digits, `_` or `-`), an inline definition, a `contextId` other than your own, or a budget above the agent's. |
| `400` | `INVALID_CREDENTIAL` | The credential could not be used to start a run. |
| `400` | `INVALID_IDEMPOTENCY_KEY` | The `Idempotency-Key` is malformed. |
| `400` / `409` | `BUDGET_TOO_LOW` | The budget (`400` when you sent it, `409` when it is the agent's own) is below the minimum or cannot cover the first model call. The message names the minimum. |
| `400` / `409` | `BUDGET_EXCEEDS_PERIOD_CAP` | The budget (`400` when you sent it, `409` when it is the agent's own, for instance a run of an older version) is larger than one of the agent's period caps, so the run could never fit. `period` and the message name the cap; send a `budget.maxInferenceCents` no larger than it. |
| `402` | `INSUFFICIENT_BALANCE` | Prepaid accounts: your balance cannot cover the budget. |
| `402` | `SUBSCRIPTION_LIMIT_EXCEEDED` | Your plan's monthly credit limit is reached. |
| `402` | `AGENT_BUDGET_EXHAUSTED` | One of the agent's [period caps](#period-caps) has no room for the run's budget. `period` and `resetsAt` say which and when it resets; room held by runs in progress comes back when they end. |
| `403` | `FORBIDDEN` | The credential lacks `runs:c` for this agent (the same answer whether or not the agent exists). |
| `403` | `RUN_REQUIRES_BOUND_USER` | A token bound to no user. |
| `403` | `AGENT_RUNS_NOT_ENABLED` | Agent runs are not switched on for the tenant. |
| `401` | — | The API key or bearer token is missing or invalid. |
| `403` | `AGENT_TOOL_NOT_ENABLED` | The agent lists a tool that is not available to the tenant (`web_fetch` while it is off, or `web_search` while it is not enabled for the platform). |
| `404` | `AGENT_NOT_FOUND` | No such agent, or no such version, in your app context. |
| `404` | `NOT_FOUND` | The request path is not `/v1/runs`. |
| `409` | `AGENT_RETIRED`, `AGENT_VERSION_PURGED` | The agent is retired, or the version was purged. |
| `409` | `AGENT_TOOL_UNAVAILABLE` | One of the agent's tools is no longer available (for a script tool: its version is gone, or declares no `inputSchema`). |
| `409` | `MODEL_NOT_AVAILABLE`, `MODEL_NOT_SUPPORTED_IN_RUNS` | The agent's model is not available to you, or not supported in runs. |
| `409` | `IDEMPOTENCY_IN_PROGRESS` | A run with this `Idempotency-Key` exists; `runId` names it. |
| `413` | `PAYLOAD_TOO_LARGE` | The body exceeds 256 KB. |
| `422` | `IDEMPOTENCY_KEY_REUSED` | The key was used with a different body. |
| `429` | `CONCURRENT_RUN_CAP`, `RUN_HOLD_CAP` | Too many of your runs are in progress, or too much budget is reserved by them. Retry after one ends. |
| `429` | `BALANCE_BUSY` | Retry shortly. Any other `429` code names one of your limits or quotas. |
| `503` | `WRITE_FROZEN`, `RUN_UNAVAILABLE`, `BALANCE_UNAVAILABLE`, `AGENT_RUNS_SWITCH_UNAVAILABLE`, `TOOL_CHECK_UNAVAILABLE`, `CREDENTIAL_CHECK_UNAVAILABLE`, … | A temporary fault, or new runs are briefly not accepted. Retry later. After `BALANCE_UNAVAILABLE`, a retry with the same `Idempotency-Key` may be answered `409` naming a run that has already ended; send a new key. |

---

## Notes & limits

- **A run cannot do anything its caller cannot do.** Its tool calls carry the caller's identity
  and permissions; the tool list only narrows them. An agent cannot be given more authority than
  the credential that starts it, and there is no way to run an agent under its own identity.
- **The agent's prompt is a steering channel for your authority.** Content a tool reads (a record,
  a document, a web page) reaches the model and can influence what it does next, within your
  permissions. List write tools only on agents that need them, keep `maxWrites` low, and use
  `readOnly: true` for runs that should only read.
- **Admission is checked once, at the start.** Your plan's limits and quotas are checked when a run
  starts; within the run, data-changing tool calls are bounded by `maxWrites`.
- `GET /v1/runs` lists a context's runs (see [List runs](#get-v1runs--list-runs)).
- **The answer is not stored.** A run's record (its metadata and tool-call outcomes) is kept for at
  least 30 days after it ends; the answer is never part of it.
- **One shot only.** A run takes one input and ends. There is no conversation thread and no
  background run that continues after the request.
- **Tool-call records keep metadata only**: a tool's name and outcome, never its arguments or
  result, except the address a `web_fetch` call read.
