# Agents & runs — how-to

Short, goal-oriented guides for storing an agent and running it. Every example uses synthetic
data. For every field, limit and error code, see the [reference](./reference.md).

The examples call the API over HTTP with `curl`, because a run's answer is a Server-Sent Events
stream that is easiest to see raw. The SDKs (0.49 and later) expose the same operations on their
`agents` sub-client, spelled in each language's convention (`createRun` in TypeScript and Java,
`create_run` in Python). From the command line, `vectros agents` manages stored agents
([CLI](../clients/cli.md#command-catalog)), and a blueprint can declare them in its `agents` section
([blueprints](../clients/blueprints.md#agents)). From an MCP client, the MCP server's `agent_list`,
`agent_run` and `run_get` tools run your stored agents ([MCP](../clients/mcp.md#the-26-tools)).

```bash
export VECTROS_API=https://api.vectros.ai
export VECTROS_KEY=ssk_...   # a scoped key; see "Get a key that can run agents" below
```

The two switches below are in the developer portal, under **Settings → Agent runs**. Each is also a
developer-portal API call, shown with each step; `$DEVELOPER_TOKEN` is an account owner's
developer-portal session token, as in the webhook guide in
[Operations and trust](../operations-trust/how-to.md).

---

## Turn agent runs on

Agent runs are off for every tenant until an account owner turns them on, separately for the live
and the test environment. Until then, `POST /v1/runs` answers `403` with `errorCode`
`AGENT_RUNS_NOT_ENABLED`. You can store and version agents before runs are on.

Only an account owner can turn it on. In the developer portal, open **Settings → Agent runs**,
choose **Test** or **Live**, and turn on **Agent runs**. Or with the developer-portal API:

```bash
curl -X PATCH "$VECTROS_API/developer/agent-runs?tenant=test" \
  -H "Authorization: Bearer $DEVELOPER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "enabled": true }'
```

**Expected result:** `200` with `{ "tenant": "test", "enabled": true }`. Repeat with `tenant=live`
for your live environment. `GET /developer/agent-runs?tenant=live` reads the current state.

---

## Get a key that can run agents

Give the credential only what it needs:

- to **store** agents: `agents:c`, plus `agents:r` to read them back and `agents:u` to write new
  versions;
- to **run** them: `runs:c`, plus `runs:r` to read a run afterwards. To let a role run only some agents, name each one:
  `runs:cr:incident-investigator` starts that agent and reads your own runs of it, and no other.

A credential with `runs:c` can list the agents its grant covers (`GET /v1/agents`) in a summary
view, without seeing their prompts or tools, so the credential that runs agents does not need
`agents:r`. See [Identity and access](../identity-access/how-to.md) for minting a scoped key.

---

## Store an agent

```bash
curl -sS -X POST "$VECTROS_API/v1/agents" \
  -H "Authorization: Bearer $VECTROS_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "ticket-summarizer",
    "description": "Summarizes a support ticket and the notes on it",
    "model": "claude-sonnet-5-5",
    "system": "You summarize support tickets. Read the ticket record, then answer in three short bullet points.",
    "tools": [
      { "name": "records_get" },
      { "name": "search_content" }
    ],
    "limits": { "maxSteps": 6, "maxToolCalls": 8 },
    "budget": { "maxInferenceCents": 25 }
  }'
```

The answer is `201` with the agent at version 1 and every default filled in. Keep its `id`.

- The prompt field is **`system`**. An unknown top-level field is ignored, so a misspelt prompt
  field stores an agent with an empty prompt; read the agent back once to check.
- Sending the same `name` again returns the stored agent unchanged (`200`, `created: false`) when
  your credential can read it (`agents:r`); otherwise the answer is `400`. To
  make a create converge on your definition, send `POST /v1/agents?upsert=true` (needs
  `agents:u` as well): it writes a new version only when the definition differs.

---

## Run it and read the stream

```bash
curl -sS -N -X POST "$VECTROS_API/v1/runs" \
  -H "Authorization: Bearer $VECTROS_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: ticket-4711-summary-1" \
  -D - \
  -d '{
    "agentId": "<agent id>",
    "input": { "text": "Summarize ticket 4711." }
  }'
```

The response headers carry `X-Vectros-Run-Id`; keep it. The body is a stream of events, each an
`event: run.event` frame with a JSON `data` line. Events the run records also carry an `id:` line;
a `message.delta` carries the `seq` of the `message.completed` it belongs to:

```text
id: 1
event: run.event
data: {"type":"run.started","runId":"<run id>","seq":1,"terminal":false,"agentId":"<agent id>","agentVersion":1}

event: run.event
data: {"type":"message.delta","runId":"<run id>","seq":2,"terminal":false,"text":"I'll read the ticket first."}

id: 2
event: run.event
data: {"type":"message.completed","runId":"<run id>","seq":2,"terminal":false,"step":1,"text":"I'll read the ticket first."}

id: 3
event: run.event
data: {"type":"tool.completed","runId":"<run id>","seq":3,"terminal":false,"step":1,"toolCallId":"tc-1-0","tool":"records_get","outcome":"OK"}

: keepalive

id: 5
event: run.event
data: {"type":"run.completed","runId":"<run id>","seq":5,"terminal":true,"status":"COMPLETED","reason":"end_turn","settled":true,"inferenceBalanceCentsChargedMilli":3120,"inferenceBalanceCentsRefundedMilli":21880}
```

(The ids, counts and amounts above are illustrative.) To read the stream reliably:

1. Read each event's `type`, and **ignore types and fields you do not know**; new ones can be added
   in any release.
2. Show `message.delta` text as it arrives; `message.completed` carries one model call's complete
   text.
3. Skip comment lines that start with `:` (keepalives).
4. **Stop at the event with `terminal: true`.** Its `status` and `errorCode` say how the run ended.
5. If the stream ends without a terminal event, or the terminal event has `settled: false`, read
   the run with `GET /v1/runs/{id}`.

The answer is delivered only in the stream; it is not stored. Save it yourself if you need it.

---

## Retry a start safely

Send an `Idempotency-Key` on every start. If the request fails or the connection drops before you
see the `X-Vectros-Run-Id`, retry with the **same key and exactly the same body bytes** (keep the
serialized body; do not rebuild it). If the first request started a run, no second run is started:
the retry answers `409` `IDEMPOTENCY_IN_PROGRESS` with the first run's id in `runId` and in the
`X-Vectros-Run-Id` header, and you read that run with `GET /v1/runs/{id}`. If the first request was
refused before a run began, the retry is evaluated afresh. To start a new run, use a new key.

---

## Read a run afterwards

```bash
curl -sS "$VECTROS_API/v1/runs/<run id>" -H "Authorization: Bearer $VECTROS_KEY"
```

You get the run's `status`, the agent version it ran, the number of model calls (`steps`), the
name and outcome of each tool call that ran (a call the run refused appears only in the stream),
and, once settled, what it was charged (`usage`). The model's answer is not included. A run's record
is kept for at least 30 days after it ends. Only whoever started it can read it (the key, or the user a token
is bound to), and the tenant's root key; the root key adds `?contextId=` for a run in another app
context.

---

## Stop a run

```bash
curl -sS -X POST "$VECTROS_API/v1/runs/<run id>/cancel" -H "Authorization: Bearer $VECTROS_KEY"
```

The answer is `202` while the run stops: a model call in progress is cut within a few seconds, and
a tool call in progress is allowed to finish (up to about 45 seconds) so its change is recorded.
The run then ends `CANCELLED`. A run that has already ended answers `200` with its final state, so
you can repeat the cancel safely.

Closing the stream is not a cancel: the run stops only when the platform next writes to the stream
and finds it closed, and otherwise runs to its wall-clock limit. Cancel when you need the run to
stop.

---

## Let an agent write

A tool that changes data must be listed with `allowWrites: true`, and the agent needs a
`maxWrites` of at least 1:

```json
{
  "name": "ticket-triager",
  "model": "claude-sonnet-5-5",
  "system": "Read the ticket and set its priority field to low, normal or high.",
  "tools": [
    { "name": "records_get" },
    { "name": "records_update", "allowWrites": true }
  ],
  "limits": { "maxSteps": 4, "maxToolCalls": 4, "maxWrites": 1 }
}
```

Each write is made with the authority of the credential that starts the run, and is refused
exactly as the API would refuse it for that credential. Keep `maxWrites` as low as the job allows.
To run a write-capable agent without letting it write, start the run with `"readOnly": true`.

---

## Change an agent without breaking running callers

Every change writes a new version; earlier versions are never edited.

1. Read the agent and note its `latestVersion`.
2. `PUT /v1/agents/{id}` with the **whole** definition and `"expectedVersion": <latestVersion>`.
   A field you leave out takes its default; nothing is carried over. If someone else wrote a
   version in between, the update is refused with `409` `VERSION_CONFLICT`: read again and retry.
3. Callers that must not pick up the change yet can pin a version with `"agentVersion": N` in
   `POST /v1/runs`.

To take an agent out of use, `DELETE /v1/agents/{id}` retires it: it stays readable, can no longer
run, and its name stays reserved. `PUT /v1/agents/{id}?restore=true` brings it back with the body
as its next version.

---

## Read a web page in a run

`web_fetch` reads one public web page and returns its text. It is off until an account owner turns
it on for the tenant: the **Web fetch tool** switch under **Settings → Agent runs** in the developer
portal, or with the developer-portal API:

```bash
curl -X PATCH "$VECTROS_API/developer/agent-tools?tenant=test" \
  -H "Authorization: Bearer $DEVELOPER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "toolClasses": { "web_fetch": true } }'
```

An account under a business associate agreement must also have accepted the web fetch enablement,
shown under the switch in the developer portal; until then turning it on answers `409`
`ACCEPTANCE_REQUIRED`. Then list it like any other tool:

```json
{ "name": "web_fetch" }
```

The page is fetched by a third-party web-fetch provider, and the address is kept in the run's
tool-call record. Use it for public pages only, and never let personal, patient or account
information reach the address: say so in the agent's `system` prompt as well.

---

## Answer questions from your content in a run

List `rag_ask`, and give the run's key `inference:r` as well as read access to the content it should
answer from. The agent asks a question; the tool searches what the key can read, and Claude Haiku 5.5
writes an answer from what it found, returned with its sources:

```json
"tools": [{ "name": "rag_ask" }],
"budget": { "maxInferenceCents": 50, "ragMaxInferenceCents": 20 }
```

Each answer is a model call paid from the run's budget. `ragMaxInferenceCents` (optional) caps what all
of one run's `rag_ask` answers may cost together, so a run keeps room for its own model calls. A call has
30 seconds for the search and the answer; an answer not back by then ends the call with a tool error
and is charged up to its maximum. The
[reference](./reference.md#rag_ask) has the arguments and the result.

---

## Cap what an agent spends per day or month

Add `budget.periods` to the definition. This agent may spend at most 25 cents per run, 5 dollars a
day and 50 dollars a month, across all of its runs:

```json
"budget": {
  "maxInferenceCents": 25,
  "periods": [
    { "period": "DAY", "maxInferenceCents": 500 },
    { "period": "MONTH", "maxInferenceCents": 5000 }
  ]
}
```

Each run reserves its 25 cents against the day and the month when it starts and gets back what it did
not spend when it ends. Once a period has no room, starts are refused with `402`
`AGENT_BUDGET_EXHAUSTED` until it resets (`resetsAt`) or a run in progress ends. Read what has been
spent with `GET /v1/agents/{id}`: its `periodUsage` lists each capped period and the month. Periods run
at UTC-05:00, the clock of your monthly bill. The [reference](./reference.md#period-caps) has the details.

---

## Handle a run that could not start

A refused start returns JSON (`message`, `errorCode`, `statusCode`), starts nothing and charges
nothing. The ones to plan for:

| `errorCode` | What to do |
|---|---|
| `AGENT_RUNS_NOT_ENABLED` | Ask an account owner to turn agent runs on for this environment (**Settings → Agent runs** in the developer portal). |
| `AGENT_TOOL_NOT_ENABLED` | The agent lists a tool that is not available: turn `web_fetch` on (above), or remove the tool from the agent. `web_search` has no account-owner switch: while it is not enabled for the platform, remove it. |
| `INSUFFICIENT_BALANCE` | Prepaid accounts: top up, or send a lower `budget.maxInferenceCents`. |
| `BUDGET_TOO_LOW` | Raise the budget to at least the minimum the message names. |
| `AGENT_BUDGET_EXHAUSTED` | One of the agent's period caps is full: wait for `resetsAt`, or for one of its runs to end. |
| `BUDGET_EXCEEDS_PERIOD_CAP` | The run's budget is larger than a period cap: send a `budget.maxInferenceCents` no larger than the cap the message names (or, `409`, update the agent). |
| `CONCURRENT_RUN_CAP`, `RUN_HOLD_CAP` | Wait for one of your runs to end, then retry; honour `Retry-After`. |
| `BALANCE_BUSY`, `WRITE_FROZEN`, other `503` codes | Retry after `Retry-After`, with the same `Idempotency-Key`, except after `BALANCE_UNAVAILABLE`: retry with a new key. |

The full table is in the [reference](./reference.md#errors-before-a-run-starts).
