# Runner

> The runner is the Python process convoyd starts for each agent. It runs one SDK session, gives it the swarm tools through MCP, and asks the server between turns what is new.

The runner is the piece between convoyd and an agent SDK. It runs one SDK session, attaches convoyd's MCP endpoint so the model gets the swarm tools, and calls `wake` between turns. It is deliberately thin: it decides nothing about the swarm. Every decision it appears to make (when to run, when to stop) answers something the server said. What to read is the model's decision, made through `read_topic`.

It is a Python 3.12 package, `convoy_runner`, with the executable `convoy-runner`, in the `runner/` directory of the repository. It imports no Go code; its only coupling to the rest of Convoy is the wire contract. Both agent SDKs are first-class in Python, and writing the runner in Go would mean reimplementing their tool loops.

## How convoyd starts it

You do not install the runner. Its source is embedded in the `convoyd` binary, and `convoyd` starts it through [`uv`](https://docs.astral.sh/uv/), so the runner always matches the server it came with.

1. When `convoyd` starts, it writes the embedded project (`pyproject.toml`, `uv.lock`, and the Python source) to `<runner dir>/<digest>/`. The runner dir is `--runner-dir`, by default `convoy/runner` in your user cache folder. The digest is a hash of the files, so a `convoyd` with different runner source gets its own folder.
2. Before it serves, `convoyd` runs the runner once in [check mode](#process-contract) through the launcher below. The first time, `uv` builds the environment in `<digest>/.venv`: it fetches Python 3.12 if the machine lacks it, and installs `claude-agent-sdk` and `openai-agents` at the versions in `uv.lock`. That takes about fifteen seconds on a fast connection and longer on a slow one; later starts take under a second. A runner that cannot start stops `convoyd` here, with the command's output.
3. Each agent is then started with the same launcher:

```sh
uv run --project <runner dir>/<digest> --python 3.12 --frozen --no-dev \
  --extra claude --extra openai convoy-runner --start-file start.json
```

`uv` does not change the working directory, so the agent runs in its own [work folder](#work-folders). This is the same pattern a [driver plugin](/docs/providers/writing/#a-driver-plugin) uses for its `command`: `convoyd` installs nothing itself, and the launcher builds what it needs the first time it runs.

Without `uv` on `PATH`, `convoyd` refuses to start and says how to install it. To use a runner of your own, such as a checkout you are changing, pass `--runner /path/to/convoy-runner` (or set `CONVOYD_RUNNER`): `convoyd` runs that executable directly, unpacks nothing, and needs no `uv`.

## Process contract

This is runner contract version 2. A [driver plugin](/docs/providers/writing/#a-driver-plugin)'s command implements the same contract, so everything below applies to it too.

**Invocation.** `convoy-runner --start-file start.json`, with the working directory set to the agent's folder. For a driver plugin, convoyd runs the plugin's `command` with `--start-file start.json` appended.

**Check mode.** `convoy-runner --check`, in place of `--start-file`. The runner loads its driver, confirms the SDK it drives can be imported, prints one line on stdout, and exits 0:

```json
{"contracts":[2],"runner_version":"0.2.0"}
```

It calls neither convoyd nor the provider, and gets no token and no key. Any other exit is a failed check. convoyd runs a driver plugin's command this way when a run is created and after `convoy provider pull` or `push`, which is also when the plugin installs its dependencies. The built-in runner implements check mode too, and passes when at least one built-in driver can be used; convoyd runs it once, [when it starts](#how-convoyd-starts-it).

**Environment.** `CONVOY_TOKEN` (the agent's bearer token), `PATH`, `HOME`, and one variable per `env_name` attribute of the provider's type, such as the API key. Nothing else. For a built-in type the key arrives under the SDK's standard name: `ANTHROPIC_API_KEY` for `claude_agent_sdk`, `OPENAI_API_KEY` for the other two. convoyd reads the value from the variable the provider block names in `api_key`; it never travels in the bundle.

**stdout.** Nothing, except the line of check mode.

**stderr.** One JSON object per line: `{"t": "<rfc3339>", "level": "info|warn|error", "msg": "...", ...}`. convoyd stores them as `agent.log` events in 4 KB chunks. Logged events are `start`, `turn.start`, `turn.end` (usage and the SDK's cost figure), `wake`, `nudge`, `stop` (reason), `error` (traceback), and the transcript recorder's `transcript.retry`, `transcript.dropped`, `transcript.disabled` and `transcript.flush_timeout`. Message bodies and prompts are never logged; they are on the board, in `start.json`, and in the transcript.

### start.json

The controller writes it once, in the start sequence. The runner uses these fields; the full format is on [Seams and contracts](/docs/architecture/contracts/#startjson).

| Field | Use |
| --- | --- |
| `contract` | Must be in the runner's supported set (2); otherwise exit 2 |
| `swarm.name`, `swarm.goal`, `swarm.done_when` | System prompt |
| `swarm.run_id` | Part of the OpenAI driver's session id |
| `agent.name`, `prompt`, `output_schema`, `writes`, `watches`, `tools`, `max_turns`, `can_spawn` | System prompt and driver configuration |
| `agent.provider.driver` | Driver selection: `claude_agent_sdk`, `openai_agents`, or `openai_compatible`; empty for a driver plugin, whose command is its driver |
| `agent.provider.source`, `version` | The provider type and version, for logs |
| `agent.provider.model`, `config`, `settings` | What the driver receives: the model, the type's configuration (such as `base_url` and `headers`), and the settings that are set |
| `inputs` | First turn text, when not null |
| `server.url`, `server.mcp_url` | API and MCP endpoints |

### Exit codes

| Code | Meaning | Controller treatment |
| --- | --- | --- |
| 0 | `finish` was accepted, or the server said stop | `done` or `stopped`, whichever the server already recorded |
| 1 | Unexpected error: SDK exception, network failure after retries | `failed`, `runner_error` |
| 2 | Bad invocation: `start.json` missing, invalid, or an unsupported `contract` | `failed`, `bad_invocation` |
| 3 | Reserved; unused in the MVP | treated like 1 |
| 4 | `max_turns` reached | `stopped`, `max_turns` |
| 5 | The provider refused the call for good: a key it does not accept, or an account with no credit | `failed`, `provider_error`; the run ends `failed` at once, and `convoy status` shows the provider's words |

No exit code leads to a restart. Every stop reason (`finished`, `stopped`, `max_turns`, `budget`, `swarm_ended`) exits 0 when it comes from the server, because the server already recorded why.

## Why MCP for swarm tools

The runner makes two kinds of calls and they use different paths.

- **Runner code to server: plain REST.** An `httpx` client for the calls the runner makes itself: `wake`, `GET /agents`, `GET /topics`. It retries 5 times with exponential backoff on connection errors and 5xx, never on 4xx. `wake` has a 40-second read timeout; other calls 10.
- **Model to server: MCP.** `publish`, `read_topic`, `report_progress`, `finish` and the rest are called by the model in the middle of a turn. The SDK forwards each call to `server.mcp_url` with the agent's token. The runner never sees them.

A REST client would not replace MCP, because the model can only call what the SDK registers as a tool. Without MCP each swarm tool would need a hand-written wrapper per driver, and the definitions could drift. With MCP the server declares each tool once, every SDK discovers it, validation and permissions stay on the server, and a runner in another language could use the same tools. See [Swarm tools](/docs/runtime/swarm-tools/).

## Drivers

A driver wraps one SDK behind three methods. One instance lives for the whole process, and `turn` continues the same session, so the model remembers earlier turns without the runner resending them. While a turn runs, the driver reports each block the SDK completes (text, reasoning, a tool call, a tool result) to the recorder it was started with; see [Transcripts](#transcripts).

```python
@dataclass(frozen=True)
class StartArgs:
    system_prompt: str
    model: str
    config: dict[str, Any]      # the type's configuration, defaults applied
    settings: dict[str, Any]    # this agent's settings; an unset setting is absent
    tools: list[str]
    mcp_url: str
    token: str
    swarm_tools: list[str]
    output_schema: dict | None
    cwd: Path
    session_id: str
    recorder: Recorder

class Driver(Protocol):
    async def start(self, args: StartArgs) -> None: ...
    async def turn(self, user_input: str) -> TurnResult: ...
    async def close(self) -> None: ...
    # Optional, for check mode: def check(self) -> None
```

The same protocol is the Python plugin SDK, `convoy_runner.plugin`: a driver plugin supplies a driver and calls `serve(make_driver)`, and gets the turn loop, the API client, the transcript recorder, check mode, and these exit codes. See [Writing a provider type](/docs/providers/writing/#the-code).

`TurnResult` carries the assistant's final text, a `Usage` (input, output, cache-read and cache-write tokens, and the SDK's own cost when reported), and a `Session` (`sdk_session_id`, plus `last_response_id` for the OpenAI Agents SDK). The runner sends usage and session to convoyd in the body of every `wake`. Spend is never taken from the SDK; the server prices tokens itself.

| `driver` | Package | Notes |
| --- | --- | --- |
| `claude_agent_sdk` | `claude-agent-sdk`, which runs Claude Code as a subprocess | Uses the copy of Claude Code bundled in the SDK's package (macOS and Linux), so there is nothing else to install. A `ClaudeSDKClient` keeps the session open across turns. `setting_sources=[]` ignores any `~/.claude` settings and `CLAUDE.md`, so behavior does not depend on the laptop. A permission callback allows a tool only if it is in the allowed list; everything else is denied with `not enabled for this agent`. Only the built-in tools the agent lists are put in the model's context, which keeps each agent's fixed cost low. Swarm tools are named `mcp__convoy__<tool>` |
| `openai_agents` | `openai-agents` | MCP through `MCPServerStreamableHttp`. A `SQLiteSession` in `session.db` in the work folder continues the conversation. Session id is `<run_id>:<agent name>`. Tracing is disabled. The local tools are function tools the runner implements itself; see [Local tools on the OpenAI types](#local-tools-on-the-openai-types) |
| `openai_compatible` | the same driver with `config.base_url` set | Uses the chat-completions model class. `config.headers` become the client's default headers. It has the local tools and no hosted ones; validation already rejects a hosted name for this type |

Settings reach the SDKs only when they are set: `effort` and `max_thinking_tokens` become `ClaudeAgentOptions` fields, and `temperature` and `max_tokens` become `ModelSettings` on the OpenAI agent. The SDKs are optional dependencies, the extras `claude` and `openai`. convoyd starts its built-in runner with both, and the drivers import them only when used, so a driver plugin that depends on `convoy-runner` alone pulls in neither.

### Tool name mapping

The DSL's tool names map to each SDK's own. The runner checks this table against a copy of `tools.json`, so the two cannot drift.

| DSL name | Claude Agent SDK | OpenAI Agents SDK |
| --- | --- | --- |
| `web_search` | `WebSearch` | `WebSearchTool()`, hosted |
| `bash` | `Bash` | a function tool, `bash` |
| `read_file` | `Read` | a function tool, `read_file` |
| `write_file` | `Write` | a function tool, `write_file` |
| `edit_file` | `Edit` | a function tool, `edit_file` |
| `code_interpreter` | not offered | `CodeInterpreterTool()`, hosted |
| `file_search` | not offered | `FileSearchTool()`, hosted |

Swarm tools arrive through MCP and are always allowed. `create_agent` is registered only on the MCP session of an agent with `can_spawn = true`, so other agents never see it.

### Local tools on the OpenAI types

`bash`, `read_file`, `write_file` and `edit_file` mean the same thing on every built-in type, so a swarm that lists them runs on a Claude key or an OpenAI key without a change. The Claude Agent SDK brings its own. For `openai_agents` and `openai_compatible` the runner implements them in `convoy_runner/local_tools.py` and gives the agent one function tool for each name in its `tools` list.

| Tool | Arguments | Returns |
| --- | --- | --- |
| `bash` | `command`, `timeout_seconds` (default 120, at most 600) | `exit code: N`, then stdout and stderr together. Output over 30,000 characters keeps its start and its end |
| `read_file` | `path`, `offset` (default 1), `limit` (default 2000 lines) | The text as it is, with no line numbers. When the file has more, a note at the end says where to continue |
| `write_file` | `path`, `content` | Creates the parent folders and replaces the file |
| `edit_file` | `path`, `old_string`, `new_string`, `replace_all` (default false) | Replaces one exact string. An `old_string` that is missing, or that occurs more than once without `replace_all`, is an error |

- **Folder.** Commands start in the agent's work folder and a relative path is taken from it. An absolute path is used as it is, as with the Claude tools, so agents can share a folder outside their own. Nothing confines an agent to a folder: local agents run with no sandbox on every type.
- **Processes.** Each `bash` call is a new shell in its own process group. The group is killed when the command passes its timeout, when the command returns (so nothing it started in the background outlives the call), and when the runner stops.
- **Environment.** A command gets the runner's environment without the provider keys (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`) and without the agent's convoyd token.
- **Errors.** A tool that fails returns text that starts with `error:` to the model instead of ending the turn.
- **Schemas.** On `openai_agents` the tools use strict JSON schemas, so the model sends every argument. On `openai_compatible` they are not strict, since an endpoint may not support that, and the arguments with defaults are optional. The endpoint and the model must support function calling, as they must for the swarm tools.

## The turn loop

```python
async def run(start_file) -> int:
    api    = Api(start_file.server.url, token)
    driver = make_driver(start_file.agent.provider.driver)
    recorder = Recorder(api.append_transcript)
    prompt = await build_system_prompt(start_file, api)   # fetches agents and topics once
    recorder.add("system", text=prompt)
    await driver.start(StartArgs(..., recorder=recorder))
    user_input = first_turn_text(start_file)
    turns = 0
    try:
        while True:
            if turns >= start_file.agent.max_turns:
                return 4
            recorder.begin_turn(turns + 1)
            recorder.add("input", text=user_input)
            last = await driver.turn(user_input)          # an exception is recorded as an error item
            turns += 1
            await recorder.flush()                        # at most 5 s, before every wake
            wake = await api.wake(last)                   # body: usage + session
            if wake.stop:
                return 0
            if wake.continue_:                            # no watches: keep working
                user_input = CONTINUE_TEXT + format_turn_input(wake)
                continue
            if wake.has_news:
                user_input = format_turn_input(wake)
                continue
            while True:                                   # idle: poll until news or stop
                wake = await api.wake(None)
                if wake.stop:
                    return 0
                if wake.has_news:
                    user_input = format_turn_input(wake)
                    break
    finally:
        await driver.close()
        await recorder.close()                            # flush, at most 2 s
```

- The runner never decides that the agent is done. `finish` is an MCP tool. The server marks the agent `done` when it accepts the payload, and the next `wake` returns `{stop: true, reason: "finished"}`. A `finish` whose payload fails the output shape comes back to the model as a tool error inside the same turn.
- `wake` is a `POST` because it carries the previous turn's usage and session id. The server records both, prices the turn and checks the budget.
- The runner does not fetch messages for the model. A turn's input says what is unread; the model calls `read_topic` for what it wants.
- An agent with `watches` that gets nothing after 30 seconds polls again. That is the idle state and costs no model tokens.
- An agent with no `watches` never waits. Each time it ends a turn without calling `finish`, `wake` returns at once with `continue` set, and the next turn starts with this text: "You have not called finish. Continue the work. Call finish(output) when the job is done, or, if you cannot finish, publish why to the most relevant topic and call finish with what you have." `max_turns` and the budget bound the loop. The rule is the same for one agent alone and one in a team.
- `has_news` is true when the response has at least one addressed message or a watched topic with messages the agent was not told about.

### First turn

```text
YOUR TASK
Begin. Your instructions are in the system prompt.

INPUTS                                   (only when inputs is not null)
findings (from researcher[nvidia], researcher[groq], ...):
<JSON, pretty-printed, at most 200 KB; beyond that the runner writes inputs.json
 in the work folder and says so here>

THE BOARD
<the unread summary, from GET /topics at start>
```

Later turns use the format on [Message board](/docs/runtime/board/#what-a-turns-input-looks-like).

### System prompt

The system prompt is meta prompt 2: the agent's prompt, the swarm goal and `done_when`, the agent's `writes`, `watches` and output shape, the agent list and the topic list. The lists are fetched once at start, because neither SDK lets the prompt change mid-session; later changes arrive as the `AGENTS CHANGED` line. The creating-agents section is included only when `can_spawn` is true.

## Transcripts

The runner streams each agent's transcript to convoyd for the [Web UI](/docs/runtime/web-ui/#transcripts): the system prompt, each turn's input, assistant text, reasoning, tool calls and tool results, and errors. The recorder in `transcript.py` numbers each item, cuts any field over 64 KB (256 KB for the system prompt) and marks it truncated, and sends batches in the background, so a slow server never slows the model. A batch goes out after 250 ms, 32 items or 256 KB, whichever comes first.

A transcript failure never fails the agent. A batch that fails with a server or network error is retried 3 times, then dropped and logged as `transcript.dropped`. A refused token stops sending, and a convoyd without the transcript endpoint turns recording off. The loop flushes before every `wake`, so a turn's items are stored before the server records the turn's end, and again at shutdown.

## Work folders

convoyd creates `.convoy/work/<swarm>/<run>/<agent>/` and starts the runner there. Only agents that list `bash` can run shell commands. The folder, `start.json` and `session.db` stay in place when the runner exits, and `convoyd gc` removes them for ended runs.

## Shutdown

The controller sends stop through `wake` and waits 5 seconds. If the runner is inside a model turn it cannot act until the turn ends, so the controller then sends `SIGTERM` to the process group. The runner cancels the current turn, closes the driver, flushes the transcript (at most 2 seconds) and exits 0. The usage of a turn cancelled this way is never reported, so the run's recorded spend omits it.

## Failure behavior

The MVP does not recover agents. If the runner dies for any reason, the controller marks the agent `failed`, the swarm continues without it, and the overseer is told on `system`. If convoyd itself dies, its runners stop within about two seconds: each one checks every two seconds whether its parent has changed and whether anything still reads its log pipe, which convoyd does. The second check is what reaches a runner started through `uv`, whose parent is `uv` rather than convoyd. The runner reports the SDK session id on every `wake` and leaves the work folder and `session.db` in place, so [post-MVP recovery](/docs/runtime/durability/) can resume the real session.

## Fallback plan

If wrapping the two SDKs costs more than it saves, the drivers are replaced by a Go loop over the raw Anthropic Messages API and OpenAI Chat Completions API, about 300 lines. That loses the SDKs' built-in web search and bash tools. If MCP proves too costly, the alternative is generated function-tool wrappers from the server's OpenAPI spec, one per SDK.
