---
title: "Run agents from your app"
description: "Start a BoxCompute agent from your own code with /api/v2/runs, and get a signed webhook when it finishes or needs an answer, or when a VM command ends."
---

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

# Run agents from your app

`/api/v2/runs` runs one of your workspace's agents from your own code: a site,
a script or a queue worker. It is the same agent as a chat in the app, with the
same tools, VM and AI limits, and every run appears in your chat list.
[Webhooks](#webhooks) tell your app when a run ends or stops to wait for an
answer, or when a [VM command](#vm-command-events) ends, so it never has to
poll.

Every account has single runs and webhooks. [Batches](#run-a-batch-early-access)
run the same prompt once per item and require early access.

## Create a key

In the app, open **Menu → API keys → New API key** and tick **Can run agents**.
That adds three scopes to the usual ones:

| Scope | Allows |
| --- | --- |
| `agents:read` | `GET /api/v2/agents` |
| `chat:write` | Start, stop and answer runs; start and cancel early-access batches |
| `chat:read` | Read runs, batches and batch items |

Existing keys do not gain these scopes; create a new key. A key
[limited to one workspace](/api-keys#limit-a-key-to-one-workspace) reaches only
that workspace's agents and runs.

## Start a run

```bash
curl --fail-with-body 'https://api.boxcompute.ai/api/v2/runs' \
  -H "Authorization: Bearer $BOXCOMPUTE_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: order-1234' \
  --data '{"prompt": "Build a one-page site for Kedai Kopi and publish a preview"}'
```

The response is `202` straight away, while the agent works:

```json
{
  "run": {
"id": "5d1c…",
"conversationId": "c_…",
"workspaceId": "ws_…",
"agentId": "agt_…",
"status": "running",
"source": "api",
"prompt": "Build a one-page site for Kedai Kopi and publish a preview",
"answer": null,
"answerTruncated": false,
"error": null,
"question": null,
"startedAt": 1762761600000,
"endedAt": null,
"url": "https://app.boxcompute.ai/?conversation=c_…&workspace=ws_…"
  }
}
```

Only `prompt` is required (1–100,000 characters, and the whole request body at most 128 KiB, so a long prompt in a non-Latin script can hit `413 PAYLOAD_TOO_LARGE` sooner). Optional fields:

| Field | Meaning |
| --- | --- |
| `agentId` | Which agent runs it, from `GET /api/v2/agents`. Omitted: the workspace's default agent |
| `conversationId` | Send a follow-up in that chat, which keeps its agent and model |
| `sandboxId` | Choose a VM in the selected workspace for a new chat; cannot be combined with `conversationId` |
| `workspaceId` | Omitted: your default workspace, or a workspace-limited key's own |
| `timezone` | An IANA name such as `Asia/Kuala_Lumpur`, for anything the agent dates or schedules |

Other fields return `400 INVALID_REQUEST`. Every POST on these routes needs
`Content-Type: application/json`, or it returns `415`.

A chosen VM must not be reserved for another use. The chat remembers your VM
choice; if you later delete that VM, it falls back to the workspace's default.

### Choose the agent, not the model

A run uses its agent's model; the request cannot pick one. `GET /api/v2/agents`
lists each agent's `id`, `name`, `modelId` and `isDefault`. To run on another
model, including your own model key or OpenAI-compatible endpoint, set it on
the agent in the app and pass that agent's `agentId`. Agents using a Claude,
ChatGPT or Qwen plan cannot be started through the API. Choose an agent on
another model instead.

### Retry safely

Send an `Idempotency-Key` (1–255 visible ASCII characters) to make retries
safe. The same key with the same request returns the run it already started,
even when two retries race. The same key with a different request returns
`409 IDEMPOTENCY_CONFLICT`. Without a key, every call starts a new run.

## Read, stop and answer

| Method | Route | Body | Response |
| --- | --- | --- | --- |
| `GET` | `/api/v2/runs/:id` | | `{ "run": Run }` |
| `POST` | `/api/v2/runs/:id/stop` | `{}` | `{ "run": Run, "stopped": boolean }`; `stopped` is false if the run had already ended |
| `POST` | `/api/v2/runs/:id/answer` | `{ "questionId", "answer" }` | `{ "run": Run, "delivered": boolean }`; `delivered` is false if that question was already answered, expired or the run ended |

`status` is one of:

- `running`
- `waiting`: blocked on `question` until it is answered or expires
- `completed`: `answer` holds the agent's final message
- `failed`: `error` says why
- `stopped`

`GET` reads any run in the key's workspaces, including chats started in the
app (`"source": "app"`).

### Questions and approvals

A waiting run's `question` has an `id`, a `kind` (`approval`, `question`,
`secret` or `domain`), `text` and `options`. Answer it with its `id`:

```bash
curl --fail-with-body "https://api.boxcompute.ai/api/v2/runs/$RUN_ID/answer" \
  -H "Authorization: Bearer $BOXCOMPUTE_API_KEY" \
  -H 'Content-Type: application/json' \
  --data "{\"questionId\": \"$QUESTION_ID\", \"answer\": \"Allow once\"}"
```

An approval takes exactly `Allow once` or `Deny`. A `secret` is filled in the
app only; answering one returns `409`. Answers are at most 12,000 characters.
Unanswered questions in API-started runs expire after about 10 minutes by
default. App [scheduled runs](/vm-sandbox-beta#schedule-an-agent-prompt) give
you an hour by default to answer approvals and questions.

A request cannot set the approval mode. A run follows your saved setting for
that chat, or your default in **Settings → Account**. Under **Ask first**, a
run that wants to start a VM or open a preview waits for you to answer, here
or in the chat. Choose **Full access** for an app that should never wait for
platform approvals; the agent's own questions still wait.

### Errors

Errors carry a `code`, as on [every v2 route](/limits-and-errors#handle-errors).
These are specific to runs:

| Status | Code | Meaning |
| --- | --- | --- |
| `403` or `409` | `MODEL_UNAVAILABLE` | The agent's model cannot run for this account, or runs on your Claude plan, Codex Sub or Qwen Sub |
| `409` | `RUN_IN_PROGRESS` | That conversation is still running; wait for it to end |
| `429` | `AI_LIMIT_REACHED` | Your AI limit is used up; the message says when it resets |
| `429` | `RUN_LIMIT_REACHED` | A free account's other chat is still running |
| `503` | `SERVICE_UNAVAILABLE` | AI usage could not be checked; retry with the same `Idempotency-Key` |

## Run a batch (early access)

A batch runs one prompt for each input, with a separate chat and ordinary run
for every item. Ask BoxCompute to enable early access first; otherwise creating
one returns `403 FEATURE_ACCESS_DENIED`. If access is later removed, you can
still read and cancel existing batches.

```bash
curl --fail-with-body 'https://api.boxcompute.ai/api/v2/batches' \
  -H "Authorization: Bearer $BOXCOMPUTE_API_KEY" \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: product-copy-2026-11' \
  --data '{
"prompt": "Write product copy for {{input}}. Save it in outputs/{{key}}/.",
"items": [
  {"key": "coffee", "input": {"name": "Kedai Kopi", "audience": "commuters"}},
  {"key": "tea", "input": "A loose-leaf tea shop for home brewers"}
],
"concurrency": 2
  }'
```

The response is `202` with `{ "batch": Batch }`. Creation needs `chat:write`.
Its required fields are `prompt` (1–100,000 characters) and `items` (1–500).
Each item needs a unique `key` (1–120 characters, no control characters) and
an `input`: nonempty text or an object, at most 8,000 characters after JSON
serialization. The batch-create body limit is 4 MiB, not the usual 128 KiB.

The prompt substitutes `{{key}}` and `{{input}}` once, without recursively
expanding placeholders in the input. Object inputs become JSON text. If the
prompt has no `{{input}}`, the input is appended after a blank line.
Optional `agentId`, `workspaceId`, `sandboxId` and `timezone` work as on a
single new run. The agent is fixed when the batch's first item starts.

`concurrency` is 1–10, default **3**. It is a ceiling, not reserved capacity:
normal account AI limits, simultaneous-chat limits and shared capacity still
apply. Items share the VM and filesystem, so use a separate output directory
per key rather than having every item overwrite the same file.

The first item must be admitted before creation succeeds; if it is refused,
no batch is kept. Use `Idempotency-Key` to retry the same request safely;
changing the request under that key returns `409 IDEMPOTENCY_CONFLICT`.
An account can have at most **5 active batches** (`running` or `cancelling`);
creating another returns `429 RATE_LIMITED`.

### Read batch results

| Method | Route | Scope | Response |
| --- | --- | --- | --- |
| `GET` | `/api/v2/batches/:id` | `chat:read` | `{ "batch": Batch }` |
| `GET` | `/api/v2/batches/:id/items` | `chat:read` | `{ "items": BatchItem[], "nextCursor": string \| null }` |
| `POST` | `/api/v2/batches/:id/cancel` | `chat:write` | Body `{}`; `{ "batch": Batch, "cancelled": boolean }` |

A batch has `status` `running`, `cancelling`, `completed` or `cancelled`, and
`counts` for `total`, `queued`, `running`, `completed`, `failed`, `stopped` and
`cancelled` items. **Completed means every item has ended, not that every item
succeeded.** Waiting approvals and questions count as running.

Items are returned in original order. Pass `limit` (default 50, maximum 100)
and then the returned `nextCursor` as `cursor` to page through them. Optional
`status` filters are `queued`, `running`, `completed`, `failed`, `stopped` and
`cancelled`. `waiting` can appear in an item's response but is included in the
`running` filter; it is not a separate accepted filter.

Each item has `key`, `status`, `error` and `run`. Before it starts, `run` is
`null`; afterwards, read that run's `answer` or `error`. An item that could not
start reports its own `error`. A batch item's run has `batch: { "id", "key" }`;
a standalone run has `batch: null`.

`blocked` is either `null` or `{ "reason", "since" }`, not another batch status.
A temporary admission refusal is retried; after 24 hours blocked, queued items
fail. A permanent refusal fails them immediately. Waiting for shared capacity
alone does not set `blocked` or start that 24-hour timer.

Cancelling discards queued items and asks running items to stop at the next
step. Status stays `cancelling` until they stop, then becomes `cancelled`.
The response's `cancelled` is false if the batch had ended or was already
cancelling. Cancellation does not undo files or other work already done.

## Webhooks

Open **Menu → Webhooks → New webhook** in the app and enter:

- **URL:** `https://` on the standard port 443, at a public address.
- **Events:** any of the run events below, [batch events](#batch-events) or
  [VM command events](#vm-command-events).
- **Runs**, shown when a run event is ticked: **Runs started with an API
  key**, or **Every run, including chats and schedules**. Every run sends your
  chats' prompts and answers to that URL too.

| Event | Sent when |
| --- | --- |
| `run.completed` | The run ended with an answer |
| `run.failed` | The run ended with an error |
| `run.stopped` | Someone stopped it |
| `run.waiting` | It asked a question or an approval and is waiting |

Copy the `whsec_…` signing secret when the webhook is created. It is shown only
once; **Roll secret** replaces it, and the old one stops working at once. An
account can have up to 10 webhooks.

Each delivery is a JSON POST. `data.run` is exactly what
`GET /api/v2/runs/:id` returns, except that `answer` is cut at 32,000
characters, with `answerTruncated: true`. GET the run for the whole answer.

```json
{
  "id": "evt_…",
  "type": "run.completed",
  "createdAt": 1762761654000,
  "data": { "run": { "id": "5d1c…", "status": "completed", "answer": "Published at https://…" } }
}
```

### Batch events

Select **Batches** events in the webhook form for `batch.completed` and
`batch.cancelled`. Each carries `data.batch`, the same batch view as
`GET /api/v2/batches/:id`, with final counts, not individual answers.
`batch.completed` can include failed items; fetch the items to check results.
The **Runs** selection does not filter batch events.

Batch items also send the ordinary run events above. Use `data.run.batch.id`
and `data.run.batch.key` to associate them with their batch and input.

### VM command events

The same webhooks can tell you when a command you started in a VM ends, so
your app never polls it. They cover
[observable operations](/execute#run-an-observable-operation) started with
`POST /api/v2/sandboxes/:id/operations` and the MCP server's `process_start`.
The **Runs** choice does not apply to them.

| Event | Sent when |
| --- | --- |
| `operation.completed` | The command exited, with any exit code; check `exitCode` |
| `operation.failed` | It could not run, or its VM went away |
| `operation.timed_out` | It ran past its `timeoutSeconds` |
| `operation.cancelled` | It was cancelled |

`data.sandboxId` names the VM, and `data.operation` is exactly what
`GET /api/v2/sandboxes/:id/operations/:operationId` returns. Output is not in
the event: read it from the operation's output route before `expiresAt`, 24
hours after the command ends.

```json
{
  "id": "evt_…",
  "type": "operation.completed",
  "createdAt": 1763190000000,
  "data": {
"sandboxId": "sbx_…",
"operation": { "operationId": "op_…", "state": "completed", "exitCode": 0, "finishedAt": "2026-11-15T07:00:03.000Z" }
  }
}
```

**Send test event** in a webhook's ⋯ menu posts `"type": "webhook.test"` with
`data.webhookId`.

### Verify the signature

Deliveries are signed the [Standard Webhooks](https://www.standardwebhooks.com)
way, so its libraries verify them. Each request carries:

- `webhook-id`: the event ID, the same on every retry, so deduplicate on it
- `webhook-timestamp`: Unix seconds
- `webhook-signature`: `v1,` and a base64 HMAC-SHA256 of
  `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64-decoded
  part of the secret after `whsec_`

```js
import express from "express";
import { Webhook } from "standardwebhooks";

const app = express();
const verifier = new Webhook(process.env.BOXCOMPUTE_WEBHOOK_SECRET);

app.post("/boxcompute/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const event = verifier.verify(req.body, req.headers); // throws on a bad signature or old timestamp
  queue.add(event); // do the work after answering
  res.sendStatus(204);
});
```

Verify the raw bytes before parsing JSON, and reject timestamps more than a few
minutes old.

### Delivery and retries

Answer with any 2xx within 10 seconds, then do the work. Anything else is
retried after 1, 5 and 30 minutes, then after 2 and 8 hours: six attempts over
about ten and a half hours. After that the delivery is marked failed.
Redirects are not followed.

**Recent deliveries** in the ⋯ menu shows the last 50 and why each failed, and
**Resend** sends the same event ID again. Deliveries are kept for 30 days.
Turning a webhook off drops the events it was still owed. Test events and
resends share a limit of 30 an hour per account; past it they return `429`.

## Try it end to end

About fifteen minutes, with [webhook.site](https://webhook.site) as the
receiver. It gives you a public HTTPS URL and shows each request it gets. Use
throwaway prompts: the answers land on that site.

1. Create a webhook with a webhook.site URL, keeping the four run events and
   **Runs started with an API key**. **Send test event**: webhook.site shows the three
   `webhook-*` headers, and **Recent deliveries** says Delivered.
2. Create a key with **Can run agents** and start a run that needs no VM:

```bash
   curl 'https://api.boxcompute.ai/api/v2/runs' \
 -H "Authorization: Bearer $BOXCOMPUTE_API_KEY" \
 -H 'Content-Type: application/json' \
 -H 'Idempotency-Key: test-1' \
 --data '{"prompt": "Reply with just the word pineapple."}'
```

   Seconds later `GET /api/v2/runs/:id` shows `"status": "completed"` and
   `"answer": "pineapple"`, and webhook.site has `run.completed`.
3. Send the same request again: the same run comes back and no new chat
   appears. The same key with another prompt returns `409 IDEMPOTENCY_CONFLICT`.
4. Start `"Use ask_user to ask me to pick Red or Blue, then reply with just my
   pick."`. webhook.site gets `run.waiting`, and the run's `question` lists
   both options. [Answer it](#questions-and-approvals) with `Blue`; the run
   ends with `run.completed`.
5. Start a long prompt, such as a 2,000-word story, then
   `POST /api/v2/runs/:id/stop` with `{}`. It returns `"stopped": true`, and
   webhook.site gets `run.stopped`.

Source: https://boxcompute.ai/docs/agent-runs/index.mdx
