# Introduction > Convoy is a declarative language and a runtime for long-horizon agent swarms. You describe a team of agents in HCL; a server runs it until the goal is met or a limit is hit. Today's agent harnesses are built around one person in one session. When a job needs more than one agent, you either type "launch a sub-agent" into that session and hope, or you write Python against an agent SDK, at which point **your script is the orchestrator**. If you need it to survive a long run, you add Temporal, and now you have two systems with two ideas of state, and the agents still cannot talk to each other. Convoy treats a swarm the way Terraform treats infrastructure and Kubernetes treats workloads: you **declare** what should exist, and a long-running server makes it so. ```hcl title="main.cvy" swarm "edge_chips" { goal = "Ship a sourced 10-page market report on edge inference chips" done_when = agent.critic.output.approved == true max_runtime = "4h" max_cost_usd = 60 } agent "researcher" { for_each = toset(["nvidia", "groq", "cerebras", "tenstorrent"]) provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/research.md") writes = [topic.findings] } ``` ## What you get - **One language, one agent to many.** A solo agent and a twelve-agent swarm are the same kind of file, run by the same server, the same way. - **Native swarm primitives.** Topics and messages, typed outputs, dependency edges, and spawning are part of the language, not prompts. - **A runtime that holds the state.** `convoyd` keeps every swarm, agent, topic and message. The CLI exits; the swarm keeps running. - **A control loop.** A controller enforces the budget, the runtime limit, turn limits and stuck detection. An overseer agent judges progress and can add or redirect agents. - **Any provider.** Claude Agent SDK, OpenAI Agents SDK, or any OpenAI-compatible endpoint, through one MCP tool surface. ## The pieces | Piece | What it is | | --- | --- | | [The DSL](/docs/dsl/) | HCL with four block types: `swarm`, `provider`, `topic`, `agent`. Files end in `.cvy`. | | [The CLI](/docs/cli/) | `convoy`, a single Go binary. It never holds state: it validates files and calls the server. | | [The runtime](/docs/runtime/) | `convoyd`, a Go server with a message board, a controller, an overseer and one runner process per agent. | | [The architecture](/docs/architecture/) | How the components fit, which seams are contracts, and how the repository is laid out. | These docs describe the MVP specification as of 2026-11-05. Pages and features marked are designed but not part of the first release. Durability across crashes is the main one. ## Where to go next --- # Install > Install the convoy CLI and the convoyd server, set a provider key, and start the server. Convoy ships as two Go binaries. `convoy` is the CLI. `convoyd` is the server that holds every swarm. `convoyd` carries a third piece, the Python runner `convoy-runner`, which is the process it starts for each agent. ## Requirements | Requirement | Needed for | | --- | --- | | macOS or Linux, on arm64 or x86_64 | The release binaries, and the copy of Claude Code that the Claude Agent SDK brings | | Go 1.25 or newer | Only when building `convoy` and `convoyd` from source | | [`uv`](https://docs.astral.sh/uv/), on convoyd's `PATH` | The runner. convoyd carries the Python runner inside its binary and starts it through `uv`, which fetches Python 3.12 and the agent SDKs the first time. Driver plugins written in Python start the same way | | `git`, on convoyd's `PATH` | Swarms that use a [provider type](/docs/providers/) from a repository. convoyd fetches types with it | | A provider API key | Every provider you declare, set in `convoyd`'s environment | You do not install Python, the agent SDKs, or Claude Code yourself. The Claude Agent SDK brings its own copy of Claude Code on macOS and Linux. ## Install the binaries The install script downloads the latest release for your platform, checks its checksum, and puts `convoy` and `convoyd` in `~/.local/bin`: ```sh curl -fsSL https://raw.githubusercontent.com/convoyharness/convoy/main/install.sh | sh ``` `CONVOY_INSTALL_DIR` chooses another folder, and `CONVOY_VERSION` a release other than the latest, such as `v0.1.0`. The archives themselves are on the [releases page](https://github.com/convoyharness/convoy/releases), one per platform, with a `checksums.txt`. With Go, build both from source instead: ```sh go install github.com/convoyharness/convoy/cmd/convoy@latest github.com/convoyharness/convoy/cmd/convoyd@latest ``` From a checkout, build them in place: ```sh go build -o bin/ ./cmd/convoy ./cmd/convoyd ``` Both are single executables. `convoy version` and `convoyd --version` print the release they were built from. `convoy` never holds state. It reads the files in the current folder or calls the `convoyd` API, and exits. `convoyd` is the only long-running process. ## The runner comes with convoyd There is no runner to install. The Python runner, `convoy-runner`, is inside the `convoyd` binary. The first time `convoyd` starts, it unpacks the runner into your user cache folder (`~/Library/Caches/convoy/runner` on macOS, `~/.cache/convoy/runner` on Linux) and has `uv` build its environment: Python 3.12, `claude-agent-sdk`, and `openai-agents`. ```console $ convoyd 09:06:24 INFO preparing the built-in runner: the first start downloads the agent SDKs and can take a minute 09:06:38 INFO the built-in runner is ready seconds=14 ``` That first start takes about fifteen seconds on a fast connection and longer on a slow one, and leaves about 450 MB on disk, most of it the copy of Claude Code that the Claude Agent SDK brings. Later starts take under a second. `convoyd` does this before it serves, so a swarm never waits on it, and a problem with the runner stops `convoyd` at start instead of failing your first agent. If `uv` is not on `PATH`, `convoyd` says so and exits. Install it with `curl -LsSf https://astral.sh/uv/install.sh | sh` or `brew install uv`. To run a runner of your own instead, such as a checkout you are changing, pass `--runner /path/to/convoy-runner` or set `CONVOYD_RUNNER`. `convoyd` then runs that executable as it is, and needs no `uv`. `--runner-dir` moves the folder the built-in runner is unpacked into. The same Python package is the SDK that [driver plugins](/docs/providers/writing/#a-driver-plugin) build on; they depend on `convoy-runner` without the agent SDKs and bring their own. ## Set provider keys A `provider` block names an environment variable; it never contains a key. `convoyd` reads that variable from its own environment when it starts a runner and passes the value into the runner's environment. Keys are not stored in the swarm bundle or the database, and no endpoint returns them. ```sh export ANTHROPIC_API_KEY=sk-ant-... export OPENAI_API_KEY=sk-... ``` If a provider omits `api_key`, the SDK's default variable is used: `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`. `convoy run` is refused with `missing_env` if a declared variable is not set in `convoyd`'s environment. Set the keys in the shell that starts `convoyd`, not the shell that runs `convoy`. ## Start convoyd ```sh convoyd ``` With no flags, `convoyd` listens on `127.0.0.1:7070`, keeps its database in `./convoy.db` and agent work folders under `./.convoy/`, and serves the [Web UI](/docs/runtime/web-ui/) at the same address. On a terminal it prints where it is listening, which runner it uses, and which provider keys it found. | Flag | Environment | Default | Meaning | | --- | --- | --- | --- | | `--port` | `CONVOYD_PORT` | `7070` | Listen port | | `--db` | `CONVOYD_DB` | `./convoy.db` | SQLite file holding specs, events and messages | | `--work-dir` | `CONVOYD_WORK` | `./.convoy/work` | Root of agent work folders | | `--runner` | `CONVOYD_RUNNER` | the runner inside `convoyd`, started through `uv` | A runner executable to use instead | | `--runner-dir` | `CONVOYD_RUNNER_DIR` | `/convoy/runner` | Where the built-in runner is unpacked | | `--token` | `CONVOYD_TOKEN` | empty | Token the CLI must present. Empty means requests from loopback need none | | `--public-url` | `CONVOYD_PUBLIC_URL` | `http://127.0.0.1:` | Address runners use to reach `convoyd` | | `--max-processes` | `CONVOYD_MAX_PROCESSES` | `50` | Most runner processes alive at once, overseers included. Extra agents wait in Pending | | `--provider-dir` | `CONVOYD_PROVIDER_DIR` | `./.convoy/providers` | Where driver plugin packages are kept | | `--overseer-provider` | | none | Built-in provider type for the default overseer: `claude_agent_sdk`, `openai_agents` or `openai_compatible` | | `--overseer-model` | | none | Model for the default overseer | A swarm's own `overseer` attribute wins over the two overseer flags. A run with neither is refused. See [the overseer](/docs/concepts/overseer/). The full server reference is on [convoyd](/docs/runtime/). ## Point the CLI at the server The CLI talks to `http://localhost:7070` unless told otherwise. Set `CONVOY_URL`, or pass `--server` on any command. ```sh export CONVOY_URL=http://localhost:7070 export CONVOY_TOKEN=... # only if convoyd was started with --token ``` `--dir ` selects the folder of `.cvy` files; the default is the current folder. ## Next Run a swarm in five minutes with the [quickstart](/docs/quickstart/), or write one by hand in [your first swarm](/docs/first-swarm/). --- # Quickstart > Install Convoy, start the server with one API key, and run your first swarm, in about five minutes. This guide installs Convoy and runs the smallest example, [writer and critic](/docs/examples/writer-critic/): two agents in a loop that ends when the critic approves. You need macOS or Linux, [uv](https://docs.astral.sh/uv/), and an Anthropic or OpenAI API key. ### Install The script installs two binaries: `convoy`, the CLI, and `convoyd`, the server. ```sh curl -fsSL https://raw.githubusercontent.com/convoyharness/convoy/main/install.sh | sh ``` To build from source instead, or to see what else `convoyd` needs, read [install](/docs/install/). ### Start the server `convoyd` holds every swarm and starts one process per agent. It reads provider keys from its own environment; a swarm names the variable and never contains the key. ```sh export ANTHROPIC_API_KEY=sk-ant-... # or: export OPENAI_API_KEY=sk-... convoyd ``` The first start takes longer, about fifteen seconds on a fast connection, while `uv` downloads Python and the agent SDKs. Leave it running. ### Get the example In a second terminal: ```sh git clone https://github.com/convoyharness/convoy cd convoy/examples/writer_critic ``` The folder is the swarm: [`main.cvy`](/docs/examples/writer-critic/#the-swarm-file) and one Markdown prompt per agent. As written it uses an Anthropic key. For an OpenAI key, change the two lines of the `provider` block to the values in their comments: ```hcl title="main.cvy" provider "llm" { source = "openai_agents" model = "gpt-6.1-sol" } ``` ### Run it `convoy run` validates the folder, sends it to the server, prints the run and exits. The swarm keeps running on the server. ```console $ convoy run swarm "writer_critic" run 1 accepted: 3 agents pending AGENT STATUS PROVIDER MODEL critic pending llm claude-sonnet-5-5 overseer pending llm claude-sonnet-5-5 writer pending llm claude-sonnet-5-5 watch with: convoy watch writer_critic ``` ### Watch it `convoy watch` shows the agents and the message board live, and prints the result when the run ends. ```console $ convoy watch writer_critic swarm writer_critic run 1 DONE elapsed 00:00:39 / 10m spend $0.10 / $1.00 AGENT STATUS TURNS PROVIDER SPEND LAST PROGRESS critic done 3 llm $0.04 Approved the revision at 9/10 writer stopped 2 llm $0.03 Revised the draft from the critic's note overseer stopped 2 llm $0.03 run 1 ended: DONE result critic approved true score 9 final A race condition happens when a program's result depends on ... ``` `convoy ui writer_critic` opens the same run in the browser: the graph, the board, and every agent's transcript. If the key is wrong or its account has no credit, the run ends within seconds as `FAILED`, and the same two commands say why: ```console run 1 ended: FAILED failed critic, writer the provider's account has no credit ("Credit balance is too low"). Add credit to the account ANTHROPIC_API_KEY belongs to, then run the swarm again. ``` ## What just happened 1. The server created three agents: the two you declared and the overseer. 2. Neither the writer nor the critic has `inputs`, so both started at once. The critic found nothing to review and ended its turn. 3. The writer published a draft to `drafts`. The critic `watches` that topic, so the message gave it a turn. 4. The critic published its notes to `review`, which woke the writer. The loop is nothing more than those two `watches`. 5. The critic called `finish` with `approved = true`. `done_when` became true and the run ended **Done**, well inside its one-dollar and ten-minute limits. ## Next --- # Your first swarm > Write the edge_chips market-report swarm by hand, one block at a time, then validate, run and watch it. This tutorial builds the swarm from the [introduction](/docs/) from an empty folder. Each step adds one kind of block and explains the decision behind it. The finished file is about 60 lines. You need `convoy` and `convoyd` installed and running; see [Install](/docs/install/). ### Declare the swarm Create a folder with `main.cvy` and a `prompts/` directory. Every `*.cvy` file in the folder is merged into one configuration, so file boundaries are yours to choose. The `swarm` block is the only required block, and there is exactly one. Its label is the swarm's name; the server keys swarms by it. `goal` is shown to every agent. `done_when` is the condition the server checks to end the run, here that the critic approved. `max_runtime` is required. `max_cost_usd` is optional, but without it nothing bounds spend except time, and `convoy validate` warns. The `overseer` is the built-in agent that watches the team. ```hcl title="main.cvy" swarm "edge_chips" { goal = "Ship a sourced 10-page market report on edge inference chips" done_when = agent.critic.output.approved == true max_runtime = "4h" max_cost_usd = 60 overseer = { provider = provider.anthropic, model = "claude-sonnet-5" } } ``` ### Declare providers A provider names a [provider type](/docs/providers/) with `source`, which decides which agent SDK drives the model, and says where its key lives. `api_key` is the name of an environment variable in `convoyd`'s environment, never the key. Declare one provider per type you use; this swarm uses two so the writer can run on a different model family from the critic. ```hcl title="main.cvy" provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" } provider "openai" { source = "openai_agents" api_key = "OPENAI_API_KEY" } ``` ### Declare topics Topics are the channels of the message board. Each needs a one-line `description`, which every agent sees in its topic list. Keep one topic per kind of message: facts, drafts, feedback, and a topic for questions only a person can answer. ```hcl title="main.cvy" topic "findings" { description = "One sourced fact per message, with URL" } topic "drafts" { description = "Report drafts, newest wins" } topic "review" { description = "Critic feedback on drafts" } topic "human" { description = "Questions that need a person" } ``` ### Fan out the researchers `for_each` creates one agent per element: `researcher[nvidia]`, `researcher[groq]`, and so on. `each.key` reaches the prompt through `vars`, so one prompt file serves all four; inside the file, `{{vendor}}` is replaced. The researchers have no `inputs` and no `depends_on`, so they start as soon as the run starts. `writes` is the only topic they may publish to. `tools` lists built-in tools of the provider's SDK. `max_turns` caps the agent. ```hcl title="main.cvy" agent "researcher" { for_each = toset(["nvidia", "groq", "cerebras", "tenstorrent"]) provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/research.md") vars = { vendor = each.key } tools = ["web_search", "bash"] writes = [topic.findings] max_turns = 40 } ``` ### Add the writer The writer needs the researchers' finished work, so it declares `inputs`. Each value must reference another agent's output. The writer starts only after every referenced agent has finished, and receives the values as JSON in its first turn. `values(agent.researcher)[*].output` collects the output of all four instances. `watches = [topic.review]` gives the writer another turn each time the critic publishes feedback. `writes = [topic.drafts]` is where its drafts go. ```hcl title="main.cvy" agent "writer" { provider = provider.openai model = "gpt-6.1-sol" prompt = file("prompts/writer.md") inputs = { findings = values(agent.researcher)[*].output } writes = [topic.drafts] watches = [topic.review] } ``` ### Add the critic The critic watches `drafts` and writes `review`. Together with the writer it forms a loop on the board: draft wakes critic, review wakes writer. The dependency graph has no cycle, because `inputs` runs only from researchers to writer. The critic declares an `output` shape. `done_when` reads `agent.critic.output.approved`, and validation requires that field to exist in a declared `output`. The critic ends the run by calling `finish` with `{ approved = true, score = 8 }`. ```hcl title="main.cvy" agent "critic" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/critic.md") watches = [topic.drafts] writes = [topic.review] output = { approved = bool, score = number } } ``` ### Write the prompts Each prompt file says the agent's job, what it must publish and where, and what its `finish` output must contain. Prompt files are plain text; use `vars` for substitution. A minimal `prompts/research.md`: ```text title="prompts/research.md" Find sourced facts about {{vendor}}'s edge inference chips: models, performance and power figures, pricing, customers. Publish one fact per message to findings, with the URL. When you have covered all five areas, call finish with a list of the facts you consider strongest. ``` Write `writer.md` and `critic.md` the same way. Convoy wraps each in a system prompt that adds the goal, the other agents and the board mechanics, so the file only needs the job. ### Validate, run, watch `convoy validate` runs offline and checks every rule: references, types, cycles, prices, files. ```console $ convoy validate main.cvy:31: warning: agent "writer" watches topics and keeps the default max_turns (50) ``` `convoy run` validates again, sends the folder to `convoyd`, prints the run number and exits. The swarm keeps running on the server. ```console $ convoy run swarm "edge_chips" accepted: run 1, 7 agents pending $ convoy watch edge_chips $ convoy say edge_chips human "Skip Tenstorrent, focus on the other three" ``` ## Where to go next - [Swarms and runs](/docs/concepts/swarms/) and [agents and turns](/docs/concepts/agents/) explain what the server does with this file. - The [DSL reference](/docs/dsl/) lists every attribute and validation rule. - [`convoy goal`](/docs/cli/goal/) generates a file like this from a sentence. --- # Swarms and runs > A swarm is a named declaration; a run is one execution of it. Files start a swarm, and the server holds its state. A **swarm** is the set of agents, topics and limits declared by a folder of `.cvy` files. A **run** is one execution of that swarm on the server. The swarm is the name; the run is what happens. ## Swarms are keyed by name The label on the `swarm` block is the swarm's name: `swarm "edge_chips"` is `edge_chips` everywhere. `convoy run` sends the files to `PUT /v1/swarms/edge_chips`. Every other command, such as `convoy status edge_chips`, addresses the swarm by that name. Exactly one `swarm` block must exist across all files in the folder. ## One active run at a time Each `convoy run` starts a new run with the next run number. A swarm has at most one active run, meaning one that is Pending or Running. - `convoy run` on a swarm with an active run is refused with `swarm_active`. Wait for the run to finish, or [`convoy stop`](/docs/cli/stop/) it. - `convoy run` on a swarm whose latest run has ended starts run N+1. - A running swarm's spec never changes. Applying edits to a live run is post-MVP. ## History Finished runs are kept. `convoy status edge_chips` shows the latest run; `convoy status edge_chips --run 1` shows an earlier one. `--json` prints the same data for scripts. Each run keeps its own spec, spend, agents, outputs and event log, so comparing two runs of the same swarm is a matter of reading two rows. ## Run status and end reasons A run is Pending until the controller's first pass, then Running, then one of three terminal states. Terminal runs carry an end reason. | Status | End reason | Meaning | | --- | --- | --- | | Done | `done` | `done_when` became true | | Stopped | `budget` | Spend reached `max_cost_usd`. Outputs already produced are kept | | Stopped | `max_runtime` | Wall-clock time reached `max_runtime` | | Stopped | `stopped` | Someone ran `convoy stop` | | Failed | `failed` | Every agent ended and `done_when` was still false | | Failed | `server_restart` | `convoyd` restarted while the run was active | The controller checks these in the order of the table above, so a pass that sees both the budget crossed and `done_when` true ends the run as `budget`. When a run ends, every agent still alive is stopped. See [budgets and limits](/docs/concepts/budgets/). `done_when` is evaluated whenever an agent it references finishes, and the server also re-evaluates it on every controller pass. A `done_when` that cannot be evaluated yet does not end the run. Durability is . In the MVP a runner that exits without calling `finish` marks its agent Failed, and a `convoyd` restart marks every active run Failed with reason `server_restart`. Everything recovery needs is stored from the start, so adding it later changes behavior, not the schema. ## Where state lives The files start the swarm. After `convoy run`, `convoyd` holds the state: the stored spec, every agent's status, every topic and message, spend, and the event log, in a SQLite file (`--db`). Three consequences follow. - The CLI is stateless. It exits after `convoy run`, and the swarm keeps going. `convoy watch` and `convoy say` attach to the server, not to your files. - Editing `main.cvy` after `convoy run` changes nothing about the running swarm. - Agents created at runtime by the overseer or by an agent with `can_spawn` exist only in the server. They are not written back to your files. Exporting a live swarm as `.cvy` is post-MVP. For the HTTP surface behind these commands see [the HTTP API](/docs/architecture/api/). --- # Agents and turns > An agent works in turns. It starts when its inputs are ready, gets more turns from the board or from continue turns, and ends by calling finish. An **agent** is one model session run by a **runner** process. It works in **turns**. One turn is one call into the SDK: the model reads its input, calls tools, and stops. Between turns the agent is Idle and costs nothing. The SDK session persists across turns, so the agent remembers what it has already read and done. ## Starting - An agent with no `inputs` and no `depends_on` starts as soon as the run starts. - An agent with `inputs` starts only after every agent it references has finished. The referenced outputs are passed into its first turn as JSON. - `depends_on` works the same way but passes nothing. Every reference in `inputs` or `depends_on` is an edge in the dependency graph, which must have no cycles. References in `writes`, `watches` and `done_when` are not edges. An agent also waits in Pending when `convoyd` is at `--max-processes`. A `count` agent expands into instances named `worker[0]`, `worker[1]`, and so on; a `for_each` agent into instances named by key, such as `researcher[nvidia]`. Referencing `agent.researcher` in `inputs` or `depends_on` waits for all instances. ## Taking more turns After its first turn, an agent gets another turn in exactly two cases: 1. A message is published to a topic in its `watches`. 2. A message is published with `to` set to the agent's name, on any topic. The input of that turn is an unread summary of the board, plus any messages addressed to the agent, in full. The agent pulls what else it needs with `read_topic`. See [topics and the board](/docs/concepts/board/). ### Continue turns An agent with an empty `watches` list works until it calls `finish`. Whenever it ends a turn without finishing, it immediately gets a **continue turn**, carrying any messages addressed to it, until it calls `finish` or reaches `max_turns`. This is how a single agent works through a long job, and it is the same rule in a team or alone. It also means an agent with empty `watches`, no `output` and the default `max_turns` can loop for 50 turns; `convoy validate` warns, and long jobs should set their own limit. ## Finishing Calling `finish(output)` ends the agent. If the agent declares an `output` shape, the payload is checked against it and a mismatch is returned to the model as an error, so it can correct itself. After `finish` the agent is Done, `agent..output` resolves to the payload, and its runner exits on its next `wake`, which revokes its token. Agents that watch topics usually never call `finish`. The server stops them when the run ends. An agent is also stopped when it reaches `max_turns`. ## Output shapes `output` is an object type: `{ approved = bool, score = number }`. It is required when `done_when` or another agent's `inputs` reads a field of this agent's output. Reading `.approved` from an agent that declares no `output`, or a field not in its shape, is a validation error. Without `output`, `finish` accepts any JSON. ```hcl output = { approved = bool, score = number } ``` ## Agent states | State | Meaning | | --- | --- | | Pending | Waiting for `inputs` or `depends_on`, or for a free process slot | | Running | In a turn | | Idle | Between turns, waiting on the board | | Stuck | Running, but no `report_progress` for 20 minutes. Not terminal; the overseer is woken | | Done | Called `finish` | | Stopped | Stopped by `convoy stop`, its parent, the overseer, the run ending, or `max_turns` | | Failed | The runner exited without `finish`. No restart in the MVP | The server treats a runner's `wake` call as "turn ended" and its response as "turn started", so it always knows whether an agent is Running or Idle. Details are in [the controller](/docs/runtime/controller/) and [the runner](/docs/runtime/runner/). ## Progress Agents call `report_progress(summary)` after each meaningful step. The summary is what [`convoy status`](/docs/cli/status/), other agents and the overseer see, and it resets the Stuck timer. --- # Topics and the board > Agents talk through topics on a shared message board. Messages are pulled, not pushed, and watches decide when an agent gets a turn. The **board** is the swarm's shared message store. A **topic** is an append-only list of **messages** on it. Every agent can read every topic. Each agent declares which topics it may write to and which topics give it a turn. ## Topics Topics are declared with the [`topic`](/docs/dsl/topic/) block and a one-line `description`, which every agent sees in its topic list. Convoy adds built-in topics: `system` (events from the controller to the overseer) and `progress` (the overseer's notes, shown by `convoy status` and `convoy watch`). Agents may create more with `create_topic(name, description)`; the new topic is added to the creator's `writes`. ## Messages Every message has a global sequence number, a topic, a sender, a body, an optional `to` (an agent name) and an optional `reply_to` (a sequence number). The sender is taken from the caller's token, never from the request body. ## Reading: cursors and the unread summary `read_topic(topic, after, limit)` reads any topic at any time. `after` is a sequence number, so an agent that joins late can read history. For each agent and topic the server keeps a **cursor**: the highest sequence number the agent has read with `read_topic`. A cursor advances only when the agent reads. Nothing is pushed into an agent's context without the agent asking, except messages addressed to it. Each turn after the first starts with an **unread summary** of every topic, not the messages themselves: ```text UNREAD findings 7 unread (seq 120-126) watched review 1 unread (seq 131) watched drafts 0 unread ADDRESSED TO YOU #132 from overseer on review: "Cut section 4, it duplicates section 2." ``` The agent decides what to pull. A busy topic cannot flood an agent, because it receives counts and fetches only what it wants. ## Writes and watches | Attribute | Effect | | --- | --- | | `writes` | Topics the agent may publish to. `publish` to any other topic is rejected | | `watches` | Topics whose new messages give the agent a turn | An agent can add a topic to its watches at runtime with `watch_topic`. A message on a topic the agent does not watch never wakes it, but it shows up in the next unread summary. ## Addressing `publish(topic, body, to = "writer")` publishes to the topic as usual and also gives the named agent a turn, whether or not it watches that topic. The addressed message appears in full in that agent's next turn input, so instructions do not depend on the agent choosing to read them. The message is visible to everyone; there are no private inboxes. The overseer instructs agents this way. ## Debounce The server waits a short quiet period after a message before giving the agent its turn, so a burst becomes one turn. The default is 5 seconds, with a cap of 30 seconds: a steady stream wakes an agent at most every 30 seconds, and a lone message wakes it after 5. An agent never wakes itself by publishing to a topic it also watches. ## People: the human topic `convoy say "" [--to ]` publishes as the sender `human`. If an agent watches that topic or is named in `--to`, it gets a turn. By convention a topic named `human` carries questions that need a person; agents post there only when blocked, and the overseer is woken by messages on it. See [`convoy say`](/docs/cli/say/). ## Assigning work Static assignment is written in the DSL with `count` or `for_each` and `vars`. Dynamic assignment is done by the overseer, which creates an agent for the work or addresses a message to one. Two agents never compete for the same message. Work queues with claim semantics are post-MVP. Implementation detail is in [the message board runtime](/docs/runtime/board/). --- # The overseer > The overseer is a built-in agent that judges progress against the goal and steers the team. It cannot end the swarm or change its goal. The **overseer** is an agent that `convoyd` starts for every swarm. It is not declared as an `agent` block. It does none of the work. It reads the board, judges whether the goal is on track, and changes the swarm through the same API as every other agent. ## Controller and overseer | | Controller (code) | Overseer (LLM) | | --- | --- | --- | | Decides | Whether an agent crashed, is stuck, finished, or hit a limit or the budget | Whether the goal is on track, whether an agent needs a narrower brief, whether a role is missing | | Acts by | Starting and stopping runner processes | Publishing instructions, creating agents, stopping agents it created | | Reads | Agent status, progress timestamps, spend, `done_when` | The board, progress summaries, its own earlier notes | | Is wrong | Rarely. It is testable code | Sometimes, so its actions are limited and logged | Anything computable is the controller's job. Judgment is the overseer's. ## Declaring it Set `overseer = { provider = provider.anthropic, model = "claude-sonnet-5", can_spawn = false }` on the [`swarm`](/docs/dsl/swarm/) block, or start `convoyd` with `--overseer-provider` and `--overseer-model` as a server-wide default. The swarm's attribute wins. A run with neither is refused. `can_spawn` defaults to `true`; set it to `false` to keep the team at exactly what the file declares. The overseer's token usage counts toward `max_cost_usd`. ## When it wakes The controller publishes to the `system` topic, addressed to the overseer, on these occasions: - The run starts. - Every 5 minutes (`--overseer-interval`), with a status line: elapsed time, spend, and agent counts. - An agent becomes Stuck, Failed, or finishes, or cannot start because a dependency failed. The overseer is also woken by a message published to `human`, or by any message addressed to `overseer`. Events within the debounce window become one turn. ## What it sees Each turn carries the unread summary, with `system` messages and anything addressed to it in full. The prompt tells it to start by calling `list_agents` for every agent's status and last progress summary, then to read the topics that matter and its own earlier notes on `progress`. It also sees the goal, `done_when`, and spend against `max_cost_usd`. ## What it can do - Every swarm tool. - `note_progress(text)`, which publishes to `progress`. It ends every turn with one. If it forgets, the server posts a placeholder note. - Instruct an agent by publishing to a topic with `to` set. - Create agents with `create_agent` (when `can_spawn` is true). It becomes their parent. - Stop agents it created, or any agent that is Stuck. - Post to `human` when a decision needs a person. ## What it cannot do The server enforces these. There is no endpoint for them. - Change the goal or `done_when`. - End the swarm. `finish` is rejected for the overseer. - Create agents when its `can_spawn` is false. - Create an agent that uses a tool, provider or model that no declared agent uses. - Write to `system`, or to any topic that does not exist. If it believes the goal is met while `done_when` is false, it can only note that and publish a message to the agent whose output decides `done_when`. ## Example 1. The controller marks `researcher[groq]` Stuck after 20 minutes without a progress report and publishes that to `system`. 2. The overseer reads `findings`, sees nothing from the groq researcher, stops it, and creates `researcher_groq_patents` with a prompt pointing at patent filings. 3. The server checks the new agent against the swarm's declared tools, providers and models, then starts it. 4. The overseer calls `note_progress` and ends its turn. With `can_spawn = false`, step 2 becomes a narrower instruction addressed to the stuck agent, which is left running. See [spawning](/docs/concepts/spawning/). The implementation is on [the controller](/docs/runtime/controller/) page. --- # Spawning agents > Agents with can_spawn can create other agents at runtime, within limits on tools, models and depth. Spawning is declared in the file, not left to a prompt. A swarm can grow while it runs. The overseer and any agent with `can_spawn = true` can call `create_agent(hcl)` with one `agent` block. The server parses it, validates it against the swarm, and creates it in Pending with the caller as its **parent**. ## Declared, not prompted Whether a team may grow is an attribute in the file: ```hcl agent "lead" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/lead.md") can_spawn = true } ``` `can_spawn` defaults to `false`. A prompt that says "create helpers" does nothing without it: the server rejects `create_agent` from an agent whose spec lacks it (`spawn_not_allowed`), and the tool is not registered for it. Putting the permission in the language means you can read from the file alone who can add agents, and a prompt injection cannot grant it. The overseer's `can_spawn` is set on the `swarm` block and defaults to `true`. ## Limits | Rule | Error | | --- | --- | | The caller must have `can_spawn` | `spawn_not_allowed` | | Spawn depth: declared agents and the overseer are depth 0; a chain may go to depth 3 | `depth_limit` | | The child's `tools` must be a subset of the parent's | `tools_not_allowed` | | The child's provider and model must be the parent's, or be used by a declared agent | `model_not_allowed` | | The block must be valid: no `count` or `for_each`, a free name, `inputs` and `depends_on` that resolve | `invalid_agent` | For the overseer, which has no tools of its own, the subset rule is replaced by the swarm-wide union: the child's tools, provider and model must each appear on some declared agent. A child may itself set `can_spawn = true`, subject to the same rules and the depth limit. There is no limit on the number of agents. `--max-processes` protects the machine, and `max_cost_usd` bounds the cost of spawning too many. See [budgets](/docs/concepts/budgets/). ## Parents and children - A parent may stop only agents it created, with `stop_agent(name, reason)`. The overseer may also stop a Stuck agent. `convoy stop` may stop any. - Stopping a parent stops its children first, depth-first. - A parent that Fails also stops its children. - Created agents exist only in the server. They do not appear in your `.cvy` files. ## Why bounds matter A web page read by one agent can carry instructions. Because a child can use at most what its parent has, and the overseer cannot change the goal, an injected instruction cannot widen the swarm's reach. See also [the overseer](/docs/concepts/overseer/) and [agents](/docs/concepts/agents/). --- # Budgets and limits > How Convoy bounds a run: a dollar budget, a runtime limit, per-agent turn limits, a process cap, and a stuck timer. A swarm can run for hours with many agents, so every run is bounded in dollars, time and turns. | Limit | Set with | Scope | On reaching it | | --- | --- | --- | --- | | Dollars | `max_cost_usd` on `swarm` | Whole run, overseer included | Every agent stopped; run Stopped, reason `budget` | | Wall-clock time | `max_runtime` on `swarm` (required) | Whole run | Every agent stopped; run Stopped, reason `max_runtime` | | Turns | `max_turns` on `agent` (default 50) | One agent | That agent is Stopped | | Processes | `convoyd --max-processes` (default 50) | The machine | Extra agents wait in Pending | | Silence | `--stuck-after` (default 20m) | One Running agent | Marked Stuck; the overseer is woken | ## max_cost_usd The dollar budget counts every agent and the overseer. After each turn the runner reports token usage; the server prices it and adds it to the run's spend. When spend reaches `max_cost_usd`, every agent is stopped and the run ends Stopped with reason `budget`. Outputs already passed to `finish` are kept. If `max_cost_usd` is unset, nothing limits spend except `max_runtime`, and `convoy validate` warns. ### Pricing Spend is computed from token usage and per-model prices in USD per million input, output, cache-read and cache-write tokens. Prices come from each [provider type](/docs/providers/)'s model catalog: the built-in types price the Claude and OpenAI models, and a third-party type prices its own. Validation and the server read the same catalog. A provider's own `price` overrides it for all of its models: ```hcl provider "local" { source = "openai_compatible" base_url = "http://localhost:11434/v1" price = { input = 0, output = 0 } } ``` `input` and `output` are required; the cache prices default to `input`. `openai_compatible` prices no models, so its providers need a `price` once a budget is set. When `max_cost_usd` is set and any agent's model, or the overseer's, has neither a price in its type's catalog nor a provider `price`, validation fails. The server applies the same check to the overseer chosen by its flags and rejects the run with `unpriced_model`. The server prices every type itself, from the token counts the runner or driver plugin reports, so the SDK's own cost figure is not what the budget uses. ### Overshoot Turns already in flight finish. Actual spend can therefore exceed the cap by up to one turn per running agent, and the count grows with the number of agents working at the moment the cap is reached. `convoy status` reports the actual spend, which may be above `max_cost_usd`. Turns the server cannot price are counted separately as unpriced. Per-agent budgets are post-MVP. ## max_runtime A duration string such as `"30s"`, `"10m"` or `"4h"`. When elapsed time reaches it, every agent is stopped and the run ends Stopped with reason `max_runtime`. ## max_turns An agent is stopped after this many turns. The default is 50. Agents that watch topics should set their own limit, since they take a turn for every wake; validation warns when they do not. The overseer has a fixed limit of 500, and hitting it stops the overseer, not the run. ## --max-processes One runner process runs per agent, almost always blocked waiting for its next turn. `--max-processes` (default 50) caps how many the machine runs at once, across all runs and counting overseers. Agents beyond it stay Pending, and earlier-declared agents win a scarce slot. The language has no agent-count limit. ## The stuck timer A Running agent that has not called `report_progress` for 20 minutes is marked Stuck, and the overseer is woken. The controller does not kill or restart it. The agent returns to Running on its next progress report. Idle agents are never Stuck, since waiting is their design. A long tool call can trip the timer, and an agent that reports while repeating itself will not; the other limits still bound it. ## Order of checks The controller checks the budget first, then `max_runtime`, then `done_when`. A pass that sees the budget crossed and `done_when` true ends the run as `budget`. See [swarms and runs](/docs/concepts/swarms/#run-status-and-end-reasons). --- # Language rules > The rules of the Convoy language that apply to every block, including file merging, names, value types, durations, strings, and comments. A swarm is written in HCL, the syntax Terraform uses, in files that end in `.cvy`. There are four block types: [`swarm`](/docs/dsl/swarm/), [`provider`](/docs/dsl/provider/), [`topic`](/docs/dsl/topic/), and [`agent`](/docs/dsl/agent/). This page covers what is true of the whole language. Each block has its own page, [References and functions](/docs/dsl/expressions/) covers expressions, and [Validation rules](/docs/dsl/validation/) lists every error and warning. The language follows Terraform where Terraform has a rule and adds agent-specific rules where it does not. ## Files and merging `convoy validate` and `convoy run` read every `*.cvy` file in the swarm folder and merge them into one configuration. - Block order and file boundaries do not matter. A reference can point at a block in another file. - Exactly one `swarm` block must exist across all files. - Files whose names start with `.` or `#`, or end with `~`, are ignored (editor temp files). - A folder with no `.cvy` files is an error: `No .cvy files found in `. - A syntax error in one file is reported, and the other files are still parsed, so one bad file does not hide errors in the rest. - Top-level attributes are not allowed. Only blocks. - Prompt files live in `prompts/` by convention. They are plain text, read with `file()`, and are not part of the HCL. Typical layouts: one `main.cvy`, or a split like the [Vending-Bench example](/docs/examples/vending-bench/), which uses `main.cvy`, `providers.cvy`, and `topics.cvy`. ```text my-swarm/ main.cvy providers.cvy topics.cvy prompts/ research.md writer.md ``` ## Blocks A block is a type, one label, and a body: ```hcl agent "writer" { # attributes } ``` The label is the block's name. Every block type takes exactly one label, including `swarm`, where it is the swarm's name. Names must match `[A-Za-z_][A-Za-z0-9_]*`: letters, digits, and underscores, not starting with a digit. A name must be unique within its type across all files. Two blocks of different types may share a name: `topic "review"` and `agent "review"` are allowed, and references tell them apart (`topic.review`, `agent.review`). An unknown block type is an error with a suggestion (`Unsupported block type "agnet". Did you mean "agent"?`). So is an unknown attribute inside a block: attributes are checked against a fixed schema, and a misspelling gets a suggestion too. ## Attributes An attribute is `name = expression`. Convoy distinguishes three kinds, by when the expression is evaluated: | Kind | Examples | Evaluated | May reference | | --- | --- | --- | --- | | Static | `goal`, `max_runtime`, `model`, `tools`, `settings`, `max_turns`, `source`, `version`, `api_key` and every other provider attribute | Once, on your machine and again on the server, when the file is loaded | Nothing, only constants and functions | | Per-instance | `prompt`, `vars` | Once per agent instance, during `count` or `for_each` expansion | `count.index`, or `each.key` and `each.value` | | Reference or late | `provider`, `writes`, `watches`, `depends_on`, `inputs`, `done_when`, `overseer.provider` | References are checked at load. `inputs` and `done_when` are evaluated by the server as agents finish | `provider.`, `topic.`, `agent.` | A static attribute that contains a reference fails with `This attribute must be a constant value`. The full list of which attribute is which is on [References and functions](/docs/dsl/expressions/#evaluation-contexts). ## Value types | Type | Written as | Used by | | --- | --- | --- | | string | `"text"` or a heredoc | `goal`, `model`, `prompt`, `description` | | number | `60`, `0.5` | `max_cost_usd`, `max_turns`, `price` | | bool | `true`, `false` | `can_spawn`, `done_when` | | list | `["bash", "web_search"]` | `tools`, `writes`, `watches`, `depends_on` | | set | `toset(["a", "b"])` | `for_each` | | map | `{ vendor = "nvidia" }` | `vars`, `inputs`, `for_each` | | object | `{ provider = provider.anthropic, model = "x" }` | `overseer`, `price` | Maps and objects both use `{ key = value }`. Keys that are valid identifiers need no quotes. Commas between entries are optional when entries are on separate lines. ### Durations A duration is a string with a unit: `"30s"`, `"10m"`, `"4h"`, `"168h"`. Units are `s`, `m`, and `h`, and they may be combined (`"1h30m"`). A bare number (`max_runtime = 3600`) or another unit (`"2d"`) is an error at the attribute. Only `max_runtime` is a duration today. ## Strings and interpolation Strings are double-quoted. `"${expr}"` interpolates any expression into the string: ```hcl vars = { me = "implementer[${count.index}]" } ``` Multi-line strings use a heredoc. `<<-EOT` strips common leading indentation: ```hcl goal = <<-EOT Raise pass^4 of the airline agent by improving its playbook on the train split, then prove the gain on the held-out split. EOT ``` Prompt files are not interpolated. `file("prompts/x.md")` returns the text unchanged, which is why `${...}` in a prompt file stays literal. To put per-instance values into a prompt, set `vars` on the agent and write `{{name}}` in the file. See [Prompt variables](/docs/dsl/agent/#vars). ## Comments ```hcl # a line comment // also a line comment /* a block comment */ ``` ## Reserved names in expressions Five roots can start a reference: `provider`, `topic`, `agent`, and, inside the agents that declare them, `count` and `each`. Using `each` anywhere else is [TS031](/docs/dsl/validation/#ts031), and `count.index` is [TS033](/docs/dsl/validation/#ts033). The other names, such as `var` or `local`, do not exist: Convoy has no variables, locals, or modules. To parameterize a swarm, use `env()` and `vars`. ## Why HCL HCL gives Convoy a syntax that people already read, a parser with precise source ranges for error messages, an expression language with references, and `count` and `for_each`. The model that writes a swarm for you (`convoy goal`) has seen a great deal of Terraform, and the same discipline carries over: declare the shape, let references define the graph, and let a tool check the whole thing before anything runs. Convoy uses `hashicorp/hcl/v2` directly and borrows OpenTofu's diagnostics, DAG, and function code. ## A complete annotated example This is the `edge_chips` swarm. Four researchers gather facts in parallel. When all four finish, a writer drafts the report. A critic reviews each draft and sends feedback through the board. The writer revises. The swarm ends when the critic approves. ```hcl title="main.cvy" swarm "edge_chips" { goal = "Ship a sourced 10-page market report on edge inference chips" done_when = agent.critic.output.approved == true # late: server evaluates max_runtime = "4h" # duration string max_cost_usd = 60 # dollars, whole run overseer = { provider = provider.anthropic, model = "claude-sonnet-5" } } provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" # name of a variable in convoyd's environment } provider "openai" { source = "openai_agents" api_key = "OPENAI_API_KEY" } topic "findings" { description = "One sourced fact per message, with URL" } topic "drafts" { description = "Report drafts, newest wins" } topic "review" { description = "Critic feedback on drafts" } topic "human" { description = "Questions that need a person" } agent "researcher" { for_each = toset(["nvidia", "groq", "cerebras", "tenstorrent"]) # 4 instances provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/research.md") vars = { vendor = each.key } # fills {{vendor}} in the prompt tools = ["web_search", "bash"] # claude_agent_sdk built-ins writes = [topic.findings] max_turns = 40 } agent "writer" { provider = provider.openai model = "gpt-6.1-sol" prompt = file("prompts/writer.md") inputs = { findings = values(agent.researcher)[*].output } # graph edge writes = [topic.drafts] watches = [topic.review] # not an edge } agent "critic" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/critic.md") watches = [topic.drafts] writes = [topic.review] output = { approved = bool, score = number } # typed finish payload } ``` The dependency graph here has one set of edges: each researcher to the writer. The writer and critic loop through the board, and the board is not part of the graph. See [References and functions](/docs/dsl/expressions/#the-dependency-graph). ## Block reference --- # swarm > The swarm block names the swarm, states its goal, and sets the rules that end it, including done_when, max_runtime, max_cost_usd, and the overseer. The `swarm` block declares the goal and the stopping rules for a run. Every configuration has exactly one, in any file. Its label is the swarm's name, which `convoy run`, `convoy status`, and the API use. ## Minimal example ```hcl title="main.cvy" swarm "hello" { goal = "Write a haiku about convoys" done_when = agent.poet.output.done == true max_runtime = "10m" } ``` This validates with one warning: `max_cost_usd` is not set ([TS061](/docs/dsl/validation/#ts061)). It also needs a `poet` agent that declares `output = { done = bool }`. ## Full example ```hcl title="main.cvy" swarm "vending_year" { goal = <<-EOT Run the Vending-Bench 2 machine for a full simulated year and end with the highest bank balance possible without going bankrupt. EOT done_when = agent.operator.output.day >= 365 || agent.operator.output.bankrupt == true max_runtime = "168h" max_cost_usd = 300 overseer = { provider = provider.anthropic model = "claude-sonnet-5" can_spawn = false } } ``` ## Attributes | Attribute | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `goal` | string | yes | | The goal in plain language. Shown to every agent and to the overseer. | | `done_when` | bool expression | yes | | When true, the run is Done. Evaluated each time a referenced agent finishes. | | `max_runtime` | duration string | yes | | Wall-clock limit for the whole run. | | `max_cost_usd` | number greater than 0 | no | unset | Dollar budget for the whole run, counting every agent and the overseer. | | `overseer` | object with `provider`, `model`, `can_spawn` | no | convoyd's flags | The overseer's provider and model, and whether it may create agents. | ### goal A string that states what the swarm is for. It is placed in every agent's system prompt and in the overseer's, so write it for a model that has no other context. Use a heredoc for anything longer than a sentence. `goal` is static: it cannot reference other blocks. ### done_when A boolean expression that decides when the swarm is finished. It may only read agent outputs: `agent..output.`, combined with comparison and logic operators (`==`, `!=`, `>=`, `&&`, `||`, `!`). ```hcl done_when = agent.critic.output.approved == true done_when = agent.reporter.output.held_out_gain >= 0.10 done_when = agent.operator.output.day >= 365 || agent.operator.output.bankrupt == true ``` To read one instance of a `for_each` agent, index it by key: `agent.runner["shard_a"].output.passed`. See [References and functions](/docs/dsl/expressions/#for_each-agents). How it is evaluated: - The server evaluates it every time an agent that it references finishes. It is not polled. - Agents that have not finished are unknown values. An expression that depends on an unknown value is unknown, and the server treats unknown as "not yet". - A known `true` ends the run with status Done, and every running agent is stopped. - A known `false` means not done. - An evaluation error, such as comparing a number with a string, is reported once as a swarm-level event and treated as `false`. - If every agent finishes and `done_when` is still false, the run ends as Failed. Every agent whose output `done_when` reads must declare an `output` shape that includes the field you read. Otherwise validation fails ([TS021](/docs/dsl/validation/#ts021), [TS022](/docs/dsl/validation/#ts022)). Referencing anything other than an agent output, such as a topic or a provider, is [TS023](/docs/dsl/validation/#ts023). `done_when` references are not dependency-graph edges. The swarm does not wait for the referenced agents to start; it just checks the condition when they finish. ### max_runtime A [duration](/docs/dsl/#durations) string such as `"4h"`. When the limit passes, every agent is stopped and the run's status is Stopped with reason `max_runtime`. It is required so that every run has an upper bound even when no budget is set. ### max_cost_usd A number greater than zero (US dollars) bounding spend across every agent and the overseer. Spend is computed by the server from the token usage each runner reports after each turn, priced with Convoy's built-in table or the provider's own [`price`](/docs/dsl/provider/#price). When spend reaches the limit, every agent is stopped, the run is Stopped with reason `budget`, and outputs already produced are kept. Turns already in flight finish first, so actual spend can exceed the cap by up to one turn per running agent. `convoy status` reports actual spend. If `max_cost_usd` is set, every model used by an agent, and the overseer's model if declared, must have a price, or validation fails with [TS060](/docs/dsl/validation/#ts060). If it is not set, validation warns ([TS061](/docs/dsl/validation/#ts061)) because only `max_runtime` bounds the run. A value of zero or less, or a non-number, is [TS062](/docs/dsl/validation/#ts062). See [Budgets and limits](/docs/concepts/budgets/). ### overseer The overseer is the built-in agent that judges whether the swarm is making progress and can add, redirect, or stop agents. This attribute chooses its model. ```hcl overseer = { provider = provider.anthropic, model = "claude-sonnet-5" } ``` | Key | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `provider` | provider reference | yes | | A `provider.` reference. | | `model` | string | no | the provider's `model` | Model name, passed to the SDK unchanged. Required unless the provider sets `model`. | | `can_spawn` | bool | no | `true` | Whether the overseer may call `create_agent`. | `model` may be left out when the provider block sets its own [`model`](/docs/dsl/provider/#model); the overseer then runs on that one, as an agent with no `model` does: ```hcl overseer = { provider = provider.llm } ``` With neither, the overseer has no model, which is [TS004](/docs/dsl/validation/#ts004). Any other key is an error with a suggestion. When `overseer` is omitted, convoyd uses its `--overseer-provider` and `--overseer-model` flags. If neither is set, the server rejects the run with HTTP 422, code `overseer_missing`. This is not a `validate` error, because validation cannot know the server's flags. If the overseer comes from the flags and `max_cost_usd` is set, the server checks the overseer model's price and rejects the run with `unpriced_model` if it has none. See [The overseer](/docs/concepts/overseer/). ## Limits that are not in the language There is no limit on the number of agents in the language. How many run at once is a property of the machine, set by `convoyd --max-processes`. Agents beyond it wait in Pending. ## What validate checks | Code | Severity | Rule | | --- | --- | --- | | [TS001](/docs/dsl/validation/#ts001) | error | Exactly one `swarm` block | | [TS002](/docs/dsl/validation/#ts002) | error | `goal`, `done_when`, or `max_runtime` is missing | | [TS003](/docs/dsl/validation/#ts003) | error | An attribute has the wrong type, including a malformed duration | | [TS004](/docs/dsl/validation/#ts004) | error | `overseer` sets no `model`, and neither does its provider | | [TS010](/docs/dsl/validation/#ts010) | error | `overseer.provider` or a name in `done_when` does not exist | | [TS021](/docs/dsl/validation/#ts021) | error | `done_when` reads a field of an agent with no `output` | | [TS022](/docs/dsl/validation/#ts022) | error | `done_when` reads a field not in the agent's `output` | | [TS023](/docs/dsl/validation/#ts023) | error | `done_when` references something other than `agent.*.output` | | [TS060](/docs/dsl/validation/#ts060) | error | `max_cost_usd` is set and a model has no price | | [TS061](/docs/dsl/validation/#ts061) | warning | `max_cost_usd` is not set | | [TS062](/docs/dsl/validation/#ts062) | error | `max_cost_usd` is not a number greater than zero | Unknown attributes, and unknown keys inside `overseer`, are also errors. --- # provider > A provider block names a provider type with source, sets the attributes that type defines, and gives settings defaults for its agents. Keys are always environment variable names. A `provider` block declares one configured use of a **provider type**: which driver runs an agent, how to reach the model, and where the key comes from. Agents reference a provider by name (`provider.anthropic`) and pick a model from it, or take the provider's own [`model`](#model). Declare one or more. A swarm can use several providers at once, so one agent can run on Claude and another on a local model. `source` names the type. Three types are built into Convoy. Any other type is a plugin that its inference provider publishes and convoyd fetches; see [Provider types](/docs/providers/). ## Minimal example ```hcl title="providers.cvy" provider "anthropic" { source = "claude_agent_sdk" } ``` The key is read from `ANTHROPIC_API_KEY` in convoyd's environment, the type's default. With `model`, the block also says which model its agents run on, so the agents do not have to: ```hcl title="main.cvy" provider "llm" { source = "claude_agent_sdk" model = "claude-sonnet-5-5" } agent "writer" { provider = provider.llm # runs on claude-sonnet-5-5 prompt = file("prompts/writer.md") } ``` ## Full example Three built-in types and one from a repository: ```hcl title="providers.cvy" provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" settings = { effort = "high" } # default for every agent on this provider } provider "openai" { source = "openai_agents" api_key = "OPENAI_API_KEY" } provider "local" { source = "openai_compatible" base_url = "http://localhost:11434/v1" # Ollama, or any Chat Completions endpoint price = { input = 0, output = 0 } # openai_compatible prices no models } provider "fast" { source = "acme/acme" # github.com/acme/convoy-provider-acme version = "~> 1.4" tier = "priority" # an attribute the acme type defines } ``` ## Core attributes These are the same for every type. Every other attribute in the block is defined by the type. | Attribute | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `source` | string | yes | | The provider type: a built-in name or an address. | | `version` | string | no | the newest version the server has | A version constraint. Not allowed with a built-in type. | | `model` | string | no | | The default model for every agent on this provider, and for the overseer when it names this provider. | | `price` | object | no | the type's model catalog | USD per million tokens for every model on this provider. | | `settings` | object | no | `{}` | Defaults for the `settings` of every agent on this provider. | | `sdk` | string | | | Deprecated name of `source`, accepted for the three built-in types. Set exactly one of the two. | Every attribute of a provider block is static: it cannot contain references, and an `api_key` cannot contain a function call. ### source | Form | Example | Meaning | | --- | --- | --- | | `` | `openai_compatible` | A built-in type | | `/` | `acme/acme` | The repository `https://github.com//convoy-provider-` | | `//` | `git.example.com/acme/acme` | The repository `https:////convoy-provider-` | Addresses are lower-case. You never download a type yourself: convoyd fetches it the first time a swarm names it, and `convoy validate` asks convoyd for its schema. See [Using a provider type](/docs/providers/using/). ### version A constraint in the syntax OpenTofu uses for provider versions: `"1.4.2"`, `"~> 1.4"` (1.4 or later, below 2.0), `">= 1.2, < 2.0"`. Without one, the newest version convoyd holds is used. A prerelease such as `0.2.0-dev` is selected only by a constraint that names it exactly. convoyd prefers a version it already holds over a newer one in the repository, so the version a swarm gets changes only when someone runs [`convoy provider pull`](/docs/cli/provider/) or changes `version`. Each run records the version and digest it used. ### model The default model for every agent on this provider. An agent that sets no [`model`](/docs/dsl/agent/#provider-and-model) of its own runs on this one, and an agent's own `model` wins. The swarm's [`overseer`](/docs/dsl/swarm/#overseer) follows the same rule when it names this provider. ```hcl provider "llm" { source = "claude_agent_sdk" model = "claude-sonnet-5-5" } agent "coder" { count = 3 provider = provider.llm # claude-sonnet-5-5 prompt = file("prompts/coder.md") } agent "reviewer" { provider = provider.llm model = "claude-opus-5-5" # its own model wins prompt = file("prompts/reviewer.md") } ``` With the model in one place, moving a swarm to another provider is a two-line edit, as long as the [tools](#built-in-types) its agents list exist on both types: ```hcl provider "llm" { source = "openai_agents" # was "claude_agent_sdk" model = "gpt-6.1-sol" # was "claude-sonnet-5-5" } ``` The model is resolved when the swarm is loaded. From then on every agent has one concrete model: `convoy status`, the Web UI and the runner never see the difference between a model an agent names and one it takes from its provider. The checks on a model apply to this one as to any other, and are reported once, on this line, however many agents use it: a name outside a closed catalog ([TS019](/docs/dsl/validation/#ts019)), a deprecated model ([TS070](/docs/dsl/validation/#ts070)), and a missing price once `max_cost_usd` is set ([TS060](/docs/dsl/validation/#ts060)). A default that no agent uses is not checked. An agent with no `model` on a provider with no `model` is [TS004](/docs/dsl/validation/#ts004). ### settings Defaults for the `settings` of every agent on this provider. An agent's settings resolve key by key: the agent's own [`settings`](/docs/dsl/agent/#settings), then its provider's, then the type's default. A setting none of them sets is not passed to the model at all. ```hcl provider "openai" { source = "openai_agents" settings = { temperature = 0.2, max_tokens = 4000 } } ``` An unknown key, a value of the wrong type, or one outside the setting's range is [TS018](/docs/dsl/validation/#ts018). ### price Overrides the type's prices for every model on this provider. The object has these keys, all USD per million tokens: | Key | Required | Default | | --- | --- | --- | | `input` | yes | | | `output` | yes | | | `cache_read` | no | the value of `input` | | `cache_write` | no | the value of `input` | Values must be numbers of zero or greater. Without `price`, a model's price comes from its type's catalog, keyed by the exact string in an agent's `model`. Use `price` for a model the type does not price: a local model (`price = { input = 0, output = 0 }`), or any model on `openai_compatible`, which prices none. Missing prices are [TS060](/docs/dsl/validation/#ts060) once `max_cost_usd` is set; a malformed `price` is [TS063](/docs/dsl/validation/#ts063). ## Keys are variable names An attribute whose type is `env_name`, such as every built-in type's `api_key`, holds the **name** of an environment variable, never the key. Keys are not stored in the swarm bundle or the database, and are not read on your machine. convoyd reads the variable from its own environment when it starts a runner and passes the value into that runner's environment, under the name the type gives it. ```hcl api_key = "ANTHROPIC_API_KEY" # correct: a variable name ``` The value must be a literal string matching `^[A-Z_][A-Z0-9_]*$`. All of these are [TS014](/docs/dsl/validation/#ts014): ```hcl api_key = env("ANTHROPIC_API_KEY") # a function call api_key = "sk-ant-api03-..." # looks like a key, not a name api_key = "anthropic_key" # lowercase ``` This is deliberate. `env()` values travel in the bundle and are stored with the run. An `api_key` that could call `env()` would put a secret there. Use `api_key` when you want two providers of the same type with different keys, or when the variable has another name. ## Built-in types The three built-in types ship with Convoy and run in its own runner. The [language reference](/docs/dsl/reference/#provider-types) lists them in full, generated from their manifests. | `source` | Drives | Attributes | Settings | Built-in tools | | --- | --- | --- | --- | --- | | `claude_agent_sdk` | Claude Agent SDK | `api_key` (default `ANTHROPIC_API_KEY`) | `effort` (`low` to `max`), `max_thinking_tokens` | `web_search`, `bash`, `read_file`, `write_file`, `edit_file` | | `openai_agents` | OpenAI Agents SDK | `api_key` (default `OPENAI_API_KEY`) | `temperature` (0 to 2), `max_tokens` | `web_search`, `bash`, `read_file`, `write_file`, `edit_file`, `code_interpreter`, `file_search` | | `openai_compatible` | Any Chat Completions endpoint | `api_key` (default `OPENAI_API_KEY`), `base_url` (required), `headers` | `temperature`, `max_tokens` | `bash`, `read_file`, `write_file`, `edit_file` | All three types offer `bash`, `read_file`, `write_file` and `edit_file` under the same names: the Claude Agent SDK's own tools on `claude_agent_sdk`, and [the runner's](/docs/runtime/runner/#local-tools-on-the-openai-types) on the two OpenAI types. The other OpenAI tools are hosted on OpenAI's platform, so `openai_compatible` does not have them. An `openai_compatible` endpoint must support streaming and function calling, because both the local tools and the [swarm tools](/docs/runtime/swarm-tools/) (the board, `finish`, and so on) reach the model as function tools. `headers` is a map of strings sent with every request: ```hcl provider "gateway" { source = "openai_compatible" base_url = "https://gateway.example.com/v1" headers = { "X-Team" = "research" } price = { input = 1, output = 4 } } ``` Claude models and the OpenAI models are priced by their types; other model names are accepted and passed through unchanged. ## What validate checks | Code | Severity | Rule | | --- | --- | --- | | [TS003](/docs/dsl/validation/#ts003) | error | An attribute has the wrong type | | [TS011](/docs/dsl/validation/#ts011) | error | `source` is not a built-in type or an address; `version` is invalid or set on a built-in type; both or neither of `source` and `sdk` | | [TS012](/docs/dsl/validation/#ts012) | error | The block does not match its type: a required attribute is missing, one it does not define is set, or a value fails its checks | | [TS014](/docs/dsl/validation/#ts014) | error | An `env_name` attribute, such as `api_key`, is not a literal environment variable name | | [TS016](/docs/dsl/validation/#ts016) | error | The type could not be resolved | | [TS017](/docs/dsl/validation/#ts017) | warning | The type was not checked, because no server could be reached | | [TS018](/docs/dsl/validation/#ts018) | error | `settings` does not match the type's settings | | [TS060](/docs/dsl/validation/#ts060) | error | `max_cost_usd` is set and a model on this provider has no price | | [TS063](/docs/dsl/validation/#ts063) | error | `price` is malformed | | [TS070](/docs/dsl/validation/#ts070) | warning | A deprecated attribute or setting of the type is used | An agent that names a provider that does not exist is [TS010](/docs/dsl/validation/#ts010), reported on the agent. On the agent too: no `model` on the agent or its provider is [TS004](/docs/dsl/validation/#ts004), and a `tools` entry the type does not offer is [TS013](/docs/dsl/validation/#ts013). A model outside a closed catalog is [TS019](/docs/dsl/validation/#ts019) and a deprecated model is [TS070](/docs/dsl/validation/#ts070), reported where the model is written: on the agent, or on the provider's `model` when agents take it from there. --- # topic > A topic block declares one channel on the message board, with a one-line description every agent sees. A `topic` block declares a channel on the swarm's message board. Agents publish messages to topics they list in `writes`, and get a turn when a message lands on a topic they list in `watches`. Declare as many as you need, or none for a swarm of agents that never talk. The name is used in `writes`, `watches`, and the `publish` tool. See [Topics and the board](/docs/concepts/board/). ## Minimal example ```hcl title="topics.cvy" topic "findings" { description = "One sourced fact per message, with URL" } ``` ## Full example A block with a single attribute fits on one line, which is how the samples write them: ```hcl title="topics.cvy" topic "findings" { description = "One sourced fact per message, with URL" } topic "drafts" { description = "Report drafts, newest wins" } topic "review" { description = "Critic feedback on drafts" } topic "human" { description = "Questions that need a person" } ``` ## Attributes | Attribute | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `description` | string | yes | | One line saying what belongs here. Shown to every agent in its topic list. | ### description Agents see the description when they call `list_topics`, and it is the only thing that tells them which topic is the right one. Say what belongs on the topic and who writes it, not what the topic is called. The Vending-Bench sample encodes cadence and sender in the text: ```hcl topic "ledger" { description = "Bookkeeper, after each daily log: the reconciled line for the day and every open order with its expected delivery day. Wakes the operator for the next morning" } ``` `description` is static and must be a string. ## The `human` topic By convention, a topic named `human` is where agents post questions that need a person. The meta prompts tell agents to post to `human` only when blocked on a decision a person has to make, and the overseer gets a turn whenever a message is published to `human`. The language does not require the topic to exist. Declare it if you want that channel, and read it with `convoy watch`. `convoy say` is separate: it publishes to any topic you name, with sender `human`. ## Topics are not dependency edges Listing a topic in `writes` or `watches` does not order agents. `watches` gives an agent a turn when a message arrives; `writes` limits where it may publish (a `publish` call to any other topic is rejected). Ordering comes only from `inputs` and `depends_on`. See [References and functions](/docs/dsl/expressions/#the-dependency-graph). ## What validate checks | Code | Severity | Rule | | --- | --- | --- | | [TS002](/docs/dsl/validation/#ts002) | error | `description` is missing | | [TS003](/docs/dsl/validation/#ts003) | error | `description` is not a string | | [TS050](/docs/dsl/validation/#ts050) | warning | No agent writes to this topic | | [TS051](/docs/dsl/validation/#ts051) | warning | No agent watches this topic | A topic that only people read or write, such as `human`, can trigger TS050 or TS051. Both are warnings and do not stop `convoy run`. --- # agent > An agent block declares one agent, or several with count or for_each, including its model, prompt, tools, dependencies, topics, output shape, and limits. An `agent` block declares one agent, several identical ones when `count` is set, or one per element of a set or map when `for_each` is set. An agent runs in turns, and one turn is one call into its SDK. It starts when its `inputs` and `depends_on` are satisfied, takes more turns when a topic it watches gets a message or a message is addressed to it, and ends when it calls `finish`. See [Agents and turns](/docs/concepts/agents/) for the runtime behaviour. This page is the language reference. ## Minimal example ```hcl title="main.cvy" agent "poet" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/poet.md") output = { done = bool } } ``` `provider` and `prompt` are always required. `model` is required unless the provider block sets [`model`](/docs/dsl/provider/#model), which is then the default for every agent on it. ## Full example ```hcl title="main.cvy" agent "implementer" { count = 4 provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/implementer.md") vars = { me = "implementer[${count.index}]" repo = env("COMMIT0_REPO_DIR") library = "simpy" } tools = ["bash", "read_file", "write_file", "edit_file"] inputs = { assignments = agent.lead.output } depends_on = [agent.setup] writes = [topic.builds, topic.human] watches = [topic.tasks, topic.failures] output = { files = list(string), passed = bool } max_turns = 60 can_spawn = true } ``` ## Attributes | Attribute | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | `provider` | provider reference | yes | | The `provider` block to run under, as `provider.`. | | `model` | string | no | the provider's `model` | Model name, passed to the provider unchanged. Required unless the provider sets `model`. | | `prompt` | string | yes | | The agent's instructions. Almost always `file("prompts/.md")`. | | `vars` | map of string | no | none | Values substituted for `{{name}}` in the prompt text. | | `tools` | list of string | no | `[]` | Built-in tools of the provider's type this agent may use. | | `settings` | object | no | `{}` | Settings of the provider's type for this agent, such as `{ effort = "high" }`. | | `inputs` | map of expression | no | none | Named values from other agents' outputs. Agent starts after they finish. | | `depends_on` | list of agent references | no | `[]` | Agents that must finish first. Passes nothing. | | `writes` | list of topic references | no | `[]` | Topics this agent may publish to. | | `watches` | list of topic references | no | `[]` | Topics whose new messages give this agent a turn. | | `output` | object type | no | none | Shape of the `finish` payload. | | `max_turns` | number | no | `50` | The agent is stopped after this many turns. | | `can_spawn` | bool | no | `false` | Whether the agent may call `create_agent`. | | `count` | whole number | no | none | Creates that many identical agents. | | `for_each` | set of string or map | no | none | Creates one agent per element. | ### provider and model `provider = provider.anthropic` names the [provider](/docs/dsl/provider/) block. It is a reference, not a string: `provider = "anthropic"` is an error (`Expected a reference like provider.`). `model` is passed to the provider unchanged, for example `claude-opus-5-5` or `gpt-6.1-sol`. An agent that sets no `model` runs on its provider's [`model`](/docs/dsl/provider/#model), the default for every agent on that provider. An agent that sets one uses its own. One of the two must be set, or the agent is [TS004](/docs/dsl/validation/#ts004): ```hcl provider "llm" { source = "claude_agent_sdk" model = "claude-sonnet-5-5" } agent "writer" { provider = provider.llm # claude-sonnet-5-5, from the provider prompt = file("prompts/writer.md") } agent "critic" { provider = provider.llm model = "claude-opus-5-5" # its own prompt = file("prompts/critic.md") } ``` Every instance of a `count` or `for_each` agent gets the same model, whichever way it is set. When the swarm sets `max_cost_usd`, the model must have a price ([TS060](/docs/dsl/validation/#ts060)): its provider's `price`, or the price in its type's catalog. A type with a closed catalog warns about a model it does not list ([TS019](/docs/dsl/validation/#ts019)); the built-in types accept any name. ### prompt The agent's instructions. Convoy places them in the YOUR JOB section of the system prompt it builds for every agent, below the swarm goal, the agent's name, its topics, and how to use the swarm tools. Use `file()`, so the prompt lives in `prompts/`: ```hcl prompt = file("prompts/critic.md") ``` A path that does not exist is [TS040](/docs/dsl/validation/#ts040). The file is read when the swarm is loaded and sent to the server in the bundle. Later edits to the file do not change a run that is already started. The expression must evaluate to a string and may use `count.index`, `each.key`, and `each.value`, but the file text itself is not interpolated. ### vars `vars` substitutes values into the prompt text. `{{vendor}}` in the prompt file is replaced with `vars.vendor`. ```hcl title="main.cvy" agent "researcher" { for_each = toset(["nvidia", "groq"]) prompt = file("prompts/research.md") vars = { vendor = each.key } # ... } ``` ```text title="prompts/research.md" You research one vendor: {{vendor}}. Publish one sourced fact per message to the findings topic. ``` Rules: - `vars` is a map of strings. The samples quote numbers (`max_rounds = "6"`). - Every `{{name}}` in the prompt whose `name` is a key of `vars` is replaced. - A `{{name}}` with no matching var is left unchanged, so placeholders meant for other layers survive. - A var that the prompt never uses is a warning ([TS054](/docs/dsl/validation/#ts054)). - `vars` may use `count.index`, `each.key`, `each.value`, `env()`, and string interpolation. - This is the only substitution. `${...}` inside a prompt file is not interpolated. Use `env()` for paths and settings, never for secrets. The values travel in the bundle and are stored with the run. ### tools The built-in tools of the provider's type that this agent may use. Each name must be one the type offers. The built-in types offer: | Type | Offers | | --- | --- | | `claude_agent_sdk` | `web_search`, `bash`, `read_file`, `write_file`, `edit_file` | | `openai_agents` | `web_search`, `bash`, `read_file`, `write_file`, `edit_file`, `code_interpreter`, `file_search` | | `openai_compatible` | `bash`, `read_file`, `write_file`, `edit_file` | `bash`, `read_file`, `write_file` and `edit_file` run on the agent's machine and mean the same thing on all three types, so an agent that lists them can move between providers by changing its `provider` and `model`. `web_search` on `openai_agents`, `code_interpreter` and `file_search` are hosted: they run on OpenAI's platform. For any other type, `convoy provider show ` lists its tools. A name the type does not offer is [TS013](/docs/dsl/validation/#ts013), and the message lists the offered tools and suggests the nearest name. Swarm tools (`list_topics`, `read_topic`, `publish`, `watch_topic`, `create_topic`, `list_agents`, `create_agent`, `stop_agent`, `report_progress`, `finish`) are always available and are never written in `tools`. `create_agent` is offered only when `can_spawn` is true. An empty `tools` list is valid and gives an agent that can only use the swarm tools. ### settings Settings of the provider's type that tune this agent's model calls, such as reasoning effort or temperature. Each key must be a setting the type defines: | Type | Settings | | --- | --- | | `claude_agent_sdk` | `effort` (`low`, `medium`, `high`, `xhigh`, `max`), `max_thinking_tokens` (0 or more) | | `openai_agents`, `openai_compatible` | `temperature` (0 to 2), `max_tokens` (1 or more) | ```hcl agent "planner" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/planner.md") settings = { effort = "max" } } ``` Each setting resolves key by key: the agent's `settings`, then its [provider's `settings`](/docs/dsl/provider/#settings), then the type's default. A setting none of them sets is not passed, so the SDK's own default applies. An unknown key or a value outside a setting's range is [TS018](/docs/dsl/validation/#ts018). Agents created at run time with `create_agent` may set `settings` too, and are checked the same way. ### inputs, depends_on, and watches These three attributes control when an agent runs. Only the first two order agents. | Attribute | Effect | Graph edge | | --- | --- | --- | | `inputs` | The agent starts after every referenced agent has finished, and receives the values as JSON in its first turn. | yes | | `depends_on` | The agent starts after every referenced agent has finished. Nothing is passed. | yes | | `watches` | A message on one of these topics gives the agent another turn. | no | An agent with no `inputs` and no `depends_on` starts when the swarm starts. **inputs** is a map of names to expressions. Each expression must read another agent's `output`: ```hcl inputs = { brief = agent.triager.output claude = agent.proposer_claude.output } ``` The agent starts once `triager` and `proposer_claude` are both Done and gets `{"brief": {...}, "claude": {...}}` in its first turn. The expressions may reach into a field (`agent.coach.output.version`), or collect every instance's outputs, `agent.worker[*].output` for a `count` agent and `values(agent.builder)[*].output` for a `for_each` agent: ```hcl inputs = { components = values(agent.builder)[*].output } ``` Anything with a root other than `agent` is an error, `inputs may only reference agent outputs`. Reading a field requires the referenced agent to declare it in `output` ([TS021](/docs/dsl/validation/#ts021), [TS022](/docs/dsl/validation/#ts022)). Each `inputs` reference is an edge, and the graph must have no cycle ([TS020](/docs/dsl/validation/#ts020)). **depends_on** is a list of agent references. Use it to order agents when you do not need the data: ```hcl depends_on = [agent.manager] # all instances of manager depends_on = [agent.runner["shard_a"]] # one instance ``` **watches** is a list of topics. After its first turn, an agent gets another turn in exactly two cases: a message is published to a topic in `watches`, or a message is sent with `to` set to the agent's name. An agent with an empty `watches` list works until it calls `finish`: whenever it ends a turn without finishing, it gets a continue turn, until it finishes or reaches `max_turns`. The writer and critic in `edge_chips` loop through the board (`writes` and `watches`) while the graph has no cycle, because `watches` and `writes` are not edges. ### writes The topics the agent may publish to. A `publish` call to any other topic is rejected and the model sees the error. Each entry is a `topic.` reference. ### output The shape of the object the agent passes to `finish`. After `finish`, the status is Done and `agent..output` resolves to the payload. The server checks the payload against the shape. A mismatch is returned to the model as a tool error with the path, for example `output.score: number required`, and the model can try again. `output` is required whenever `done_when` or another agent's `inputs` reads a field of this agent's output. Two forms are accepted. They mean the same: ```hcl output = { approved = bool, score = number } output = object({ approved = bool, score = number }) ``` The shorthand is used in every sample. The type must be an object. Field types are limited to: | Type | Example | | --- | --- | | `string` | `path = string` | | `number` | `score = number` | | `bool` | `approved = bool` | | `list(T)` | `files = list(string)` | | `map(T)` | `scores = map(number)` | | nested object | `meta = { id = string, tags = list(string) }` | `any` is rejected, so the server can always check a payload. A primitive or collection at the top level (`output = string`) is an error, `output must be an object type`. An agent with no `output` can still call `finish`; the payload is accepted as free-form JSON. Nothing may read named fields of it, though. ### max_turns The agent is stopped after this many turns. Default `50`. A turn is one SDK call, so a long-lived agent that wakes for every message on a busy topic can use turns fast; set the limit deliberately. For long jobs, set it high: the Vending-Bench operator uses `max_turns = 1500`. See [Budgets and limits](/docs/concepts/budgets/). ### can_spawn When `true`, the agent is given the `create_agent` tool and can add agents to the running swarm. Whether a team can grow is declared in the file, not left to a prompt. A child created this way may set `can_spawn = true` only if its creator could spawn, and is bounded by the creator's tools, providers, and models. The server also rejects `create_agent` from any other caller. See [Spawning agents](/docs/concepts/spawning/). ### count `count` is allowed on `agent` blocks only. The value is a whole number, and that many identical agents are created. Use it for a pool of workers that differ only in their index; use `for_each` when each instance gets its own input. ```hcl agent "implementer" { count = 4 vars = { me = "implementer[${count.index}]" } # ... } ``` - **Names.** Each instance is named `[]`, from `implementer[0]` to `implementer[3]`. - **count.index.** Inside the block, `count.index` is the instance's index, a number. It is available in `prompt` and `vars` only. - **Values.** The value must be known when the files load and be a whole number from 0 to 1000 ([TS032](/docs/dsl/validation/#ts032)). `0` produces zero instances and a warning. - **References.** `agent.implementer` is a list, as in Terraform. `agent.implementer[0].output` is one instance, `agent.implementer[*].output` is the list of all outputs in index order, and `length(agent.implementer)` is the count. See [References and functions](/docs/dsl/expressions/#count-and-for_each-agents). - **`count.index` without `count`** is [TS033](/docs/dsl/validation/#ts033). An agent with both `count` and `for_each` is [TS034](/docs/dsl/validation/#ts034). ### for_each `for_each` is allowed on `agent` blocks only. The value is a set of strings or a map, and one agent is created per element. ```hcl agent "researcher" { for_each = toset(["nvidia", "groq", "cerebras", "tenstorrent"]) vars = { vendor = each.key } # ... } agent "runner" { for_each = { shard_a = "0,1,3,4,5,7,9,10" shard_b = "11,12,14,15,17,20,21,23" } vars = { shard = each.key, task_ids = each.value } # ... } ``` - **Names.** Each instance is named `[]`, for example `researcher[nvidia]`. Instances are processed in sorted key order. - **each.** Inside the block, `each.key` is the set element or map key, and `each.value` is the element (for a set, the same as the key) or the map value. `each` is available in `prompt` and `vars`. It is not available in `provider`, `model`, `tools`, or other static attributes. - **A list is rejected.** `for_each = ["a", "b"]` fails: `for_each requires a set or map; wrap the value in toset()` ([TS030](/docs/dsl/validation/#ts030)). A set must contain strings. - **An empty set** produces zero instances and a warning. - **References.** `agent.researcher` is an object keyed by instance key. `agent.researcher["nvidia"].output` is one instance, and `values(agent.researcher)[*].output` is the list of all outputs. See [References and functions](/docs/dsl/expressions/#count-and-for_each-agents). - **Limits.** The language has no cap on the number of `for_each` instances. `convoyd --max-processes` caps concurrent runners; extra agents wait in Pending. - **`each` without `for_each`** is [TS031](/docs/dsl/validation/#ts031). `for_each` on a block other than `agent` is an error. ## How agents start, turn, and finish | Phase | Rule | | --- | --- | | Start | No `inputs` and no `depends_on`: starts with the swarm. Otherwise starts after every referenced agent has finished. | | More turns | A message on a watched topic, or a message addressed to the agent. With empty `watches`, a continue turn after every turn that does not finish. | | Finish | `finish(output)` ends the agent as Done. `output` is checked against the declared shape. | | End of swarm | Running agents are stopped when `done_when` is true, `max_runtime` passes, or the budget is spent. | Agents that watch topics usually never call `finish`. The server stops them when the swarm ends. ## What validate checks | Code | Severity | Rule | | --- | --- | --- | | [TS002](/docs/dsl/validation/#ts002) | error | `provider` or `prompt` is missing | | [TS003](/docs/dsl/validation/#ts003) | error | An attribute has the wrong type | | [TS004](/docs/dsl/validation/#ts004) | error | No `model` on the agent, and none on its provider | | [TS010](/docs/dsl/validation/#ts010) | error | `provider`, `writes`, `watches`, `depends_on`, or `inputs` names a block that does not exist | | [TS013](/docs/dsl/validation/#ts013) | error | A `tools` entry the provider's type does not offer | | [TS018](/docs/dsl/validation/#ts018) | error | `settings` does not match the type's settings | | [TS019](/docs/dsl/validation/#ts019) | warning | `model` is not in a closed catalog | | [TS020](/docs/dsl/validation/#ts020) | error | A dependency cycle through `inputs` and `depends_on` | | [TS021](/docs/dsl/validation/#ts021) | error | An `inputs` value reads a field of an agent with no `output` | | [TS022](/docs/dsl/validation/#ts022) | error | An `inputs` value reads a field not in the agent's `output` | | [TS030](/docs/dsl/validation/#ts030) | error | `for_each` is a list or a non-string set | | [TS031](/docs/dsl/validation/#ts031) | error | `each` used without `for_each` | | [TS032](/docs/dsl/validation/#ts032) | error | `count` is not a whole number from 0 to 1000 | | [TS033](/docs/dsl/validation/#ts033) | error | `count.index` used without `count` | | [TS034](/docs/dsl/validation/#ts034) | error | both `count` and `for_each` are set | | [TS040](/docs/dsl/validation/#ts040) | error | A `file()` path does not exist | | [TS052](/docs/dsl/validation/#ts052) | warning | Non-empty `watches` and no explicit `max_turns` | | [TS053](/docs/dsl/validation/#ts053) | warning | No `watches`, no `inputs`, and no `writes` | | [TS054](/docs/dsl/validation/#ts054) | warning | A var in `vars` the prompt never uses | | [TS055](/docs/dsl/validation/#ts055) | warning | No `watches`, no `output`, and no explicit `max_turns` | | [TS060](/docs/dsl/validation/#ts060) | error | `max_cost_usd` is set and the model has no price | | [TS070](/docs/dsl/validation/#ts070) | warning | The model, or a setting, is deprecated by its type | --- # References and functions > How blocks refer to each other, which references become dependency edges, the functions the language provides, and when each kind of expression is evaluated. Expressions are the right-hand side of attributes. Convoy keeps them small: references to other blocks, a short list of functions, string interpolation, and comparison operators in `done_when`. There are no variables, locals, or modules. ## References A reference is a name that starts with the block type. | Reference | Meaning | Used in | | --- | --- | --- | | `provider.` | A provider block | `agent.provider`, `swarm.overseer.provider` | | `topic.` | A topic block | `writes`, `watches` | | `agent.` | An agent block (all of its instances) | `depends_on` | | `agent..output` | The JSON the agent passed to `finish` | `inputs`, `done_when` | | `agent..output.` | One field of that output | `inputs`, `done_when` | | `agent.[0]` | One instance of a `count` agent | `depends_on`, `inputs`, `done_when` | | `agent.[*].output` | The list of every output of a `count` agent | `inputs`, `done_when` | | `agent.["key"]` | One instance of a `for_each` agent | `depends_on`, `inputs`, `done_when` | | `agent.["key"].output` | One instance's output | `inputs`, `done_when` | | `values(agent.)[*].output` | The list of every output of a `for_each` agent | `inputs`, `done_when` | | `count.index` | The current `count` index | `prompt`, `vars` of that agent | | `each.key`, `each.value` | The current `for_each` element | `prompt`, `vars` of that agent | A reference to a block that does not exist is [TS010](/docs/dsl/validation/#ts010), with a suggestion when a name is close: ```text main.cvy:44: Reference to undeclared agent "criic" (TS010). Did you mean "critic"? ``` ### count and for_each agents When an agent has `count`, `agent.` is a list in index order, as in Terraform. `agent.worker[0]` is one instance, and the splat collects every output: ```hcl agent "integrator" { # ... inputs = { builds = agent.worker[*].output } } ``` When an agent has `for_each`, `agent.` is an object keyed by instance key, as in Terraform. `agent.researcher["nvidia"]` is one instance. The splat `[*]` applies only to lists, so a bare `agent.researcher[*].output` does not work. To get every instance's output, wrap the object in `values()`: ```hcl agent "writer" { # ... inputs = { findings = values(agent.researcher)[*].output } } ``` `depends_on = [agent.researcher]` waits for every instance. `depends_on = [agent.researcher["nvidia"]]` or `[agent.worker[2]]` waits for one, and the key or index must exist. `values()` returns outputs ordered by sorted instance key. ### Instance keys A `count` agent's keys are its indexes, `0` to `count - 1`. A `for_each` over a set uses the string as the key. Over a map, the map key is the instance key. The instance name is `[]` and appears in `convoy status`, in board messages as the sender, and in `to` addresses. ## The dependency graph Convoy builds a directed graph from agent to agent. A reference is an edge only in these two places: | Where | Edge | Passes data | | --- | --- | --- | | `inputs` values | referenced agent, to this agent | yes | | `depends_on` entries | referenced agent, to this agent | no | These are **not** edges: | Where | Why | | --- | --- | | `writes` | Permission to publish. No ordering. | | `watches` | Wakes an agent on a message. The agent may already be running. | | `done_when` | Evaluated when an agent finishes. The swarm does not wait on it. | | `provider`, `overseer` | Not agents. | The graph must have no cycles. A cycle is [TS020](/docs/dsl/validation/#ts020) and lists the path: ```text main.cvy:61: Dependency cycle: writer -> critic -> writer (TS020) ``` The graph decides start order. A node with no incoming edges starts with the swarm. A node starts once every instance it depends on has finished. Cycles through the board, such as a writer and critic that publish to each other's watched topics, are fine, because topics are not edges. That is how a swarm loops while its graph stays acyclic. You can print the graph with `convoy validate --graph`, which emits Graphviz DOT. A traversal that continues past `.output` still depends on the whole agent. `agent.coach.output.version` is an edge from `coach`, not from the field. ## Functions The language exposes a short list of functions, a subset of the 150 in OpenTofu. There is no function for time, randomness, hashing, or networking. | Function | Description | | --- | --- | | `file(path)` | Reads a UTF-8 file relative to the swarm folder and returns its text. A missing file is [TS040](/docs/dsl/validation/#ts040). | | `fileexists(path)` | True if the file exists. | | `templatefile(path, vars)` | Renders a file as a template. Available, but not part of the documented MVP language. Prefer `vars` and `{{name}}`. | | `env(name)` | Reads an environment variable on the machine that runs `convoy run`. The value is sent to the server. | | `toset(list)` | Converts a list to a set, for `for_each`. | | `tolist(v)`, `tomap(v)` | Convert to a list or map. | | `tostring(v)`, `tonumber(v)`, `tobool(v)` | Convert to a primitive. | | `keys(map)` | The keys of a map. | | `values(map)` | The values of a map, as a list. | | `length(v)` | Length of a list, map, set, or string. | | `lookup(map, key, default)` | A map value, with a default. | | `merge(map, ...)` | Merges maps. | | `concat(list, ...)` | Joins lists. | | `contains(list, v)` | True if the list holds the value. | | `distinct(list)` | Removes duplicates. | | `flatten(list)` | Flattens nested lists. | | `join(sep, list)` | Joins strings. | | `split(sep, str)` | Splits a string. | | `format(fmt, ...)` | Formats a string, `printf` style. | | `upper(str)`, `lower(str)` | Changes case. | | `trimspace(str)` | Strips leading and trailing whitespace. | | `replace(str, find, with)` | Replaces text. | | `jsonencode(v)` | Encodes a value as JSON. | | `jsondecode(str)` | Decodes JSON. | ### file Paths are relative to the folder holding the `.cvy` files, not to your shell. Every file read through `file()` is added to the bundle that `convoy run` sends, so the server never needs access to your disk. ```hcl prompt = file("prompts/critic.md") ``` ### env `env("NAME")` reads a variable on the machine running `convoy run`. The CLI collects the variables your files reference and sends only those in the bundle. The server evaluates the same files against that map. ```hcl vars = { repo = env("COMMIT0_REPO_DIR") } ``` A missing variable is an error at the call site: `env("COMMIT0_REPO_DIR") is not set`. Because the value is stored with the run and returned by the API, use `env` for paths and settings, never for secrets. API keys use a provider's [`api_key`](/docs/dsl/provider/#api_key), which names a variable on the server and never carries the value. ### toset and values ```hcl for_each = toset(["a", "b", "c"]) # list -> set inputs = { all = values(agent.runner)[*].output } ``` `for_each` rejects a list, so wrap literal lists in `toset()`. ## Evaluation contexts Convoy evaluates expressions in three contexts. Which one applies depends on the attribute. | Context | When | Variables in scope | Attributes | | --- | --- | --- | --- | | Static | When the files load, on the CLI and again on the server | Functions only | `goal`, `max_runtime`, `max_cost_usd`, `model`, `tools`, `settings`, `max_turns`, `can_spawn`, `source`, `version`, `sdk`, `api_key`, `base_url` and every other provider attribute, `price`, `description`, `count`, `for_each`, `overseer.model`, `overseer.can_spawn` | | Per-instance | During `count` or `for_each` expansion, once per instance | Functions, `count`, and `each` | `prompt`, `vars` | | Runtime | In the server, as agents finish | Functions and `agent` outputs | `inputs`, `done_when` | References such as `provider`, `writes`, `watches`, and `depends_on` are not evaluated. They are parsed as names and checked. A static attribute that contains a reference fails with `This attribute must be a constant value`. For example, `max_turns = agent.lead.output.n` is an error. If a value has to come from outside the file, use `env()`. ### Runtime evaluation The server evaluates `inputs` and `done_when` with an `agent` object holding every instance's output. It has the shape: ```text agent = { researcher = { nvidia = { output = {...} }, groq = { output = unknown } } # for_each agent worker = [ { output = {...} }, { output = unknown } ] # count agent writer = { output = {...} } # single agent } ``` An agent that has not finished is an unknown value of its declared output type, which lets an expression be evaluated at any time. **inputs.** Evaluated once, when every agent in the dependency list is Done, so no value is unknown. The result is JSON, passed into the agent's first turn. **done_when.** Evaluated each time an agent it references finishes. An unknown result means "not yet". A known `true` ends the run. A known `false` does nothing. A type error, such as comparing a number with a string, is reported once as a swarm event and treated as `false`. ```hcl done_when = agent.operator.output.day >= 365 || agent.operator.output.bankrupt == true ``` If `critic` has not finished, `agent.critic.output.approved == true` is unknown, so the swarm keeps running. ### Output types and field checks `validate` checks field reads statically. Reading `agent.critic.output.approved` requires that `critic` declares an `output` and that `approved` is in it ([TS021](/docs/dsl/validation/#ts021), [TS022](/docs/dsl/validation/#ts022)). `done_when` may reference nothing but `agent.*.output` ([TS023](/docs/dsl/validation/#ts023)). ## Strings `"${expr}"` interpolates any expression into a string. In `vars` it can use `count` or `each`: ```hcl vars = { me = "implementer[${count.index}]" } ``` Prompt files are plain text. `${...}` in a prompt file is left as written. The only substitution in a prompt file is `{{name}}` from `vars` ([details](/docs/dsl/agent/#vars)). --- # Validation rules > Every error and warning that convoy validate reports, with its diagnostic code, an example, and how to fix it. `convoy validate` loads the swarm folder and runs every rule below. It needs no server, unless a provider names a type that is not built in: then it asks convoyd for that type's schema (see [Provider types](/docs/providers/)). `convoy run` runs the same checks first, and the server runs them again when it receives the swarm, so a folder that validates on your laptop validates on the server. - **Errors** stop `convoy run`. - **Warnings** are printed and do not stop it. Each stage keeps going when an earlier one found errors, as far as it has enough to work with, so one run reports as many problems as possible. ## Reading a diagnostic The CLI prints one line per diagnostic in `file:line: message` form, with the code at the end: ```console $ convoy validate main.cvy:27: error: Unknown tool "web_serach" (TS013) main.cvy:31: warning: agent "writer" watches topics and keeps the default max_turns (50) (TS052) ``` The full rendering, which `convoy validate` prints when it has room, adds the source line and detail: ```text Error: Unknown tool "web_serach" (TS013) on main.cvy line 27, in agent "researcher": 27: tools = ["web_serach", "bash"] Provider "anthropic" uses claude_agent_sdk, which offers: web_search, bash, read_file, write_file, edit_file. Did you mean "web_search"? ``` With `--json`, every diagnostic includes its code as a field. Codes are stable; the exact message wording in the examples below can change. The `convoy goal` retry loop and the tests match on them. Misspelled names get a suggestion when a known name is within edit distance 3. ## Errors from the parser These come from reading the files, before any rule runs. Most have no code. | Message | Cause | Fix | | --- | --- | --- | | `No .cvy files found in ` | The folder has no `.cvy` files | Run in the right folder, or add a `main.cvy` | | HCL syntax error | A file does not parse | Fix the syntax at the line shown; other files are still checked | | `Unsupported block type "agnet". Did you mean "agent"?` | A top-level block that is not `swarm`, `provider`, `topic`, or `agent` | Use one of the four | | `Unsupported argument` at top level | An attribute outside any block | Move it into a block | | Invalid label | A name that is not letters, digits, and underscores | Rename the block | | `Duplicate agent "writer"`, with the file and line of the first | Two blocks of one type share a name, even across files | Rename one | | `An argument named "modle" is not expected here. Did you mean "model"?` | An attribute that is not in the block's schema | Fix the spelling or remove it | | `This attribute must be a constant value` | A static attribute contains a reference | Use a literal, or `env()` | | `Expected a reference like provider.` | `provider = "anthropic"` instead of `provider = provider.anthropic` | Remove the quotes and add the prefix | | `output must be an object type` | `output = string` or a collection at top level | Wrap in an object: `output = { value = string }` | | `for_each requires a set or map; wrap the value in toset()` | `for_each = ["a", "b"]` | Use `toset([...])` (this is [TS030](#ts030)) | | `env("NAME") is not set` | A variable that `env()` reads is missing on your machine | Export it before `convoy run` | | Invalid duration | `max_runtime = 3600` or a unit other than `s`, `m`, `h` | Use `"1h"` | ## Errors and warnings by code ### TS001 **Error. Exactly one `swarm` block.** ```text main.cvy:1: error: A swarm block is required (TS001) main.cvy:40: error: Only one swarm block is allowed; the first is at main.cvy:1 (TS001) ``` Fix: declare one `swarm` block in exactly one file. Check other `.cvy` files in the folder, since all are merged. ### TS002 **Error. A required attribute is missing.** ```text main.cvy:12: error: Missing required argument "prompt" (TS002) ``` Fix: add it. Required attributes: `swarm` needs `goal`, `done_when`, `max_runtime`. `provider` needs `sdk`. `topic` needs `description`. `agent` needs `provider` and `prompt`. Within `overseer`: `provider`. Within `price`: `input` and `output`. A missing `model` is [TS004](#ts004), because a provider can supply it. ### TS003 **Error. An attribute has the wrong type.** ```text main.cvy:9: error: Incorrect type for "max_turns": a number is required (TS003) ``` Fix: use the type shown in the block's table. Common causes: a quoted number, a list where a map is expected, or `tools = "bash"` instead of `["bash"]`. ### TS004 **Error. An agent or the overseer has no model.** It sets no `model`, and neither does its provider. ```text main.cvy:18: error: Missing model (TS004) main.cvy:6: error: Missing overseer model (TS004) ``` ```text Agent "writer" sets no model, and neither does its provider "anthropic". Set model on the agent, or on the provider as the default for its agents. ``` An agent runs on its own `model`, else on its provider's [`model`](/docs/dsl/provider/#model). The swarm's `overseer` object follows the same rule. Fix: set `model` on the agent (or inside `overseer = { ... }`), or set it once on the provider block so every agent on that provider takes it. ### TS010 **Error. A reference to a block that does not exist.** ```text main.cvy:44: error: Reference to undeclared topic "reveiw". Did you mean "review"? (TS010) ``` Applies to `provider`, `overseer.provider`, `writes`, `watches`, `depends_on`, and agents inside `inputs`. Fix: correct the name or declare the block. ### TS011 **Error. The provider's type is not named correctly.** `source` is neither a built-in type nor a well-formed address; `version` is not a valid constraint, or is set on a built-in type; both `source` and `sdk` are set, or neither; or `sdk` is not one of the three built-in types. ```text providers.cvy:2: error: Unknown provider type "claude" (TS011) ``` Fix: use `claude_agent_sdk`, `openai_agents`, `openai_compatible`, or an address such as `acme/acme`. A misspelled built-in name gets a suggestion. Remove `version` from a built-in type; write a constraint such as `"~> 1.4"` for any other. ### TS012 **Error. The provider block does not match its type.** A required attribute is missing, an attribute the type does not define is set, or a value fails its type or its checks. ```text providers.cvy:14: error: Missing base_url (TS012) providers.cvy:3: error: Unsupported provider attribute (TS012) ``` The message lists the type's attributes. Fix: add `base_url = "http://localhost:11434/v1"` to an `openai_compatible` provider, remove an attribute its type does not define (`base_url` on `claude_agent_sdk`, for example), or fix the value. `convoy provider show ` prints a type's attributes. ### TS013 **Error. A `tools` entry the provider's type does not offer.** The message lists the offered tools. ```text main.cvy:27: error: Unknown tool "web_serach" (TS013) ``` Fix: use a tool the type offers (see the [built-in types](/docs/dsl/provider/#built-in-types), or `convoy provider show `). `openai_compatible` offers the four local tools (`bash`, `read_file`, `write_file`, `edit_file`) and no hosted ones, so remove `web_search` from those agents. ### TS014 **Error. An `env_name` attribute, such as `api_key`, is not a literal environment variable name.** ```text providers.cvy:3: error: Invalid api_key (TS014) ``` Fix: write the variable name, matching `^[A-Z_][A-Z0-9_]*$`, for example `"ANTHROPIC_API_KEY"`. Set the real key in convoyd's environment. ### TS015 **Error. An agent is named `overseer`.** The name is reserved for the built-in overseer. Fix: rename the agent, and configure the overseer with the swarm's `overseer` attribute. ### TS016 **Error. The provider type could not be resolved.** The detail is the server's reason: no version meets the constraint, the repository was not found, the manifest is invalid, or its runner contract is not supported. ```text providers.cvy:8: error: Provider type not found (TS016) ``` Fix: check the address and the constraint. `convoy provider pull ` shows what the server finds; the repository must be `convoy-provider-` with tags such as `v1.4.2`. ### TS017 **Warning. The provider type was not checked, because no server could be reached.** When a manifest cached by an earlier `convoy validate` was used instead, the message names its version and age, and the swarm was checked against it. ```text providers.cvy:8: warning: Provider type not checked (TS017) ``` Without a cached manifest, that provider's attributes, and the `tools`, `settings`, and `model` of its agents, are not checked. `convoy run` checks them on the server regardless. Fix: start convoyd, or pass `--server`. ### TS018 **Error. `settings` does not match the type's settings.** An unknown key, a wrong type, or a failed check, on a provider or an agent. ```text main.cvy:16: error: Invalid setting (TS018) ``` Fix: use a setting the type defines, with a value it accepts. The [built-in types](/docs/dsl/provider/#built-in-types) list theirs. ### TS019 **Warning. `model` is not in the type's catalog**, and the type does not accept other names. The message suggests the closest name. ```text main.cvy:12: warning: Model "acme-large-2" is not in the catalog (TS019) ``` The model is passed through unchanged, so a model that launched before its provider published a new version still runs. The built-in types accept any model name and never warn. A model that agents take from their provider's [`model`](/docs/dsl/provider/#model) is reported once, on the provider's line. Fix: correct a typo, or pull a newer version of the type. ### TS020 **Error. A dependency cycle.** ```text main.cvy:61: error: Dependency cycle: writer -> critic -> writer (TS020) ``` The diagnostic lists the instance names in order and points at the `inputs` or `depends_on` of the first one. Fix: remove one edge. If two agents need to exchange work repeatedly, use topics (`writes` and `watches`), which are not edges. ### TS021 **Error. A field of an output is read, but the agent declares no `output`.** ```text main.cvy:8: error: agent "critic" declares no output, so "approved" cannot be read (TS021) ``` Applies to `done_when` and `inputs` reads such as `agent.critic.output.approved`. Fix: add `output = { approved = bool }` to the agent. ### TS022 **Error. The field is not in the agent's `output`.** ```text main.cvy:8: error: output of agent "critic" has no field "aprroved" (TS022) ``` Fix: correct the field name, or add it to the `output` type. ### TS023 **Error. `done_when` references something other than `agent.*.output`.** ```text main.cvy:5: error: done_when may only reference agent outputs (TS023) ``` Fix: rewrite the condition in terms of `agent..output.`. To depend on a topic or other state, have an agent watch the topic and report the result in its `output`. ### TS030 **Error. `for_each` is a list or a non-string set.** ```text main.cvy:3: error: for_each requires a set or map; wrap the value in toset() (TS030) ``` Fix: `for_each = toset(["a", "b"])`, or use a map. ### TS031 **Error. `each` used in an agent without `for_each`.** ```text main.cvy:15: error: each is only available in an agent with for_each (TS031) ``` Fix: add `for_each`, or replace `each.key` with a literal. `each` is available only in `prompt` and `vars`. In a `count` agent, use `count.index`. ### TS032 **Error. `count` is not a whole number from 0 to 1000, or is not known before the swarm runs.** ```text main.cvy:16: error: count must be a whole number, 0 or more; got 2.5. (TS032) ``` Fix: use a whole number. `count` may call functions, such as `length(...)`, but may not refer to an agent, a topic, or a provider. ### TS033 **Error. `count.index` used in an agent without `count`.** ```text main.cvy:16: error: Agent "writer" has no count, so count.index does not exist. (TS033) ``` Fix: add `count`, or in a `for_each` agent use `each.key`. ### TS034 **Error. An agent sets both `count` and `for_each`.** ```text main.cvy:16: error: Agent "writer" sets both count and for_each. (TS034) ``` Fix: keep one. Use `count` for identical agents and `for_each` when each one gets its own input. ### TS040 **Error. A `file()` path does not exist.** ```text main.cvy:6: error: Invalid function argument: no file exists at prompts/critic.md (TS040) ``` Fix: create the file, or correct the path. Paths are relative to the swarm folder. ### TS050 **Warning. A topic that no agent writes to.** ```text topics.cvy:3: warning: topic "review" is never written to (TS050) ``` Nothing publishes to it, so any agent that watches it can never wake. Fix: add the topic to an agent's `writes`, or delete the topic. A topic that only people write to, through `convoy say`, can ignore this. ### TS051 **Warning. A topic that no agent watches.** ```text topics.cvy:2: warning: topic "drafts" is never watched (TS051) ``` Messages on it wake nobody. Agents can still read it with `read_topic`. Fix: add it to an agent's `watches` if someone should react, or ignore the warning when the topic is a log that agents read on demand. ### TS052 **Warning. Non-empty `watches` and no explicit `max_turns`.** ```text main.cvy:31: warning: agent "writer" watches topics and keeps the default max_turns (50) (TS052) ``` A long-lived agent that wakes on every message can burn through turns. Fix: set `max_turns` deliberately. ### TS053 **Warning. No `watches`, no `inputs`, and no `writes`, and nothing reads its `output`.** ```text main.cvy:20: warning: agent "solo" has no watches, no inputs, and no writes, and nothing reads its output, so its work reaches no one (TS053) ``` An agent whose `output` is read by another agent's `inputs` or by `done_when` does not get this warning: its `finish` payload is how its work travels, as with a pool of researchers that feed a writer. Fix: add `writes` if it should talk to others, read its output from `inputs` or `done_when`, or ignore this for a solo agent whose work is its side effects. ### TS054 **Warning. A var in `vars` that the prompt never uses.** ```text main.cvy:24: warning: var "vendor" is not used in the prompt (TS054) ``` Fix: add `{{vendor}}` to the prompt file, or remove the var. ### TS055 **Warning. No `watches`, no `output`, and no explicit `max_turns`.** ```text main.cvy:18: warning: agent "worker" takes continue turns until it calls finish; set max_turns (TS055) ``` An agent with empty `watches` takes a continue turn after every turn that does not finish, until it calls `finish` or reaches `max_turns`. Fix: set `max_turns`. ### TS060 **Error. `max_cost_usd` is set and a model has no price.** Applies to every agent's model and to the overseer's, when declared, whether the model is written on the agent or taken from its provider's [`model`](/docs/dsl/provider/#model). ```text main.cvy:7: error: No price for model "qwen3:32b" (TS060) ``` A model's price is its provider's `price`, else the price in its type's model catalog. The message lists the models the type prices. Fix: use a priced model, or add a `price` to the provider, for example `price = { input = 0, output = 0 }` for a local model. `openai_compatible` prices no models, so its providers need a `price` whenever `max_cost_usd` is set. If the overseer comes from convoyd's flags, the server runs this check on `PUT` and rejects the run with `unpriced_model`. ### TS061 **Warning. `max_cost_usd` is not set.** ```text main.cvy:1: warning: max_cost_usd is not set; only max_runtime bounds this run (TS061) ``` Fix: set `max_cost_usd` on the swarm. ### TS062 **Error. `max_cost_usd` is not a number greater than zero.** ```text main.cvy:5: error: max_cost_usd must be a number greater than zero (TS062) ``` Fix: use a positive number such as `60`. ### TS063 **Error. `price` is malformed.** It must be an object with numeric `input` and `output` of zero or greater, and may have only the keys `input`, `output`, `cache_read`, and `cache_write`. ```text providers.cvy:9: error: price must be an object with numeric input and output (TS063) ``` Fix: `price = { input = 3, output = 15 }`. ### TS070 **Warning. A deprecated attribute, setting, or model of the provider's type is used.** The message carries the type's own text, such as a retirement date and a replacement. ```text main.cvy:12: warning: Deprecated model "acme-small-1" (TS070) ``` Fix: move to what the message names before the provider retires it. ## Other warnings Expansion also warns, without a code, when `count = 0` or a `for_each` set is empty, so the agent has zero instances. ## Checked by the server instead Some checks cannot happen on your machine because they depend on how convoyd was started: | Check | Where | Result | | --- | --- | --- | | No overseer in the file and none in convoyd's flags | `PUT` | HTTP 422, `overseer_missing` | | A variable a provider reads, such as `ANTHROPIC_API_KEY`, is not set in convoyd's environment | `PUT` | HTTP 422, `missing_env` | | A driver plugin fails its check | `PUT` | HTTP 422, `provider_check_failed` | | Overseer from flags has no price and `max_cost_usd` is set | `PUT` | HTTP 422, `unpriced_model` | | Bundle format version unsupported | `PUT` | Rejected before parsing | The server also re-runs every rule above and returns the rendered diagnostics in the response body. --- # Provider types > A provider type is what a provider block's source names. Three are built in; any other is a plugin that its inference provider publishes, and convoyd fetches, holds, and pins to each run. Every [`provider`](/docs/dsl/provider/) block names a **provider type** with `source`. The type decides which attributes the block takes, which `settings` its agents take, which built-in tools they may list, which models it prices, and which driver runs them. ```hcl provider "anthropic" { source = "claude_agent_sdk" } # built in provider "fast" { source = "acme/acme" # a plugin, from a git repository version = "~> 1.4" tier = "priority" } ``` Three types are built into Convoy: `claude_agent_sdk`, `openai_agents`, and `openai_compatible`. Any other type is a **plugin**: one file, `convoy-provider.hcl`, that its inference provider maintains in a git repository, and for some types code beside it. Adding a provider no longer takes a Convoy release. ## Two kinds of plugin | Kind | What it ships | What runs its agents | | --- | --- | --- | | **Preset** | A manifest only | A built-in driver, such as `openai_compatible`, configured by the manifest | | **Driver plugin** | A manifest and code | The plugin's own command, built on the Python plugin SDK | A **preset** is enough when an existing driver can already reach the endpoint: the manifest declares the provider's own attributes (a tier, a region), maps them to the built-in driver's (`base_url`, `headers`), and lists the models with their prices. A **driver plugin** brings its own agent SDK; convoyd runs its command as the agent's process, under the same [runner contract](/docs/runtime/runner/) as the built-in runner. ## Kubernetes, not Terraform convoyd is the runtime, so convoyd holds the provider types, resolves them, and records what each run used. The CLI downloads no provider code and keeps no state. There is no `init` step and no lock file. - **Resolve.** When a swarm names a type, convoyd takes the highest version it holds that meets the `version` constraint. If it holds none, it lists the repository's tags and fetches the highest that does. Fetching is automatic. - **Pin to the run.** Each run records the version and digest every provider block resolved to (`convoy status --json` shows them under `providers`). That record is the only pin: an agent the run starts later, or creates with `create_agent`, uses the same version even if a newer one was pulled in the meantime. - **Upgrade on purpose.** An installed version that meets the constraint is always preferred to a newer one in the repository, so the version a swarm gets changes only when someone runs `convoy provider pull` or changes `version`. - **Check before running.** A driver plugin installs its own dependencies the first time its command starts. convoyd makes that first start itself, in check mode, when a run is created, so a broken plugin refuses `convoy run` with its output instead of failing every agent in the run. ## Where types come from | `source` | Repository | | --- | --- | | `acme/acme` | `https://github.com/acme/convoy-provider-acme` | | `git.example.com/acme/acme` | `https://git.example.com/acme/convoy-provider-acme` | Versions are tags of the form `v`, such as `v1.4.2`; other tags are ignored. The git host's own credential setup on the server gives access to a private repository. A registry that indexes the same repositories comes later; the addresses will not change. **Tags do not move.** convoyd records each version's digest, a SHA-256 over its files, when it first fetches it. If the same tag later gives different files, the fetch fails with `provider_digest_mismatch` and the stored version is kept. ## Trust - **Secrets.** A key is always the name of a variable in convoyd's environment, never a value in the swarm. A plugin's process gets `PATH`, `HOME`, its agent's token, and the variables its manifest names, and nothing else from convoyd's environment. - **Code.** A swarm that names a driver plugin makes convoyd fetch it and run its command on the server's machine as convoyd's user. Anyone who can call the API can already run an agent with `bash` there, so this adds no new power. Run convoyd shared only with people you would let run code on it. - **Presets.** A preset runs no code, but it decides which variable is read and which URL receives it. `convoy provider pull` prints both, so read them before your first run. - **Integrity.** Each run records the digest it used. There are no signatures until there is a registry to publish keys. ## Next - [Using a provider type](/docs/providers/using/): naming one in a swarm, pinning versions, upgrading. - [Writing a provider type](/docs/providers/writing/): the manifest, presets, driver plugins, and publishing. - [`convoy provider`](/docs/cli/provider/): the commands. --- # Using a provider type > Name a third-party provider type in a swarm, see what convoyd resolved, pin and upgrade versions, and set the variables it reads. This page uses an invented provider, Acme, whose type lives at `github.com/acme/convoy-provider-acme`. ## 1. Look at the type ```console $ convoy provider pull acme/acme acme/acme 1.4.2 sha256:9f2c3a71b0d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0 (preset) reads from convoyd's environment by default: api_key = ACME_API_KEY runs on the built-in openai_compatible driver with: driver_config = { base_url = attr.base_url api_key = attr.api_key headers = { "X-Acme-Tier" = attr.tier } } ``` `pull` is optional: convoyd fetches a type the first time a swarm names it. Pulling first lets you read what you are about to trust: which variable the type reads, and where a preset sends it. `convoy provider show acme/acme` prints the type's attributes, settings, tools, and models with their prices. ## 2. Name it in the swarm ```hcl title="providers.cvy" provider "fast" { source = "acme/acme" version = "~> 1.4" # optional tier = "priority" # an attribute the acme type defines settings = { temperature = 0.2 } } agent "researcher" { provider = provider.fast model = "acme-large-1" prompt = file("prompts/researcher.md") } ``` Everything besides `source`, `version`, `model`, `price`, and `settings` is defined by the type, and checked against it. ## 3. Validate ```console $ convoy validate validate: ok (1 agents, 0 topics) ``` [`convoy validate`](/docs/cli/validate/) asks convoyd for the type's schema, so it checks `tier` against the values the type allows, `settings` against its settings, the agent's `tools` against its tools, and `model` against its catalog. When convoyd is down, it falls back to the copy it cached last time and says so ([TS017](/docs/dsl/validation/#ts017)). ## 4. Set the key on the server Keys live in convoyd's environment, never in the swarm. The type reads `ACME_API_KEY` by default; set it where convoyd runs, or point `api_key` at another variable: ```hcl provider "fast" { source = "acme/acme" api_key = "ACME_PROD_KEY" } ``` A variable that is not set refuses `convoy run` with `missing_env`, naming the variable. ## 5. Run ```console $ convoy run swarm "report" run 1 accepted: 2 agents pending provider fast: acme/acme 1.4.2 sha256:9f2c3a71b0d4… ``` The run records `acme/acme 1.4.2` and its digest. `convoy status report --json` shows the list under `providers`: ```json "providers": [ { "name": "fast", "source": "acme/acme", "constraint": "~> 1.4", "version": "1.4.2", "digest": "sha256:9f2c3a71b0d4…", "kind": "preset" } ] ``` For a driver plugin, the entry also has `runner_version`, the version of the plugin SDK its check reported. ## Versions | You want | Do | | --- | --- | | The newest version the server holds | Leave out `version` | | Stay on a major version | `version = "~> 1.4"` | | One exact version | `version = "1.4.2"` | | A prerelease, such as a release candidate | Name it exactly: `version = "1.5.0-rc1"` | | Move the server to a newer version | `convoy provider pull acme/acme@~> 1.4` | | See what the server holds | `convoy provider list` | | Remove a version | `convoy provider rm acme/acme@1.4.0` | A version an active run recorded cannot be removed (`provider_in_use`). A newer version pulled while a run is active affects only later runs. ## When something goes wrong | You see | It means | | --- | --- | | [TS016](/docs/dsl/validation/#ts016) | No version meets the constraint, the repository was not found, its manifest is invalid, or it needs a runner contract this convoyd does not speak. The message has the server's reason | | [TS012](/docs/dsl/validation/#ts012) | An attribute the type does not define, a missing required one, or a value it rejects | | `provider_check_failed` on `convoy run` | A driver plugin's command failed its check. The message has the end of its output, often a missing dependency or no network for its first install | | `provider_digest_mismatch` | The provider moved a tag after convoyd fetched it. The stored version is kept; ask the provider to publish a new version | | `provider_timeout` | A fetch took longer than `--provider-timeout`. It keeps going; run again shortly | --- # Writing a provider type > How an inference provider publishes a Convoy provider type. The convoy-provider.hcl manifest, presets over a built-in driver, driver plugins on the Python plugin SDK, and how to test and release. A provider type is a git repository named `convoy-provider-` with one file at its root, `convoy-provider.hcl`. Convoy never runs your code to learn your schema: it reads the manifest. Start from the [preset](#a-preset) if an existing driver can reach your endpoint, and write a [driver plugin](#a-driver-plugin) only if your models need your own agent SDK. The manifest uses the same syntax and type expressions as a `.cvy` file, and `convoy provider validate` reports problems with file and line. ## A preset A preset reuses a built-in driver. This one puts Acme's Chat Completions endpoint behind `openai_compatible` (Acme, its endpoint, and its prices are invented): ```hcl title="convoy-provider.hcl" provider "acme" { description = "Acme Inference, Chat Completions API" driver = "openai_compatible" driver_config = { base_url = attr.base_url api_key = attr.api_key headers = { "X-Acme-Tier" = attr.tier } } driver_settings = { temperature = setting.temperature } } attribute "api_key" { type = env_name default = "ACME_API_KEY" description = "The variable in convoyd's environment that holds the Acme API key." } attribute "base_url" { type = string default = "https://api.acme.example/v1" description = "The Chat Completions endpoint." } attribute "tier" { type = string default = "standard" enum = ["standard", "priority"] description = "The service tier requests run at." } setting "temperature" { type = number min = 0 max = 2 description = "Sampling temperature." } model "acme-large-1" { price = { input = 3, output = 12, cache_read = 0.3 } } model "acme-small-1" { price = { input = 0.2, output = 0.8 } deprecated = "Retires on 2027-03-01. Use acme-small-2." } ``` A swarm then writes: ```hcl provider "fast" { source = "acme/acme" tier = "priority" } ``` `driver_config` turns your attributes into the driver's, and `driver_settings` turns your settings into the driver's. Both are expressions over `attr.` (and `setting.` in `driver_settings`), using the language's pure functions; `file` and `env` are not available. They are type-checked when the manifest is parsed, so a typo or a value the driver cannot take is your error (PM012), not your users'. An unset setting is `null`, and a `null` result is not passed. An `env_name` attribute passes through by reference (`api_key = attr.api_key`); the built-in driver decides the variable name in the runner. The endpoint must support what the driver uses. For `openai_compatible` that is streaming and function calling, because the swarm tools and the local tools reach the model as function tools. A preset offers its driver's tools, which for `openai_compatible` are `bash`, `read_file`, `write_file` and `edit_file`; `tools = ["bash", "read_file"]` in the `provider` block offers a subset. ## A driver plugin A driver plugin ships its own driver, which runs as the agent's process. convoyd starts your `command` for each agent with `--start-file start.json` appended: ```hcl title="convoy-provider.hcl" provider "acme_agents" { description = "Acme models through the Acme Agents SDK" command = ["uv", "run", "--project", "{package}", "--frozen", "--no-dev", "convoy-provider-acme-agents"] contracts = [2] } attribute "api_key" { type = env_name default = "ACME_API_KEY" inject_as = "ACME_API_KEY" description = "The variable in convoyd's environment that holds the Acme API key." } tool "web_search" { description = "Search the web." } tool "bash" { description = "Run shell commands in the agent's folder." } model "acme-large-1" { price = { input = 3, output = 12 } } ``` - `{package}` in `command` is replaced by the package folder's absolute path. `command[0]` is looked up on the runner's `PATH`, unless it starts with `{package}/`. - `contracts` lists the [runner contract](/docs/runtime/runner/) versions your code supports. convoyd refuses a version with none in common with its own. - Every `env_name` attribute needs `inject_as`: the variable your process receives its value under. - `tool` blocks declare the built-in tools an agent may list. Where a tool does what one of Convoy's names does (`web_search`, `bash`, `read_file`, `write_file`, `edit_file`, `code_interpreter`, `file_search`), use that name, so a swarm can change providers without renaming tools. ### The code Your package depends on `convoy-runner`, which is also the plugin SDK. You supply a driver; `serve` supplies the turn loop, the API client, the transcript recorder, check mode, and the exit codes. ```toml title="pyproject.toml" [project] name = "convoy-provider-acme-agents" version = "1.0.0" requires-python = ">=3.12" dependencies = ["convoy-runner>=0.2", "acme-agents>=3"] [project.scripts] convoy-provider-acme-agents = "convoy_provider_acme_agents:main" ``` ```python title="convoy_provider_acme_agents/__init__.py" from convoy_runner.plugin import Session, StartArgs, TurnResult, Usage, serve class AcmeDriver: def check(self) -> None: import acme_agents # noqa: F401 (check mode: fail if the SDK is missing) async def start(self, args: StartArgs) -> None: # args: system_prompt, model, config, settings, tools, mcp_url, token, # swarm_tools, output_schema, cwd, session_id, recorder ... async def turn(self, user_input: str) -> TurnResult: ... return TurnResult(text=text, usage=Usage(input_tokens=i, output_tokens=o), session=Session(sdk_session_id=session_id)) async def close(self) -> None: ... def main() -> None: serve(AcmeDriver) ``` A driver must: - connect its SDK to the MCP server at `mcp_url` with the bearer `token`, and let the model call the swarm tools; - allow the tools in `tools`, and no other built-in tool; - keep one SDK session across `turn` calls; - return the turn's token counts in `TurnResult.usage` and a session id in `TurnResult.session`; convoyd prices the turn from your manifest's model prices; - call `recorder.add` for each block the SDK completes (reasoning, tool calls and results, text), so the [Web UI](/docs/runtime/web-ui/) shows the transcript. `config` holds your attributes with defaults applied, except `env_name` ones, whose values arrive in the environment under `inject_as`. `settings` holds only the settings that are set. The repository's [`examples/provider_plugin`](https://github.com/convoyharness/convoy/tree/main/examples/provider_plugin) is a complete skeleton with each step marked. ### Dependencies install themselves convoyd installs nothing. It fetches your package and runs your command, and a launcher such as `uv run --project {package} --frozen` builds the plugin's environment from your committed `uv.lock` the first time it starts, then reuses it. Each version gets its own environment with pinned, hash-checked dependencies. To make that first start happen once and before any agent runs, convoyd starts your command in **check mode** when a run is created, and after a pull or push: `--check` instead of `--start-file`. `serve` builds your driver, calls its `check()` if it has one, prints one line, and exits 0: ```json {"contracts":[2],"runner_version":"0.2.0"} ``` Anything else refuses the run with `provider_check_failed` and the end of your output. The check gets `PATH` and `HOME` only: no token and no key. It needs `uv` on the runner's `PATH`, and network access the first time a version starts. Only Python driver plugins are supported for now, because the runner library also assembles each agent's prompts. Each run records the `runner_version` a plugin's check reported. ## The manifest Exactly one `provider` block, whose label is the type's name and equals the `` of the address it is published under. | Attribute | Kind | Description | | --- | --- | --- | | `description` | both, required | One line, shown by `convoy provider list` | | `driver` | preset | A built-in type whose driver runs this type's agents | | `driver_config` | preset | The built-in type's attributes, as an expression over `attr.` | | `driver_settings` | preset | The built-in type's settings, as an expression over `attr.` and `setting.` | | `tools` | preset | The subset of the built-in type's tools this type offers. Default: all of them | | `command` | driver plugin | The runner command. `{package}` stands for the package folder | | `contracts` | driver plugin, required | The runner contract versions the code supports | | `open_models` | both | When true, a model outside the catalog is accepted without [TS019](/docs/dsl/validation/#ts019). Default false | | `format` | both | The manifest format. Default and only value: 1 | Set exactly one of `driver` and `command`. `attribute` blocks declare the attributes of a swarm's `provider` block; `setting` blocks declare the keys of `settings`. | Attribute | In | Description | | --- | --- | --- | | `type` | both, required | `string`, `number`, `bool`, `list(...)`, `map(...)`, or an object type. An `attribute` may also be `env_name` | | `default` | both | For an `attribute`: when absent, the attribute is required; `null` makes it optional and unset. For a `setting`: when absent, the setting is unset unless a swarm sets it | | `description` | both, required | Shown in generated documentation | | `enum` | both | The allowed values | | `pattern` | both | An RE2 expression a string must match in full | | `min`, `max` | both | Bounds of a number, inclusive | | `inject_as` | `attribute` | For `env_name` in a driver plugin, required: the variable the value is set under in the runner | | `deprecated` | both | When set, using it is [TS070](/docs/dsl/validation/#ts070) with this text | An `env_name` value is the name of a variable in convoyd's environment, written as a literal string matching `^[A-Z_][A-Z0-9_]*$`, never the secret, so no secret enters a bundle or the store. A manifest may not declare an attribute named `source`, `version`, `sdk`, `model`, `price`, or `settings`. A `model` block's label is the model name exactly as a swarm writes it. It has `price` (optional; `{ input, output, cache_read, cache_write }` in USD per million tokens, the cache prices defaulting to `input`), `description`, and `deprecated`. A model with no price is known but unpriced. A `tool` block has a required `description`. ## Test and release ```console $ convoy provider validate # the manifest, offline provider validate: ok (acme, a preset over openai_compatible: 3 attributes, 1 settings, 4 tools, 2 models) $ convoy provider docs > PROVIDER.md # your reference, as Markdown $ convoy provider push . --source acme/acme # install on your convoyd as 0.0.0-dev $ convoy provider test acme/acme@0.0.0-dev --model acme-large-1 --set tier=priority testing acme/acme 0.0.0-dev sha256:4b1e0c9d2a7f… on run 1 of provider_test_acme_acme ok the run ended done (it is done) ok the transcript has a tool_call for list_topics ok the first turn reported input and output tokens ok the agent reported a session id provider test: ok ``` `convoy provider test` runs a one-agent swarm on your type and checks what Convoy's own drivers are tested for. It spends real tokens. For a preset it answers the first question you will have: whether the endpoint supports what the driver needs. `push` replaces an earlier push of the same version, so you can repeat it while you work. To release: 1. Name the repository `convoy-provider-`, with `convoy-provider.hcl` at its root. 2. For a driver plugin, commit `uv.lock`. 3. Tag `v`, such as `v1.0.0`. Never move a tag: convoyd records each version's digest and refuses a tag whose files changed. Publish a new version instead. Users then write `source = "/"`, and their convoyd fetches your tag the first time a swarm names it. ## Manifest codes `convoy provider validate` reports these; every one is an error. The server reports the same ones as `provider_manifest_invalid` when it fetches a version. | Code | Rule | | --- | --- | | PM001 | Exactly one `provider` block, whose label matches `^[a-z][a-z0-9_]*$` | | PM002 | A required attribute is missing, an attribute or block type is unknown, a value has the wrong type, or the file does not parse | | PM010 | Not exactly one of `driver` and `command` | | PM011 | `driver` is not a built-in type, or `tools` lists a tool the built-in type does not offer | | PM012 | `driver_config` or `driver_settings` references an attribute or setting the manifest does not declare, or does not produce the built-in type's attributes or settings | | PM013 | An attribute or block of the other kind: `tool` blocks, `contracts`, or `inject_as` in a preset; `driver_config`, `driver_settings`, or `tools` in a driver plugin | | PM020 | A duplicate or invalid name, or an `attribute` named like a core attribute | | PM021 | An invalid type; a `default` or `enum` value that does not fit; `pattern` on a non-string or `min`/`max` on a non-number; an invalid `pattern` | | PM022 | `env_name` on a `setting`; an `env_name` attribute with no `inject_as` in a driver plugin; `inject_as` on another type or not a variable name; an `env_name` default that is not a variable name | | PM030 | A `model` price is malformed | | PM040 | `contracts` is missing, empty, or lists a number below 1; `format` is not supported | | PM041 | `command` is empty, or a `{package}` path in it leaves the package | --- # Overview > The convoy CLI is a stateless Go binary. Each command reads the current folder or calls the convoyd API. This page lists the commands, global flags, environment, exit codes, and convoyd's own flags. `convoy` is a single Go binary. It never holds state. Every command either works on the `.cvy` files in a folder or makes one or more calls to the [convoyd](/docs/runtime/) HTTP API. Close the terminal and nothing changes: the swarm lives on the server. Only one command calls a model directly, [`convoy goal`](/docs/cli/goal/), and it needs no server. ## Commands | Command | Reads | Calls | What it does | | --- | --- | --- | --- | | [`convoy goal`](/docs/cli/goal/) | goal text | a model provider | Writes `main.cvy` and `prompts/*.md` from a goal, validating and retrying. Starts nothing. | | [`convoy validate`](/docs/cli/validate/) | the folder | `POST /v1/providers:resolve`, only for types that are not built in | Parses and checks every rule. | | [`convoy run`](/docs/cli/run/) | the folder | `PUT /v1/swarms/{name}` | Validates, sends the bundle, starts a new run, exits. | | [`convoy status`](/docs/cli/status/) | | `GET /v1/swarms/{name}`, `GET .../agents` | Prints run status, spend, and one row per agent. | | [`convoy watch`](/docs/cli/watch/) | | `GET /v1/swarms/{name}/watch` | Live agent table above a tail of board messages. | | [`convoy say`](/docs/cli/say/) | | `POST .../topics/{topic}/messages` | Publishes a message as `human`. | | [`convoy stop`](/docs/cli/stop/) | | `POST /v1/swarms/{name}:stop` | Stops a run or one agent. | | [`convoy ui`](/docs/cli/ui/) | | `GET /` | Opens the [Web UI](/docs/runtime/web-ui/) in a browser. | | [`convoy provider`](/docs/cli/provider/) | a package folder, for some subcommands | `/v1/providers` | Lists, fetches, pushes, removes, checks, and documents [provider types](/docs/providers/). | ## Global flags and environment These apply to every command. | Flag | Environment | Default | Meaning | | --- | --- | --- | --- | | `--dir` | | `.` | Folder that holds the `.cvy` files | | `--server` | `CONVOY_URL` | `http://localhost:7070` | convoyd base URL | | `--token` | `CONVOY_TOKEN` | empty | Bearer token for the server. Not needed when the server is on localhost | | `--json` | | off | Machine-readable output on stdout. Diagnostics and progress go to stderr | | `--no-color` | `NO_COLOR` | auto | Disable ANSI color | Color and terminal width are detected once at startup. Diagnostics wrap at the terminal width, capped at 120 columns. Provider API keys are not CLI configuration. The CLI never reads or sends them for a swarm: convoyd reads them from its own environment. The one exception is `convoy goal`, which reads `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` from your shell to call the model that writes the swarm. ## Exit codes | Code | Meaning | | --- | --- | | `0` | Success | | `1` | Runtime error: network failure, a server error, a refused request such as `swarm_active` | | `2` | Usage error: a missing or unknown flag, a missing required argument | | `3` | Validation errors in the `.cvy` files, or a server-side 422 with diagnostics | The proposal says `convoy validate` exits 1 on errors. The CLI RFC separates usage, runtime, and validation failures, and exit 3 is what ships. Scripts should test for `3`. ## Which run Every swarm is keyed by name, and each `convoy run` starts a new numbered [run](/docs/concepts/swarms/). Commands that read or act on a swarm use the latest run. `status` and `watch` accept `--run N` to read an earlier one. `say` and `stop` always act on the latest run. ## convoyd flags `convoyd` is the server. Each flag has an environment fallback. | Flag | Environment | Default | Meaning | | --- | --- | --- | --- | | `--port` | `CONVOYD_PORT` | `7070` | Listen port | | `--db` | `CONVOYD_DB` | `./convoy.db` | SQLite file | | `--work-dir` | `CONVOYD_WORK` | `./.convoy/work` | Root of agent workspaces | | `--runner` | `CONVOYD_RUNNER` | the runner built into `convoyd`, started with `uv` | A runner executable of your own to use instead | | `--token` | `CONVOYD_TOKEN` | empty | The CLI token. Empty means loopback requests need none | | `--public-url` | `CONVOYD_PUBLIC_URL` | `http://127.0.0.1:PORT` | Address runners use to reach convoyd. Required when runner processes live on another host | | `--max-processes` | `CONVOYD_MAX_PROCESSES` | `50` | Most runner processes alive at once across all runs, overseers included. Agents beyond it wait in Pending | | `--no-ui` | `CONVOYD_NO_UI` | off | Do not serve the [Web UI](/docs/runtime/web-ui/) at `/`. `1` or `true` in the environment | | `--provider-dir` | `CONVOYD_PROVIDER_DIR` | `./.convoy/providers` | Where [driver plugin](/docs/providers/) packages are kept, as `//` | | `--provider-timeout` | | `5m` | How long a request waits for a provider fetch or check | | `--stuck-after` | | `20m` | How long a running agent may show no progress before it is marked Stuck | | `--debounce` | | `5s` | Board wake debounce | | `--overseer-provider` | | none | Built-in provider type for the server-wide default overseer: `claude_agent_sdk`, `openai_agents`, or `openai_compatible` | | `--overseer-model` | | none | Model for the default overseer | | `--overseer-base-url` | | none | The type's `base_url`, for `openai_compatible` | | `--overseer-api-key-env` | | none | The type's `api_key`: the name of the environment variable that holds its key | | `--overseer-can-spawn` | | `true` | `can_spawn` for the default overseer | The overseer flags are optional. A swarm's own `overseer` attribute wins over them, and a run with neither is refused with `overseer_missing`. See [The overseer](/docs/concepts/overseer/). ## A full session ```console $ export ANTHROPIC_API_KEY=sk-ant-... $ convoyd --port 7070 --db ./convoy.db --max-processes 50 \ --overseer-provider claude_agent_sdk --overseer-model claude-sonnet-5 & $ convoy goal --provider anthropic --model claude-opus-5 \ "Write a sourced 10-page market report on edge inference chips" wrote ./main.cvy wrote ./prompts/research.md wrote ./prompts/writer.md wrote ./prompts/critic.md validate: ok agents researcher[nvidia, groq, cerebras, tenstorrent] -> writer <-> critic topics findings, drafts, review, human review the files, then: convoy run $ convoy validate validate: ok (6 agents, 4 topics) $ convoy run swarm "edge_chips" run 1 accepted: 7 agents pending AGENT STATUS PROVIDER MODEL critic pending anthropic claude-opus-5 overseer pending anthropic claude-sonnet-5 researcher[cerebras] pending anthropic claude-sonnet-5 researcher[groq] pending anthropic claude-sonnet-5 researcher[nvidia] pending anthropic claude-sonnet-5 researcher[tenstorrent] pending anthropic claude-sonnet-5 writer pending openai gpt-6.1-sol watch with: convoy watch edge_chips $ convoy watch edge_chips $ convoy say edge_chips human "Skip Tenstorrent, focus on the other three" published seq 41 $ convoy status edge_chips $ convoy stop edge_chips ``` ## Next - [Quickstart](/docs/quickstart/) runs this session end to end. - [Validation rules](/docs/dsl/validation/) lists every check `validate` makes. - [convoyd](/docs/runtime/) describes what the server does with a run. --- # convoy goal > Turn a written goal into a validated set of .cvy and prompt files by asking a model you name, retrying with diagnostics until the files pass. It does not start anything. ```text convoy goal --provider --model [flags] "" ``` `goal` is the only command that calls a model directly. It needs no running convoyd. The model you name here only writes the swarm. The swarm declares its own providers and models. ## What it does 1. Checks flags. A missing `--provider` or `--model`, or an unknown provider, is a usage error (exit 2) before any network call. There are no defaults. 2. Builds the system prompt (meta prompt 1) from the goal and three inserts: the providers, models, and tools a swarm may declare (all priced, so a generated `max_cost_usd` passes validation); the embedded DSL reference; and two embedded example swarms. 3. Calls the model with the goal as the user message. The model returns files as blocks: ```text ... ... ``` Paths must be relative, contain no `..`, and sit under `.` or `prompts/`. 4. Loads the files in memory and runs the same checks as [`convoy validate`](/docs/cli/validate/). 5. Writes the files if they pass, and prints a summary. ## The retry loop If validation reports errors and attempts remain, the CLI appends the model's reply and a new user message to the conversation: `convoy validate reported these errors. Return the full corrected set of files.`, followed by every error in plain text. The model returns a complete corrected set and the loop repeats. - Warnings are printed but never trigger a retry. - `--attempts` bounds the loop (default 3). - If errors remain after the last attempt, nothing is written. The diagnostics are printed, the last model output is saved to `.convoy/goal-failed.txt`, and the command exits 3. ## Flags | Flag | Default | Meaning | | --- | --- | --- | | `--provider` | required | `anthropic` or `openai`. `openai` also covers OpenAI-compatible servers with `--base-url` | | `--model` | required | Model id, passed through unchanged. Not checked against any price catalog | | `--base-url` | provider default | Override the inference URL for a proxy, gateway, or self-hosted server | | `--attempts` | `3` | Total model calls before giving up | | `--max-retries` | `3` | Retries of a failed model request (network or API errors) | | `--overwrite` | off | Replace `main.cvy` and any other returned file that already exists | | `--dry-run` | off | Print the files to stdout instead of writing | Global flags such as `--dir` apply. The key comes from `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` in your shell. ## Example ```console $ convoy goal --provider anthropic --model claude-opus-5 \ "Write a sourced 10-page market report on edge inference chips" wrote ./main.cvy wrote ./prompts/research.md wrote ./prompts/writer.md wrote ./prompts/critic.md validate: ok agents researcher[nvidia, groq, cerebras, tenstorrent] -> writer <-> critic edges researcher -> writer topics findings, drafts, review, human review the files, then: convoy run ``` The summary collapses each `count` or `for_each` agent into one line, with its index range (`worker[0..3]`) or its keys, lists dependency edges as `a -> b`, and ends by pointing at `convoy run`. When a first attempt fails and the second passes, the extra diagnostics go to stderr: ```console $ convoy goal --provider openai --model gpt-6.1-sol "Fix the failing tests in ./repo" attempt 1: 2 errors, retrying main.cvy:14: error: agent "fixer" references undeclared topic "results" main.cvy:22: error: swarm "fix_tests" has no done_when wrote ./main.cvy wrote ./prompts/fixer.md validate: ok ``` ## Existing files After validation, if `main.cvy` or any returned path exists and `--overwrite` is not set, the command exits 1 with `main.cvy exists; pass --overwrite`. Nothing is written. ## Exit codes | Code | Cause | | --- | --- | | `0` | Files written (or printed with `--dry-run`) | | `1` | A file exists and `--overwrite` is not set, or the model request failed | | `2` | Missing `--provider` or `--model`, or an unknown provider | | `3` | Errors remain after the last attempt | ## API endpoint None. `goal` talks to the model provider, not to convoyd. ## Related - [convoy validate](/docs/cli/validate/) runs the same checks on the result. - [convoy run](/docs/cli/run/) is the next step. - [Your first swarm](/docs/first-swarm/) shows editing a generated file. - [Validation rules](/docs/dsl/validation/) --- # convoy validate > Parse every .cvy file in a folder, resolve references, and check every language rule. Needs no server unless a provider names a type that is not built in. Exits 3 on errors. ```text convoy validate [--dir ] [--json] [--graph] ``` `validate` never contacts a model. It contacts convoyd only when a provider names a type that is not built in, to read that type's schema. A swarm on the built-in types validates with no server at all. ## What it does 1. Loads every `*.cvy` file in the folder and merges them into one configuration. 2. For providers whose type is not built in, asks convoyd (`--server`) to resolve the types, in one call. The server fetches a type it does not hold, but never runs provider code for this. 3. Resolves references, builds the dependency graph, and checks every rule in [Validation rules](/docs/dsl/validation/), including each provider's attributes and each agent's `tools`, `settings`, and `model` against its type. 4. Prints each diagnostic with its source line, warnings first, then errors, separated by blank lines. 5. Exits 3 if there is any error, otherwise prints `validate: ok (N agents, M topics)` and exits 0. ## When the server is down `validate` keeps each type's manifest it receives in your user cache folder (`convoy/providers/` under it), indexed by server, source, and constraint. When convoyd cannot be reached, it checks the swarm against the cached manifest and warns with [TS017](/docs/dsl/validation/#ts017), naming the version and how old the copy is. With nothing cached, TS017 says the type was not checked, and the swarm still validates. The cache is a convenience: the server's answer always wins, and [`convoy run`](/docs/cli/run/) is checked on the server regardless. ```console $ convoy validate Warning: Provider type checked against a cached copy (TS017) on providers.cvy line 2, in provider "fast": 2: source = "acme/acme" No server could be reached, so provider "fast" was checked against the cached manifest of acme/acme 1.4.2, cached 3 days ago. convoy run checks it on the server. validate: ok (6 agents, 4 topics) ``` Some checks need the server and cannot run here: whether convoyd has a default overseer (`overseer_missing`), whether its environment has the provider keys (`missing_env`), and the server's price for the overseer model when it comes from server flags (`unpriced_model`). Those surface on [`convoy run`](/docs/cli/run/). ## Flags | Flag | Meaning | | --- | --- | | `--json` | Print `{"valid": bool, "diagnostics": [...]}` on stdout | | `--graph` | Print the dependency graph in DOT format and exit 0 if there are no errors | Each JSON diagnostic has `severity`, `code`, `summary`, `detail`, and `range` (`file`, `start` and `end` with `line` and `column`). ## Examples ```console $ convoy validate validate: ok (6 agents, 4 topics) ``` A warning does not fail validation: ```console $ convoy validate main.cvy:31: warning: agent "writer" watches topics and keeps the default max_turns (50) validate: ok (6 agents, 4 topics) ``` An error does: ```console $ convoy validate main.cvy:44: error: agent "critic" watches topic "reviews", which is not declared did you mean topic "review"? main.cvy:19: error: references form a cycle: agent.writer -> agent.critic -> agent.writer $ echo $? 3 ``` Render the graph: ```console $ convoy validate --graph | dot -Tsvg > swarm.svg ``` Machine-readable output: ```console $ convoy validate --json {"valid":false,"diagnostics":[{"severity":"error","code":"TS020","summary":"undeclared topic","detail":"agent \"critic\" watches topic \"reviews\"","range":{"file":"main.cvy","start":{"line":44,"column":12},"end":{"line":44,"column":31}}}]} ``` ## Exit codes | Code | Cause | | --- | --- | | `0` | No errors (warnings allowed) | | `3` | At least one error | ## API endpoint `POST /v1/providers:resolve`, only for provider types that are not built in. ## Related - [Validation rules](/docs/dsl/validation/) is the full list of checks. - [Language rules](/docs/dsl/) - [convoy run](/docs/cli/run/) validates first, then sends. - [convoy goal](/docs/cli/goal/) validates its own output in a loop. --- # convoy run > Validate the folder, send it to convoyd as a bundle, start a new run of the swarm, and exit. The swarm keeps running on the server. ```text convoy run [--dir ] [--name ] [--server ] ``` `run` never waits for the swarm. Its last line is `watch with: convoy watch `. ## What it does 1. Runs the same checks as [`convoy validate`](/docs/cli/validate/). Errors exit 3. 2. Builds the bundle: every `.cvy` file, every file named in a `file()` call, and the value of every `env()` argument read from your shell. A missing `env()` variable is an error before any network call. Provider API keys are not read or sent. convoyd reads them from its own environment. 3. Sends `PUT /v1/swarms/{name}` with the bundle as JSON. The name is the swarm block's label, or `--name` if given. 4. convoyd resolves each provider's type, fetching one it does not hold, and starts every [driver plugin](/docs/providers/) once in check mode before it creates the run. The run records the type version and digest each provider block resolved to. 5. Handles the response, below. ## Flags | Flag | Meaning | | --- | --- | | `--name` | Override the swarm name taken from the `swarm` block | ## Responses **201, accepted.** The server created a run. A new swarm name starts at run 1. If the swarm exists and its latest run has ended (Done, Stopped, or Failed), this is the next run number. Earlier runs are kept and stay readable with `--run`. For each provider whose type is not built in, `run` prints the version and digest the run uses, so you can see what will execute. ```console $ convoy run swarm "edge_chips" run 3 accepted: 7 agents pending provider fast: acme/acme 1.4.2 sha256:9f2c3a71b0d4… AGENT STATUS PROVIDER MODEL critic pending anthropic claude-opus-5 overseer pending anthropic claude-sonnet-5 researcher[cerebras] pending anthropic claude-sonnet-5 researcher[groq] pending anthropic claude-sonnet-5 researcher[nvidia] pending anthropic claude-sonnet-5 researcher[tenstorrent] pending anthropic claude-sonnet-5 writer pending openai gpt-6.1-sol watch with: convoy watch edge_chips ``` The count includes the [overseer](/docs/concepts/overseer/), which every run gets. **409 `swarm_active`.** The latest run is still Pending or Running. Nothing changes. There is no flag to replace a running swarm. Stop it first. ```console $ convoy run swarm "edge_chips" is running (run 3, started 12:04:02). Wait for it to finish, or stop it with: convoy stop edge_chips $ echo $? 1 ``` **422, rejected.** The body carries diagnostics. Exit 3. Besides the errors `validate` reports, the server makes checks it alone can: | Code | Meaning | | --- | --- | | `overseer_missing` | The swarm block has no `overseer` and convoyd has no `--overseer-provider` and `--overseer-model` | | `missing_env` | A variable a provider reads, such as its `api_key`, is not set in convoyd's environment. The message names the variable, never a value | | `provider_check_failed` | A [driver plugin](/docs/providers/) failed its check: its command did not exit 0 or did not report a runner contract convoyd speaks. The message carries the end of its output | | `unpriced_model` | `max_cost_usd` is set and an agent model, or the overseer model, has no price | | `bundle_version_unsupported` | The bundle format is newer than the server understands | A provider type the server cannot resolve is [TS016](/docs/dsl/validation/#ts016) among the diagnostics. A fetch that takes longer than convoyd's `--provider-timeout` answers 504 `provider_timeout` and exit 1; the fetch continues, so running again shortly succeeds. ```console $ convoy run error[overseer_missing]: declare overseer = { provider, model } on the swarm block, or start convoyd with --overseer-provider and --overseer-model $ echo $? 3 ``` **400 `name_mismatch`.** The URL name and the swarm block's name differ. Exit 1. ## Exit codes | Code | Cause | | --- | --- | | `0` | Run accepted | | `1` | Server unreachable, `swarm_active`, or another server error | | `2` | Usage error | | `3` | Validation errors locally, a missing `env()` variable, or a 422 from the server | ## API endpoint `PUT /v1/swarms/{name}`. See [The convoyd API](/docs/architecture/) for the server's side: the transaction that creates the run, agents, topics, and overseer row. ## Related - [convoy watch](/docs/cli/watch/) to follow the run. - [convoy stop](/docs/cli/stop/) to free a swarm name. - [Swarms and runs](/docs/concepts/swarms/) - [Budgets and limits](/docs/concepts/budgets/) - [Provider types](/docs/providers/) --- # convoy status > Print a run's status, elapsed time, spend against budget, end reason, and one row per agent. Use --json for scripts and --runs for history. ```text convoy status [--run ] [--runs] [--json] ``` ## What it does Calls `GET /v1/swarms/{name}` and `GET /v1/swarms/{name}/agents` for the latest run, or run N with `--run`. It prints a header, the goal, an agent table, and the latest overseer progress note. ```console $ convoy status edge_chips swarm edge_chips run 3 RUNNING elapsed 00:41:12 / 4h spend $4.12 / $20.00 agents 7 (running 2, idle 4, done 1) goal: Ship a sourced 10-page market report on edge inference chips AGENT STATUS TURNS PROVIDER SPEND LAST PROGRESS researcher[cerebras] done 12 anthropic $0.61 published 9 findings researcher[groq] idle 8 anthropic $0.48 waiting on patent search results writer running 3 openai $0.92 drafting section 2 critic idle 1 anthropic $0.70 reviewed draft 1, score 0.6 overseer idle 4 anthropic $0.31 all researchers productive progress (latest): 3 of 4 researchers done; writer has started. ``` ## Reading the output | Field | Meaning | | --- | --- | | elapsed | Time since the run started, against `max_runtime` | | spend | The run's total against `max_cost_usd`, or `spend $4.12 (no limit)` when unset. Priced from each turn's reported tokens | | STATUS | Agent status: pending, running, idle, stuck, done, stopped, failed. See [Agents and turns](/docs/concepts/agents/) | | TURNS | Turns the agent has taken | | LAST PROGRESS | The agent's latest `report_progress` summary | Turns in flight finish after the limit is reached, so total spend can exceed `max_cost_usd`. It is shown as is. For an ended run, the header shows the end status and reason: ```console $ convoy status edge_chips --run 2 swarm edge_chips run 2 STOPPED (budget) elapsed 02:13:50 / 4h spend $20.38 / $20.00 agents 7 (done 4, stopped 3) ``` Possible endings: `DONE`, `STOPPED (budget)`, `STOPPED (max_runtime)`, `STOPPED (stopped)` for a human stop, and `FAILED (failed)` or `FAILED (server_restart)`. ## Flags | Flag | Meaning | | --- | --- | | `--run N` | Read run N instead of the latest | | `--runs` | List every run of the swarm | | `--json` | Print one merged JSON object | ## Run history ```console $ convoy status edge_chips --runs RUN STATUS END REASON STARTED ELAPSED SPEND 3 running - 2026-11-05 12:04:02 00:41:12 $4.12 2 stopped budget 2026-11-04 09:30:11 02:13:50 $20.38 1 done done 2026-11-03 16:02:44 01:05:09 $11.77 ``` ## JSON `--json` merges the two responses. It always includes `run`, `status`, `end_reason` (null while running), `started_at`, `ended_at`, `elapsed_seconds`, `spend_usd`, `max_cost_usd` (null when unset), and per agent `spend_usd`, `turns`, `status`, and `output` once the agent has finished. ```console $ convoy status edge_chips --json | jq '{status, end_reason, spend_usd, max_cost_usd}' { "status": "running", "end_reason": null, "spend_usd": 4.12, "max_cost_usd": 20 } ``` This is the form for comparing runs, for example the team and solo arms of the [Commit0 example](/docs/examples/commit0/). ## Exit codes | Code | Cause | | --- | --- | | `0` | Status printed, whatever the run's own status | | `1` | Unknown swarm (404), unknown run, or server unreachable | | `2` | Missing swarm argument | ## API endpoints - `GET /v1/swarms/{name}?run=N` - `GET /v1/swarms/{name}/agents?run=N` - `GET /v1/swarms/{name}/runs` for `--runs` ## Related - [convoy watch](/docs/cli/watch/) for a live view. - [Budgets and limits](/docs/concepts/budgets/) - [Swarms and runs](/docs/concepts/swarms/) --- # convoy watch > Stream a run's events and draw a live agent table above a scrolling tail of board messages. Ctrl-C closes the stream and does not affect the swarm. ```text convoy watch [--run ] [--since ] [--topic ] [--full] [--json] ``` ## What it does 1. Opens `GET /v1/swarms/{name}/watch?after=0` as a server-sent event stream, for the latest run unless `--run` is given. 2. Keeps an in-memory model: the agent table, updated by `agent.*` events, and the last 20 messages, updated by `message.published`. 3. Redraws at most four times a second: clears the screen, prints the status header and agent table as in [`convoy status`](/docs/cli/status/), a rule, then the message tail. 4. Ends when the server sends `run.ended`. It prints the final status and exits 0. A frame looks like this: ```console swarm edge_chips run 3 RUNNING elapsed 00:41:12 / 4h spend $4.12 / $20.00 agents 7 (running 2, idle 4, done 1) AGENT STATUS TURNS PROVIDER SPEND LAST PROGRESS researcher[cerebras] done 12 anthropic $0.61 published 9 findings researcher[groq] idle 8 anthropic $0.48 waiting on patent search results writer running 3 openai $0.92 drafting section 2 critic idle 1 anthropic $0.70 reviewed draft 1, score 0.6 overseer idle 4 anthropic $0.31 all researchers productive ------------------------------------------------------------------------------------------ 12:04:31 findings researcher[groq] -> (all) Groq LPU v2 ships at 750 TOPS INT8, https://groq.com/... 12:04:48 findings researcher[cerebras] -> (all) WSE-3 holds 44 GB on-chip SRAM, https://cerebras.ai/... 12:05:02 progress overseer -> (all) all researchers productive 12:05:19 drafts writer -> (all) Draft 1: sections 1 to 3 of 10 (4,210 words) 12:05:40 review critic -> writer Section 2 cites a vendor blog for the TOPS figure; find an independent source ``` Each tail line is time, topic, sender and recipient, then the body truncated to one line at the terminal width. ## Flags | Flag | Meaning | | --- | --- | | `--run N` | Watch run N instead of the latest. An ended run replays and exits | | `--since SEQ` | Start from event offset SEQ instead of 0 | | `--topic NAME` | Filter the tail to one topic | | `--full` | Do not truncate message bodies | | `--json` | No redraw. Print each event as one JSON line as it arrives | ## JSON mode With `--json`, every event is one line on stdout, which is also the way to save the stream. ```console $ convoy watch edge_chips --json > events.jsonl $ head -n 2 events.jsonl {"seq":38,"type":"agent.turn_ended","swarm":"edge_chips","run":3,"agent":"writer","at":"2026-11-05T12:05:19Z","payload":{"turn":3,"input_tokens":18204,"output_tokens":2216,"cost_usd":0.0877,"run_spend_usd":4.12}} {"seq":39,"type":"message.published","swarm":"edge_chips","run":3,"agent":"writer","at":"2026-11-05T12:05:19Z","payload":{"seq":27,"topic":"drafts","to":null,"body":"Draft 1: sections 1 to 3 of 10"}} ``` The event types are listed in the [convoyd runtime](/docs/runtime/). `--json` prints every event. The table and line views ignore the events that exist for the [Web UI](/docs/runtime/web-ui/) (`agent.tool_called`, `topic.read`, `topic.created`), and print `agent.created` only for agents made at run time, since the header already lists the agents the run started with. ## Connection handling Ctrl-C closes the connection and exits 0. The swarm is unaffected. A dropped connection is retried with `after=` up to five times with backoff, so no event is lost or repeated. The server sends a keepalive every 15 seconds. Agent logs are not part of the stream by default. The local backend can include them with `--logs`. ## Exit codes | Code | Cause | | --- | --- | | `0` | Run ended and the final status was printed, or Ctrl-C | | `1` | Unknown swarm, or the connection failed after five retries | | `2` | Usage error | The exit code is 0 whatever the run's own outcome. To branch on the outcome, use `convoy status --json`. ## API endpoint `GET /v1/swarms/{name}/watch?after=N`, server-sent events over the run's event log. ## Related - [convoy status](/docs/cli/status/) - [convoy say](/docs/cli/say/) to talk to the swarm while you watch. - [Topics and the board](/docs/concepts/board/) --- # convoy say > Publish a message to a topic on the swarm's board as the sender human, optionally addressed to one agent to wake it. ```text convoy say "" [--to ] ``` ## What it does Calls `POST /v1/swarms/{name}/topics/{topic}/messages` with `{"body": "", "to": ""}`, omitting `to` when `--to` is not given. The sender is the token's identity, which for the CLI is `human`. It prints the message's sequence number. An agent gets another turn when a message lands on a topic in its `watches`, or when a message is addressed to it with `to`. So `say` to a watched topic wakes its watchers, and `--to` wakes one named agent whatever it watches. ## Flags | Flag | Meaning | | --- | --- | | `--to AGENT` | Address the message to one agent. It also wakes that agent | ## Examples Steer the swarm by publishing to a topic: ```console $ convoy say edge_chips human "Skip Tenstorrent, focus on the other three" published seq 41 ``` Address one agent directly: ```console $ convoy say edge_chips review "Cut section 4 to one page" --to writer published seq 42 ``` An unknown topic: ```console $ convoy say edge_chips reviews "typo" error: topic "reviews" not found in swarm "edge_chips" (404) $ echo $? 1 ``` ## Exit codes | Code | Cause | | --- | --- | | `0` | Published | | `1` | Topic does not exist (404), the latest run has ended (409 `run_ended`), or server unreachable | | `2` | Missing argument | Writes act on the latest run only. If it has ended, start a new one with [`convoy run`](/docs/cli/run/). ## API endpoint `POST /v1/swarms/{name}/topics/{topic}/messages` ## Related - [Topics and the board](/docs/concepts/board/) - [Message board](/docs/runtime/board/) - [convoy watch](/docs/cli/watch/) to see the reply. --- # convoy stop > Stop a whole swarm run or a single agent. Stopping a swarm ends its run as Stopped, after which convoy run can start a new one. ```text convoy stop [] ``` ## What it does Sends `{"reason": "stopped from the CLI"}` to the server and prints the resulting status. It acts on the latest run. - `convoy stop ` calls `POST /v1/swarms/{name}:stop`. Every non-terminal agent is stopped: processes are killed and tokens revoked. The run ends as Stopped with reason `stopped`, and `convoy run` may then start a new run of that name. - `convoy stop ` calls `POST /v1/swarms/{name}/agents/{agent}:stop`. The agent's children are stopped first, depth first, then the agent. The rest of the swarm keeps running. Both are idempotent: stopping something already in a terminal state succeeds and changes nothing. ## Examples ```console $ convoy stop edge_chips swarm "edge_chips" run 3 STOPPED (stopped), spend $4.87 ``` ```console $ convoy stop edge_chips researcher[tenstorrent] agent "researcher[tenstorrent]" stopped ``` Free the name, then start over: ```console $ convoy stop edge_chips && convoy run ``` ## Notes Stopping the whole swarm is the only way to replace a running one, because [`convoy run`](/docs/cli/run/) refuses with `swarm_active`. A run stopped by a human has end reason `stopped`. Runs stopped by the server itself end with `budget` or `max_runtime`. Outputs already produced are kept and readable with `convoy status --run N`. The agent form needs the caller to be the CLI, the overseer, or the agent's parent. The CLI always qualifies. ## Exit codes | Code | Cause | | --- | --- | | `0` | Stopped, or already in a terminal state | | `1` | Unknown swarm or agent (404), or server unreachable | | `2` | Missing argument | ## API endpoints - `POST /v1/swarms/{name}:stop` - `POST /v1/swarms/{name}/agents/{agent}:stop` ## Related - [convoy status](/docs/cli/status/) - [Swarms and runs](/docs/concepts/swarms/) - [Controller](/docs/runtime/controller/) --- # convoy ui > Open convoyd's Web UI in a browser, at the swarm list or at one swarm's latest run. The token is never put in the URL. ```text convoy ui [] [--print] ``` ## What it does Opens the [Web UI](/docs/runtime/web-ui/) that convoyd serves on its own port. - `convoy ui` opens `/`, the list of every swarm. - `convoy ui ` opens `/s//r/latest`, the graph of the swarm's latest run. `` is `--server` or `CONVOY_URL`, `http://localhost:7070` by default. Before opening anything, `ui` checks that `GET /` answers with HTML. If convoyd is not running, or was started with `--no-ui`, it says so and exits 1. The browser is opened with `open` on macOS, `xdg-open` on Linux, and `rundll32` on Windows. If none works, `ui` prints the URL to open by hand and exits 0. The token is never put in the URL. When convoyd runs with `--token`, the UI asks for the token once and keeps it in the browser. ## Flags | Flag | Meaning | | --- | --- | | `--print` | Print the URL instead of opening it | ## Examples ```console $ convoy ui edge_chips opened http://localhost:7070/s/edge_chips/r/latest ``` ```console $ convoy ui --print http://localhost:7070/ ``` ## Exit codes | Code | Cause | | --- | --- | | `0` | Opened, printed, or no browser available (the URL is printed) | | `1` | convoyd is unreachable or does not serve the UI | | `2` | More than one argument, or a `--server` that is not a URL | ## Related - [Web UI](/docs/runtime/web-ui/) - [convoy watch](/docs/cli/watch/) --- # convoy provider > List, show, pull, push, remove, validate, document, and test provider types. Everything that touches installed types is an API call to convoyd; validate and docs work on a local package folder. ```text convoy provider list convoy provider show [@] convoy provider pull [@] convoy provider push [dir] --source
[--version ] convoy provider rm @ convoy provider validate [dir] convoy provider docs [dir] convoy provider test [@] --model [--set =]... ``` [Provider types](/docs/providers/) live on convoyd. The CLI downloads no provider code and keeps no state: `list`, `show`, `pull`, `push`, `rm`, and `test` are API calls. `validate` and `docs` read a package folder on your machine and need no server; they are for authors. ## list Every type the server holds: the built-in ones, then installed versions by source, newest first. ```console $ convoy provider list SOURCE VERSION KIND ORIGIN claude_agent_sdk - builtin built in openai_agents - builtin built in openai_compatible - builtin built in acme/acme 1.5.0 preset git https://github.com/acme/convoy-provider-acme 3c1f9e2 acme/acme 1.4.2 preset git https://github.com/acme/convoy-provider-acme 9a07b11 acme/agents 0.0.0-dev driver push ``` ## show A type's attributes, settings, tools, and models with their prices, rendered like the [language reference](/docs/dsl/reference/#provider-types). Without `@`, the newest installed version. A built-in type needs no server. ```console $ convoy provider show acme/acme acme/acme 1.5.0 (preset) digest sha256:9f2c3a71…, origin git https://github.com/acme/convoy-provider-acme 3c1f9e2 # `acme` Acme Inference, Chat Completions API. A preset: the built-in `openai_compatible` driver runs its agents. | Attribute | Type | Required | Default | Meaning | ... ``` ## pull Asks the repository for the highest version that meets the constraint, fetches it unless the server already holds it, and checks a driver plugin. This is how a server moves to a newer version: swarms keep the version they resolved until someone pulls. It prints what you are trusting: the variables the type reads by default, and for a preset the URL and headers its `driver_config` sends them to, or for a driver plugin its command and the result of its check. ```console $ convoy provider pull acme/agents@~> 1.0 acme/agents 1.0.3 sha256:51d0e8… (driver) reads from convoyd's environment by default: api_key = ACME_API_KEY command: uv run --project {package} --frozen --no-dev convoy-provider-acme-agents check: ok (contracts [2], runner 0.2.0) ``` ## push Sends a package folder's files to convoyd, which installs them like a fetch (origin `push`) and checks a driver plugin. It is how an author tries a type before tagging it, and how a server that cannot reach a repository gets one. The version defaults to `0.0.0-dev`; pushing the same version again replaces it. `.git`, `.venv`, `__pycache__`, `node_modules`, and tool caches are skipped, files must be text, and the upload is limited to 32 MiB. ```console $ convoy provider push ./convoy-provider-acme --source acme/acme acme/acme 0.0.0-dev sha256:4b1e0c… (preset) ``` A version that came from git cannot be replaced by a push (`provider_exists`), and one an active run uses cannot be replaced or removed (`provider_in_use`). ## rm Removes an installed version and its package folder. ```console $ convoy provider rm acme/acme@1.4.2 removed acme/acme 1.4.2 ``` ## validate Parses `convoy-provider.hcl` in the folder (default `.`) and prints its diagnostics with their [manifest codes](/docs/providers/writing/#manifest-codes). No server. Exit 3 on errors; `--json` prints `{"valid", "diagnostics"}`. ```console $ convoy provider validate provider validate: ok (acme, a preset over openai_compatible: 3 attributes, 1 settings, 4 tools, 2 models) ``` ## docs Prints the folder's type reference as Markdown, with the renderer that writes Convoy's own language reference. ## test Runs a swarm with one agent, and the overseer, on the type under test, waits for it (`--timeout`, default 10m), and checks the result: the run ends `done`, the agent's transcript has a `tool_call` for `list_topics`, its first turn reports input and output tokens, and it reports a session id. These are the checks of Convoy's own driver tests. It spends real tokens. | Flag | Meaning | | --- | --- | | `--model` | The model to run. Required | | `--set` | A provider attribute, `=`. Repeatable | | `--timeout` | How long to wait for the run before stopping it | The swarm is named `provider_test_`, so `convoy status provider_test_acme_acme` shows it afterwards. ## Exit codes | Code | Cause | | --- | --- | | `0` | Success | | `1` | A server error, such as `provider_not_found`, `provider_in_use`, or a failed `test` check | | `2` | Usage error | | `3` | A manifest with errors, or a 422 from the server: `provider_manifest_invalid`, `provider_incompatible`, `provider_check_failed`, `provider_version_not_found` | ## API endpoints `GET /v1/providers`, `POST /v1/providers:resolve`, `POST /v1/providers:pull`, `POST /v1/providers:push`, `POST /v1/providers:remove`. See [HTTP API](/docs/architecture/api/#provider-types). ## Related - [Provider types](/docs/providers/) - [Using a provider type](/docs/providers/using/) - [Writing a provider type](/docs/providers/writing/) --- # convoyd > convoyd is the Go server that holds every swarm, run, agent, topic and message. It is the only way anything changes, and it starts one runner process per agent. `convoyd` is a single Go binary. It stores the state of every swarm, serves the HTTP API the CLI and the runners call, runs the controller loop, hosts the message board, and starts and stops the runner processes. The `convoy` CLI never holds state; if you close your terminal, the swarm keeps running here. ## The parts | Part | What it does | Page | | --- | --- | --- | | API server | REST, one SSE stream per run, and an MCP endpoint. One bearer token per agent. | [HTTP API](/docs/architecture/api/) | | Web UI | A browser view of every swarm, served at `/` on the same port. | [Web UI](/docs/runtime/web-ui/) | | Message board | Topics as append-only logs, one read cursor per agent per topic, the `wake` long poll. | [Message board](/docs/runtime/board/) | | Controller | A single loop that starts agents, flags stuck ones, enforces limits and the budget, and evaluates `done_when`. | [Controller](/docs/runtime/controller/) | | Overseer | A built-in agent started with every run. A runner with a fixed prompt. | [The overseer](/docs/concepts/overseer/) | | State store | SQLite in WAL mode: specs, status, the event log, messages, tokens. | [Storage](#storage) | | Process backend | Creates a work folder and runs the runner in it. Local processes in the MVP. | [Seams and contracts](/docs/architecture/contracts/#process-backend) | ## Process model One `convoyd` process serves every swarm on the machine. For each active run it starts one runner process per agent, the overseer included. A runner is a Python process, almost always blocked in a `wake` call. The example `edge_chips` swarm is eight runner processes on one laptop. - Each agent gets its own folder, `.convoy/work////`, under `--work-dir`. Brackets in an instance name are replaced with `__` on disk. - The runner reaches convoyd over HTTP only. It calls the REST API itself and the model calls the MCP tools, both with the agent's bearer token. See [Runner](/docs/runtime/runner/). - `--max-processes` (default 50) caps live runner processes across all runs, overseers included. An agent over the cap stays `pending` until a slot frees. - Provider API keys are read from convoyd's own environment when it starts a runner and handed to that runner only. They are never stored, never written to the bundle, and never returned by any endpoint. ## Storage The MVP ships one storage backend: SQLite through a pure-Go driver, in WAL mode, in one file (`--db`). No cgo, one binary, enough for one laptop and dozens of agents. Everything above storage depends on a small `store.Store` interface, so other backends stay possible. The store's contract: - Transactions are serializable. Every write goes through `Tx`, so a status change and its event row are atomic. - `seq` values for events and messages are strictly increasing per run with no gaps visible to readers. SSE replay with `after=` depends on this. - Run and agent status updates are compare-and-set: they apply only if the current status is the expected one. - A turn's row, the agent's spend, and the run's spend update in one transaction, so a reader never sees a turn without its cost. A **swarm** is a name. A **run** is one execution of that swarm from one bundle, with its own integer id and a number (1, 2, 3 within the swarm). Agents, turns, events, messages, topics and tokens each belong to exactly one run. Every run has its own board; a new run starts with an empty one. Earlier runs stay readable with `?run=N`. | Table | Holds | | --- | --- | | `swarms`, `runs` | Names; per run: status, goal, the stored bundle and its hash, limits, spend, `unpriced_turns`, the resolved overseer, the provider type version and digest each provider block resolved to (`providers`), `end_reason`, `end_detail` | | `providers` | The [provider types](/docs/providers/) convoyd holds: source, version, digest, kind, origin, and the compiled manifest. Built-in types have no rows | | `agents` | Status, resolved spec, parent and depth, counters, spend, `sdk_session_id`, `last_response_id`, `process_id`, output, progress timestamps | | `turns` | Per turn: model, the four token counts, `cost_usd` at the agent's price, the SDK's own `sdk_cost_usd` | | `progress_reports` | Every `report_progress` summary | | `events` | The event log | | `tokens` | Agent bearer tokens, stored as a sha256 hash | | `transcript_items` | Each agent's transcript: its prompt, inputs, text, reasoning, tool calls and tool results. See [Web UI](/docs/runtime/web-ui/#transcripts) | | `topics`, `messages`, `watches`, `read_cursors`, `wake_state`, `run_counters` | The board, see [Message board](/docs/runtime/board/#storage) | ### Event log Every write that changes an agent's or a run's status also inserts an event in the same transaction. The controller and the SSE broadcaster both consume the `events` table, so the log is the single source of ordering. `convoy watch` is that log, streamed. | Type | Payload | | --- | --- | | `run.created`, `run.started`, `run.ended` | `run`, `status`, `end_reason`, `end_detail`, `spend_usd` | | `agent.created` | `parent`, `declared`, `agent`, `depth`, provider, SDK, provider type `source` and `version`, model, tools, writes, watches, `can_spawn`, `max_turns`, `role_summary`, `input_deps`. Emitted for every agent, declared ones included | | `agent.started` | `process_id` | | `agent.session` | `sdk_session_id`, `last_response_id` (when first reported or changed) | | `agent.turn_started` | `turn` | | `agent.turn_ended` | `turn`, the four token counts, `cost_usd`, `run_spend_usd` | | `agent.progress` | `seq`, `summary` | | `agent.finished` | `output` | | `agent.exited` | `exit_code`, `signal` | | `agent.stuck`, `agent.unstuck`, `agent.stopped`, `agent.failed` | `reason` | | `agent.log` | `chunk` (4 KB; streamed over SSE only with `logs=1`) | | `message.published` | `seq`, `topic`, `to`, `reply_to`, `body` | | `topic.created` | `name`, `description`, `declared`, `builtin`. Emitted for every topic, declared and built-in ones included | | `topic.read` | `topic`, `cursor`, `read`: an agent's read cursor moved. At most one per agent and topic every 2 seconds | | `agent.watches` | `watches`: the agent's watches after `watch_topic` changed them | | `agent.tool_called` | `turn`, `idx`, `tool`: one per tool call in the agent's transcript | | `done_when.error` | `diagnostic` | The controller also emits `agent.blocked` and `agent.stop_requested`; see [Controller](/docs/runtime/controller/). A run's log starts with `run.created`, then a `topic.created` for every topic and an `agent.created` for the overseer and every declared agent, so the log alone rebuilds the run's graph. `topic.read`, `agent.watches` and `agent.tool_called` exist for the [Web UI](/docs/runtime/web-ui/); `convoy watch` ignores them. ### Pricing Prices come from provider types: each type's manifest lists its models with USD per million input, output, cache-read and cache-write tokens, and a provider's `price` attribute overrides them for that provider's models. The price is resolved once, into each agent's spec, when the agent is created. The server prices each turn from the runner's token counts: `cost_usd = tokens_in * in_price + tokens_out * out_price` (plus cache terms). The SDK's own figure is kept in `sdk_cost_usd` for comparison and is never used for the budget, so every SDK is charged by one rule. A model missing from the table is priced as unknown: `cost_usd` is NULL and `unpriced_turns` goes up. `convoy validate` rejects a swarm that sets `max_cost_usd` and uses an unlisted model, and the server repeats the check on `PUT` against its own table, so a run with a budget never has unpriced turns. ## Authentication Middleware runs on every `/v1/` route. 1. Read `Authorization: Bearer `. If absent, the request comes from a loopback address and `--token` is empty, the caller is the CLI (`human`) and needs no token. The CLI token, when set, maps to the same identity. A browser page also connects from loopback, so tokenless requests are refused when `Host` is not `localhost` or a loopback IP (`bad_host`), or when `Origin` or `Sec-Fetch-Site` marks them cross-origin (`cross_origin`). Requests with a token skip these checks. 2. Otherwise `sha256(token)` is looked up in `tokens`. Missing or revoked is 401. 3. Routes under `/v1/swarms/{name}/...` return 403 when the token's run is not the latest run of `{name}`. A runner token stops working when it is revoked or a new run of the swarm starts. 4. Agent-only operations (`report_progress`, `finish`, `wake`, `watches`, and appending to its transcript) require the token's agent to match the agent in the path. The CLI may call `stop`, `say` and the read endpoints. The swarm list, the graph snapshot and transcript reads are for people only: a runner token gets 403 `people_only`. 5. `create_agent` from a runner records the caller as parent and requires its `can_spawn`. `stop_agent` from a runner must target an agent the caller created. Tokens are 32 random bytes, base64url, minted when the controller starts a runner and revoked when that runner process exits. A finished or stopped agent's runner can still report its last turn's usage and the end of its transcript while it shuts down, even after the run has ended. The sender of every message and the creator of every agent come from the token, never from the request body. ## Flags Every flag has an environment fallback where one is listed. | Flag | Env | Default | Meaning | | --- | --- | --- | --- | | `--port` | `CONVOYD_PORT` | `7070` | Listen port | | `--db` | `CONVOYD_DB` | `./convoy.db` | SQLite file | | `--work-dir` | `CONVOYD_WORK` | `./.convoy/work` | Root of agent work folders | | `--runner` | `CONVOYD_RUNNER` | the runner built into `convoyd`, started with `uv` | A runner executable of your own to use instead | | `--token` | `CONVOYD_TOKEN` | empty | The CLI token. Empty means loopback requests need none | | `--public-url` | `CONVOYD_PUBLIC_URL` | `http://127.0.0.1:` | Address runners use to reach convoyd. Required by a backend whose processes run on another host | | `--max-processes` | `CONVOYD_MAX_PROCESSES` | `50` | Most runner processes alive at once, across all runs | | `--no-ui` | `CONVOYD_NO_UI` (`1` or `true`) | off | Do not serve the [Web UI](/docs/runtime/web-ui/) at `/`. The API is unchanged | | `--stuck-after` | | `20m` | Time without progress before a running agent is marked stuck | | `--debounce` | | `5s` | Quiet period before a message gives an agent a turn | | `--tick` | | `5s` | Controller pass interval | | `--stop-grace` | | `5s` | How long a stopping agent has to exit | | `--kill-grace` | | `3s` | SIGTERM to SIGKILL | | `--overseer-interval` | | `5m` | Heartbeat to the overseer | | `--wake-timeout` | | `30s` | Length of one `wake` long poll | | `--provider-dir` | `CONVOYD_PROVIDER_DIR` | `./.convoy/providers` | Where [driver plugin](/docs/providers/) packages are kept, as `//`. Presets keep nothing on disk | | `--provider-timeout` | | `5m` | How long a request waits for a provider fetch or check. A fetch continues after the request gives up; a check is stopped | | `--overseer-provider`, `--overseer-model`, `--overseer-base-url`, `--overseer-api-key-env` | | none | Server-wide default overseer, used only when the swarm declares no `overseer`. `--overseer-provider` is a built-in type; the base URL and key variable set its `base_url` and `api_key`. Optional | | `--overseer-can-spawn` | | `true` | `can_spawn` for the default overseer | Fetching provider types needs `git` on convoyd's `PATH`, and a Python driver plugin needs `uv` on the runner's `PATH`. convoyd fetches a type the first time a swarm names a version it does not hold; there is no setting for it. See [Provider types](/docs/providers/). convoyd starts without any overseer flags. A run whose swarm declares no `overseer`, on a server with no default, is rejected with `overseer_missing`. `convoyd gc` removes the work folders and boards of ended runs. `SIGTERM` stops accepting requests, sends stop to every running agent, waits up to 10 seconds, kills what remains, marks every active run `failed` with `end_reason = server_restart`, and exits. In the MVP, restarting convoyd ends every active run. On start it marks each non-terminal agent and run `failed` with `end_reason = server_restart` and kills leftover runner processes. See [Durability](/docs/runtime/durability/). ## Logging convoyd logs JSON lines to stderr with `log/slog`. At start it logs the address it listens on and, unless `--no-ui` is set, the Web UI's address (`{"msg":"web ui","ui":"http://127.0.0.1:7070/"}`). Runner stderr is stored separately as `agent.log` events. --- # Controller > The controller is one loop in convoyd that keeps a run's actual state matching its declared state. This page is the full state machine, covering every state, transition, trigger and action. The controller makes decisions that can be computed from state: has an agent crashed, is it stuck, has it finished, has a limit or the budget been reached. Anything that needs judgment is delegated to the [overseer](/docs/concepts/overseer/) by publishing a message. The controller works on runs. A `convoy run` on a swarm with no active run creates a new run; a second one while a run is `pending` or `running` is rejected with 409, so the controller never changes a running swarm's declared agents. ## Design rules 1. **One goroutine.** Every decision is made in one loop, in order, against a consistent read of the store. Process exit watchers only post events. 2. **Every transition is a store transaction that also writes an event.** Either the state change and its event both exist, or neither does. 3. **Decisions are recomputable.** The loop holds nothing in memory it could not rebuild from the store. 4. **Mechanical facts only.** Judgment goes to the overseer. ## Triggers A pass runs when any of these happens: - A tick, every 5 seconds (`--tick`). - The store commits an event. The store signals a buffered channel of size 1 after every event-writing transaction; coalescing is fine because a pass reads everything. - A process exits. The backend's wait goroutine writes an `agent.exited` event, which is itself a commit. A pass runs the run rules, then the agent rules, for every run whose status is `pending` or `running`. Passes never overlap. ## States **Run:** `pending`, `running`, `done`, `stopped`, `failed`. The last three are terminal. Every terminal run has an `end_reason`: `done`, `budget`, `max_runtime`, `failed`, `stopped` or `server_restart`. **Agent:** `pending`, `running`, `idle`, `stuck`, `done`, `stopped`, `failed`. The last three are terminal. | State | Meaning | | --- | --- | | `pending` | Waiting for `inputs` and `depends_on` to be `done`, or for a free process slot | | `running` | In a turn | | `idle` | Between turns, waiting in `wake` | | `stuck` | A `running` agent that has not reported progress for too long. Not terminal | | `done` | `finish` was accepted | | `stopped` | Stopped by a person, the overseer, a parent, a limit or the run ending | | `failed` | The runner died, bad inputs, or the server restarted | The controller keeps per agent: `created_at`, `started_at`, `last_turn_at`, `last_progress_at`, `ended_at`, and the counters `turns`, `depth` and `cost_usd`. It records `sdk_session_id`, `last_response_id` and `process_id` for [post-MVP recovery](/docs/runtime/durability/) and reads none of them. Per run it keeps `started_at`, `ended_at`, `end_reason` and `cost_usd`, the sum over every agent including the overseer. ## Run transitions Rules are checked in table order. A pass that sees both the budget crossed and `done_when` true ends the run as `budget`, which keeps the budget a hard rule that a lucky finish cannot mask. | From | Condition | To | Actions | | --- | --- | --- | --- | | `pending` | first pass | `running` | set `started_at`; emit `run.started`; publish `swarm started` to `system`, addressed to `overseer` | | `running` | `max_cost_usd` set and run `cost_usd >= max_cost_usd` | `stopped` | `end_reason = budget`; stop every non-terminal agent; emit `run.ended` | | `running` | `now - started_at >= max_runtime` | `stopped` | `end_reason = max_runtime`; cascade; emit `run.ended` | | `running` | `done_when` evaluates true | `done` | `end_reason = done`; cascade; emit `run.ended` | | `running` | `done_when` returns a diagnostic | `running` | emit `done_when.error`, once per distinct message | | `running` | every agent terminal, `done_when` not true | `failed` | `end_reason = failed`; emit `run.ended` with detail `all agents ended without meeting done_when` | | `running` | a dead end: every agent has ended except pending ones blocked on a dependency that ended without an output, and the overseer has ended or may not create agents | `failed` | `end_reason = failed`; detail `no agent can make progress: ...` | | `running` | the provider refused an agent's key, or its account has no credit | `failed` | `end_reason = failed`; detail `agent X:` and the provider's words | | `running` | `POST :stop` | `stopped` | `end_reason = stopped`; cascade; emit `run.ended` | `done_when` is evaluated on every pass, not only after a `finish`, so a run never waits for a tick that did not come. The overseer is excluded from "every agent terminal": a run whose only live agent is the overseer counts as all agents terminal. ### Budget Spend enters the store in one place: the `wake` handler. Each `wake` carries the previous turn's token usage. The handler prices it, adds it to the agent's and the run's `cost_usd` in one transaction, and emits `agent.turn_ended`. The commit triggers a pass, and the first rule of the pass compares the run's `cost_usd` with `max_cost_usd`. The overseer's turns are priced and counted the same way. When the budget rule fires, every agent is stopped by the normal stop sequence and outputs already passed to `finish` are kept. Two kinds of overshoot are expected: - **Recorded overshoot.** Turns that end between the crossing and the stop still add to `cost_usd`. `convoy status` shows the recorded total, which may be above `max_cost_usd`. - **Unrecorded spend.** A turn cut off by the stop sequence's `SIGTERM` never reaches `wake`, so its usage is not recorded. This is bounded by one partial turn per agent that was mid-turn. When `max_cost_usd` is not set the rule never fires; spend is still recorded and shown. ## Agent transitions Agents are processed in this order: the overseer, then declared agents in the dependency graph's start order, then runtime-created agents by `created_at`. Within one pass an agent moves at most one transition. ### Starting | From | Condition | To | Actions | | --- | --- | --- | --- | | `pending` | gates satisfied and a process slot is free | `running` | start sequence; emit `agent.started` | **Gates satisfied** means every instance in the agent's `inputs` and every `depends_on` target is `done`. A dependency that is `failed` or `stopped` can never satisfy the gate. The agent stays `pending` until the run ends, and the pass emits `agent.blocked` once with the names of the ended dependencies. The overseer gets the same message on `system`. **A slot is free** means agents in `running`, `idle` or `stuck`, across every active run on this server and including overseers, number fewer than `--max-processes`. This is a limit on the machine, not on the swarm; the DSL has no attribute for it. Agents are admitted in rule order, so the overseer and then earlier declared agents win a scarce slot. **Start sequence:** 1. Resolve `inputs` from the producers' outputs. A diagnostic here fails the agent with `end_reason = bad_inputs`. 2. Mint a token. 3. Build `start.json` (see [Seams and contracts](/docs/architecture/contracts/#startjson)). 4. `Create` the work folder (idempotent), then `Exec` the runner with `start.json` in the files. Store `process_id`; set `started_at` and `last_turn_at` to now. 5. Start a wait goroutine that writes `agent.exited` with the exit code and signal. ### Turns | From | Condition | To | Actions | | --- | --- | --- | --- | | `running`, `stuck` | runner calls `wake` | `idle` | `turns += 1`; `last_turn_at = now`; price and record usage; record session ids; emit `agent.turn_ended` | | `idle` | `wake` returns news | `running` | `last_turn_at = now`; emit `agent.turn_started` | The `wake` handler performs both inside the board's transaction, because they must happen at the moment of the call. The first `wake` of a process ends the first turn, which began at start. ### Progress | From | Condition | To | Actions | | --- | --- | --- | --- | | `running`, `stuck` | `report_progress(summary)` | `running` | store the summary; `last_progress_at = now`; emit `agent.progress` (and `agent.unstuck` when leaving `stuck`) | ### Limits | From | Condition | To | Actions | | --- | --- | --- | --- | | `running`, `idle`, `stuck` | `turns >= max_turns` | `stopped` | `end_reason = max_turns`; stop sequence | The runner also exits with code 4 on its own count. Whichever comes first wins and the other is a no-op. ### Stuck | From | Condition | To | Actions | | --- | --- | --- | --- | | `running` | `now - max(started_at, last_turn_at, last_progress_at) >= stuck_after` | `stuck` | emit `agent.stuck`; publish to `system`, addressed to `overseer`: `agent researcher[groq] stuck: no progress for 20m; last progress: ...` | Only `running` agents become stuck. An `idle` agent is waiting by design. `stuck_after` defaults to 20 minutes. Being stuck changes nothing about the process: the controller does not kill or restart it. What to do is the overseer's decision. A stuck agent is still bounded by `max_turns`, `max_runtime` and `max_cost_usd`. A stuck agent returns to `running` on its next `report_progress` and to `idle` when its turn ends. ### Exits | From | Condition | To | Actions | | --- | --- | --- | --- | | `running`, `idle`, `stuck` | process exited, status already `done` | `done` | none; `agent.finished` already exists | | same | exited, a stop was requested | `stopped` | finish the stop sequence | | same | exited with code 4 | `stopped` | `end_reason = max_turns` | | same | exited 0, not `done`, no stop requested | `failed` | `end_reason = runner_error`, detail `exited 0 without finish` (a runner bug, logged) | | same | exited 1 or by signal | `failed` | `end_reason = runner_error`, detail with the code or signal | | same | exited 2 | `failed` | `end_reason = bad_invocation` | Exit code 3 is reserved and treated like code 1. Every transition to `failed` also revokes the token, stops the agent's children, emits `agent.failed`, and publishes `agent X failed: ` to `system` for the overseer. There are no restarts in the MVP. A runner that dies takes its agent with it and the run continues with the agents it has left. Exits are processed exactly once: `agents.last_processed_event_seq` records the last `agent.exited` event handled, and the same transaction that updates state advances it. ### Finish | From | Condition | To | Actions | | --- | --- | --- | --- | | `running`, `stuck` | `POST :finish` accepted | `done` | store output; `ended_at = now`; emit `agent.finished`; the next `wake` returns `{stop, reason: finished}`; the token is revoked after the process exits | The finish handler performs this. The loop then evaluates gates for dependents and `done_when` on the triggered pass. ### Stop The stop sequence is used by `POST :stop`, the run-level cascade, limits, failures and parent stops: 1. Mark the agent stopping in memory (not a stored status) and emit `agent.stop_requested` with the reason. 2. Stop children first, depth-first, each through this same sequence. 3. Signal the board so a blocked `wake` returns at once with `{stop: true, reason}`. 4. Wait up to `--stop-grace` (5 seconds) for `agent.exited`. 5. If the process is still alive, destroy it: `SIGTERM` to the process group, then `SIGKILL` after `--kill-grace` (3 seconds). 6. Set status `stopped` (unless it became `done` meanwhile; `done` wins), set `ended_at` and `end_reason`, revoke the token, emit `agent.stopped`. Steps 4 and 5 are not blocking waits. The loop records the request time in memory and checks it on later passes, so a run-level cascade completes over one or two passes. `run.ended` is emitted with the run's status change, so `convoy watch` ends as soon as the run does; the cascade's `agent.stop_requested` and `agent.stopped` events follow it. ### Token lifetime An agent's token is revoked when its runner process exits, in the same transaction as `agent.exited`, whatever the agent's status and whatever the run's. When a run's cascade finishes, the tokens of agents with no live process are revoked too; agents whose runner is still shutting down keep theirs until it exits. So the agent whose `finish` ended the run still reports that last turn's usage on its next `wake`, and the turn is counted in the run's spend, and a finished or stopped agent's runner can store the end of its transcript for the [Web UI](/docs/runtime/web-ui/). ## The overseer's schedule The overseer is an agent row that watches `system`, so the board wakes it like any other agent. The controller's part is publishing to `system` as sender `convoyd`, addressed to `overseer`: | When | Message | | --- | --- | | Run started | `swarm started; N agents pending` | | Every `--overseer-interval` (5 min) while running | `tick: elapsed 00:41 of 4h; spend $3.12 of $20.00; running 2, idle 4, stuck 0, done 1, pending 0` | | `agent.stuck` | `agent X stuck: no progress for 20m; last progress: ...` | | `agent.failed` | `agent X failed: ` | | `agent.finished` | `agent X finished`, plus the first 500 characters of the output | | `agent.blocked` | `agent X cannot start: dependency Y is ` | Messages another agent addresses to `overseer` go through the board directly. Several events within the debounce window become one overseer turn. With no `max_cost_usd` the tick shows `spend $3.12 (no cap)`. ## Recovery on restart The MVP does not resume work after convoyd restarts. On start, before serving requests: 1. For every run that is `pending` or `running`, in one transaction per run: set every non-terminal agent to `failed` with `end_reason = server_restart`, revoke its tokens, emit `agent.failed`; then set the run to `failed` with `end_reason = server_restart` and emit `run.ended`. 2. For every affected agent with a stored `process_id`, kill it. Usually the process is already gone; this catches survivors. 3. Run one pass, which finds no active runs. A new `convoy run` on the same swarm starts a fresh run. The failed run stays readable with `convoy status --run N`. The local backend accepts that a pid reused by an unrelated process since the crash would be signalled too. Resuming the real SDK session from the stored session id, cursors and process handle is designed but not built. See [Durability](/docs/runtime/durability/). ## Timing parameters | Flag | Default | Used by | | --- | --- | --- | | `--tick` | `5s` | Pass interval | | `--stuck-after` | `20m` | Stuck rule | | `--stop-grace` | `5s` | Stop sequence step 4 | | `--kill-grace` | `3s` | `SIGTERM` to `SIGKILL` | | `--overseer-interval` | `5m` | Heartbeat to `system` | | `--wake-timeout` | `30s` | Board `Wake` | | `--max-processes` | `50` | Admission | ## Concurrency The loop and the HTTP handlers both write to the store. Handlers perform only the transitions marked above as theirs: turn start and end, progress, finish, agent creation and stop requests. Each is one transaction guarded by a status check in SQL (for example, `UPDATE agents SET status='done' ... AND status IN ('running','stuck')`), so a handler racing the loop cannot move an agent out of a terminal state. The loop re-reads state at the start of every rule. --- # Message board > How topics, messages, read cursors, the debounce and the wake long poll work, and what delivery guarantees an agent gets. The board pushes **that** something happened and lets each agent pull **what** happened. It is the package `server/internal/board` inside convoyd. For the model of topics and watches from an agent's side, read [Topics and the board](/docs/concepts/board/). This page is the mechanism. ## Model - A **topic** is a named, append-only sequence of messages within one run. - A **message** has a sequence number within the run, a topic, a sender, a body, an optional `to` (one agent name) and an optional `reply_to` (a sequence number in the same run). - Every agent can read every topic. An agent **writes** to the topics in its allowlist. - An agent **watches** topics. Watches decide when an agent gets a turn: a new message on a watched topic, or a message addressed to the agent, gives it a turn after the debounce. - A turn's input is an **unread summary**: for every topic, how many messages the agent has not read, their sequence range, and who sent them. Messages addressed to the agent are included in full. - The agent **pulls** with `read_topic`. The board keeps a **read cursor** per agent and topic: the highest sequence number `read_topic` has returned to that agent on that topic. Only `read_topic` moves it. ## Storage All tables are keyed by `run_id`. Every run has its own board. | Table | Columns | Notes | | --- | --- | --- | | `topics` | `name`, `description`, `declared`, `created_by`, `created_at` | `declared = 0` for built-in and runtime-created topics | | `messages` | `seq`, `topic`, `sender`, `recipient`, `reply_to`, `body`, `at` | `seq` is per run. Sender is an agent name, `human` or `convoyd`. Body is at most 64 KB | | `run_counters` | `next_seq` | Updated in the same transaction as each insert | | `watches` | `agent`, `topic` | | | `read_cursors` | `agent`, `topic`, `cursor` | No row means 0, nothing read | | `wake_state` | `agent`, `notified_seq`, `addressed_cursor`, `agents_version`, `wake_due_at`, `wake_first_at` | Which messages already caused a turn, and when the next one is due | A per-run sequence rather than a global one keeps `seq` small, dense and meaningful in prompts (`#57`). Nothing is ever deleted, so the full history is always readable. ### Two cursors, two jobs `wake_state.notified_seq` answers "has this message already caused a turn?" It moves when a turn is handed out. `read_cursors.cursor` answers "has the agent read this?" It moves only on `read_topic`. They never substitute for each other. An agent that ignores a topic is not woken again for the same messages, and those messages stay unread in every later summary. ## Built-in topics When a run is created the server inserts every declared topic and two built-in topics: | Topic | Description | Writers | Watched by | | --- | --- | --- | --- | | `progress` | Overseer progress notes | the overseer (through `note_progress`), `convoyd` | nobody by default | | `system` | Controller events for the overseer | `convoyd` only | the overseer | Both are readable by every agent. `convoy status` and `convoy watch` show `progress`. `system` gives the overseer an ordered record of what the controller did, which it can re-read with `read_topic("system")`. The overseer cannot write to `system`; if it could, it could wake itself in a loop. There is no built-in `human` topic. Swarms declare their own (the `convoy goal` prompt always does), and `convoy say` can target any topic. A message sent to `human` with `to` wakes nobody; it is for people reading the board. A topic created at runtime with `create_topic` is added to its creator's `writes` in the same transaction. Every topic has a `topic.created` event: declared and built-in topics when the run is created, runtime topics when they are created, with the creator as the event's agent. `watch_topic` emits `agent.watches` with the agent's sorted watches when it adds one. ## Publish Checks, then one transaction: 1. The topic exists; the body is at most 65,536 bytes; `to` is empty, `human`, or names an existing agent in the run; `reply_to` is zero or exists. 2. Authorization: the caller is `human`, is `convoyd`, or has the topic in its `writes`. Otherwise `not_writer`. 3. Allocate `seq`, insert the message, insert a `message.published` event. 4. Compute recipients: agents watching the topic, plus `to` (unless it is `human`), minus the sender, minus agents in a terminal status. 5. For each recipient, set `wake_first_at` if unset and `wake_due_at = min(now + debounce, wake_first_at + max_hold)`. 6. After commit, notify each recipient's waiter. Publishing never moves anyone's read cursor, the sender's included. The sender is excluded from its own wake, so an agent that publishes to a topic it also watches does not wake itself. ## Debounce | Setting | Default | Effect | | --- | --- | --- | | Debounce | 5 s | A lone message gives the agent a turn 5 seconds later. A burst of 30 in 2 seconds becomes one turn | | Max hold | 30 s | A steady stream cannot postpone the turn forever. The agent wakes at least every 30 seconds while messages keep arriving | The `min(...)` is a trailing debounce with a cap. The debounce is `--debounce`. ## Wake The runner calls `POST /agents/{a}/wake` between turns. The handler calls the board with a 30-second timeout. ```text Wake(run, agent, timeout): loop: if stop pending for (run, agent): clear it; return {stop, reason} if wake_due_at is set and now >= wake_due_at: result = collect(run, agent) if result.woken: return result clear wake_due_at, wake_first_at # spurious: nothing new wait until the earlier of the deadline and wake_due_at, or a waiter fires if the deadline passed: return {woken: false} collect(run, agent), in one transaction: triggers = messages with seq > notified_seq, sender != agent, on a watched topic or addressed to agent if none: return {woken: false} addressed = messages to agent with seq > addressed_cursor notified_seq = head of the run; addressed_cursor = max addressed seq clear wake_due_at and wake_first_at unread = Unread(run, agent); delta = agent-set changes since last wake ``` `notified_seq` moves to the head of the run, not just past the triggers, because the turn's unread summary already reports every message up to the head. A message on an unwatched topic never triggers a turn by itself, but it appears in the next summary. Waiters are an in-memory map of buffered channels keyed by run and agent. A notify never blocks, and a missed notify is harmless because the loop re-reads `wake_due_at` after any wakeup. The timeout keeps long polls renewable through proxies and lets the server shut down cleanly. **Agents with empty `watches` never wait.** They work until they call `finish`. For them `Wake` skips the loop: if a stop is pending it returns `{stop: true, reason}`; otherwise it collects at once, without the trigger check, and returns `{woken: true, continue: true, addressed, unread, delta}`. `continue` tells the runner to start a continuation turn. Addressed messages reach such an agent this way, with no debounce. **First turn.** The first turn is not produced by `wake`: the runner starts it from `start.json`, and its first `wake` call follows. Messages published before that call are picked up by it if they are past `notified_seq` and on a watched topic or addressed to the agent, so nothing addressed to an agent during its first turn is missed. ### Wake responses | Response | Meaning | | --- | --- | | `{woken: true, addressed, unread, delta}` | A turn is ready. `addressed` is in full; `unread` has one entry per topic; `delta` is set once after the agent set changed | | `{woken: true, continue: true, ...}` | Agent with no watches; keep working | | `{stop: true, reason}` | Exit. Reasons: `finished`, `stopped`, `max_turns`, `budget`, `swarm_ended` | | `{woken: false}` | 30 seconds passed with nothing new; call again | ## Unread For each topic in the run, the unread entry contains the topic name, whether it is watched, the count of messages past the agent's read cursor, the first and last unread `seq`, a count per sender, and the topic's total. It excludes the agent's own messages and addressed messages already given in full. An addressed message counts as read once it has been delivered in full, even though the topic cursor has not reached it. Every topic in the run is listed. ## Read `read_topic(topic, after?, limit?)`: - `after` defaults to the agent's read cursor, so `read_topic(t)` returns the next unread page and an agent that reads in a loop reads everything once. - `limit` defaults to 50 and is capped at 200. - After a read by an agent, its cursor becomes the larger of the old cursor and the last `seq` returned. Reads by the CLI or `convoyd` never move cursors. - The cursor is a high-water mark. Reading `after = 90` on a topic whose cursor is 40 moves it to the last row returned, and messages 41 to 90 stop counting as unread. That is deliberate: the agent chose to skip them, and `read_topic(t, after = 40)` still returns them. - An unknown topic is 404 `topic_not_found`, with a suggestion from the run's topic names. - An agent's read that moves its cursor emits `topic.read` with `{topic, cursor, read}`, where `read` counts the topic's messages at or before the cursor. It is coalesced to at most one event per agent and topic every 2 seconds: the first read is reported at once, and later reads in the window produce one event, with the latest cursor, when the window closes. The [Web UI](/docs/runtime/web-ui/) draws who reads what from these events. ## Addressed messages `to` names one agent. The message stays in its topic and is readable by everyone. For the recipient it triggers a turn whether or not the recipient watches the topic, and it appears in full in the next wake result. An agent that watches the topic and is also the recipient gets one turn and sees the message once in full. Unknown recipients are rejected so a typo is visible to the model as a tool error. ## What a turn's input looks like The runner formats a wake result as the user turn: ```text NEW ACTIVITY TO YOU (2) [#60] progress overseer -> writer Prioritize sections 2 and 3; the researchers for 4 are still working. [#61] human human -> writer Skip Tenstorrent. UNREAD BY TOPIC (read_topic("") returns the next unread page) review * 1 unread #58 critic 1 findings 7 unread #120-#126 researcher[groq] 4, researcher[nvidia] 3 no unread: drafts, human, progress, system AGENTS CHANGED: +researcher_groq_patents, -researcher[groq] ``` - `TO YOU (n)` lists addressed messages in sequence order, one header line each (`[#seq] topic sender -> to (reply to #n)`), then the body. It is omitted when there are none. - `UNREAD BY TOPIC` lists topics with unread messages, watched topics first, then by count descending. `*` marks a watched topic. Each line has the count, the sequence range and up to five senders with counts. - Topics with nothing unread collapse into the `no unread:` line. - `AGENTS CHANGED` appears only when the wake carries a delta. It is how an agent learns about created and stopped agents, since the agent list in its system prompt is fetched once at start. ## Delivery guarantees - **Turns.** Each message triggers at most one turn per agent. - **Content.** Nothing is lost to an agent that reads. A message stays in the unread summary of every later turn until the agent reads past it. - **Addressed messages.** Given in full at most once, in the turn that hands them out, then counted as read. They stay in their topic and can be read again. - **History.** Nothing is deleted. In the MVP a runner that crashes mid-turn ends its agent as `failed`, so there is no redelivery path. The cursors and `notified_seq` are stored on every change so that [post-MVP recovery](/docs/runtime/durability/) can resume from exactly what the agent had seen and read. ## Limits | Limit | Value | Error | | --- | --- | --- | | Message body | 64 KB | 413 `body_too_large` | | Read page | 50 default, 200 max | | | Debounce, max hold | 5 s, 30 s | | | Topic name | identifier regex, 64 characters | | | Topics per run | 100 | 409 `topic_limit` | There is no retention or compaction in the MVP. An ended run keeps its board until `convoyd gc`. Publish, collect and the cursor update are short SQLite transactions; the board serializes `Publish` and `collect` with a mutex per run. --- # 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 `//`. 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 `/.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 / --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": "", "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__` | | `openai_agents` | `openai-agents` | MCP through `MCPServerStreamableHttp`. A `SQLiteSession` in `session.db` in the work folder continues the conversation. Session id is `:`. 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], ...): THE BOARD ``` 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////` 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. --- # Swarm tools (MCP) > The ten tools every agent gets, plus the overseer's extra one. convoyd serves them over Streamable HTTP MCP, and each is a thin wrapper over a REST handler. convoyd is an MCP server. It serves the swarm tools at `POST /v1/swarms/{name}/mcp`, one MCP instance per active run, created lazily. Both agent SDKs attach it as a remote MCP server with the agent's bearer token, so the tools are written once in Go and work for every SDK. The token identifies the caller; `{me}` below is the token's agent. Each tool handler calls the same Go function the REST handler calls, so there is one implementation per operation. Tool errors (the 422 and 409 bodies) are returned as MCP tool results with `isError: true` and the message text, which the SDKs show to the model. The model can correct and retry inside the same turn. ## Tools | Tool | Input | REST call | Who may call it | | --- | --- | --- | --- | | `list_topics` | none | `GET /topics` | Every agent | | `read_topic` | `topic: string`, `after?: integer`, `limit?: integer` | `GET /topics/{t}/messages` | Every agent | | `publish` | `topic: string`, `body: string`, `to?: string`, `reply_to?: integer` | `POST /topics/{t}/messages` | Agents with the topic in `writes` | | `watch_topic` | `topic: string` | `POST /agents/{me}/watches` | Every agent, for itself | | `create_topic` | `name: string`, `description: string` | `POST /topics` | Every agent | | `list_agents` | none | `GET /agents` | Every agent | | `create_agent` | `hcl: string` | `POST /agents` | Agents with `can_spawn`, and the overseer when its `can_spawn` is true | | `stop_agent` | `name: string`, `reason: string` | `POST /agents/{name}:stop` | The creating parent; the overseer for its children or stuck agents | | `report_progress` | `summary: string` | `POST /agents/{me}/progress` | Every agent, for itself | | `finish` | `output: object` | `POST /agents/{me}:finish` | Every agent except the overseer | | `note_progress` | `text: string` | publish to `progress` | The overseer only | All REST paths are under `/v1/swarms/{name}`. See [HTTP API](/docs/architecture/api/) for every request and response. ### `list_topics()` Returns every topic with its description, writers, watchers, message count and the caller's unread count. Agents also get this at the start of each turn. ### `read_topic(topic, after?, limit?)` Returns messages with `seq` greater than `after`, oldest first, at most `limit` (default 50, maximum 200). `after` defaults to the caller's read cursor, so `read_topic(t)` returns the next unread page. The call advances the caller's cursor to the highest `seq` returned. An explicit `after` below the cursor returns history without moving the cursor back. Errors: `topic_not_found`, with a suggestion. ### `publish(topic, body, to?, reply_to?)` Appends a message. The sender comes from the token. With `to`, the named agent also gets a turn and sees the message in full, whether or not it watches the topic. Every other watcher gets a turn after the debounce. Errors: `not_writer` (the topic is not in the caller's `writes`), `topic_not_found`, `body_too_large` (over 64 KB), an unknown `to` or `reply_to`. ### `watch_topic(topic)` Adds the topic to the caller's `watches`. Messages published to it after the call can give the agent a turn; the read cursor is unchanged. ### `create_topic(name, description)` Creates a topic and adds it to the caller's `writes`. The name must match the identifier rule and be at most 64 characters. Errors: `topic_limit` (100 topics per run) and a name that already exists. ### `list_agents()` One row per agent: name, status, parent, whether declared, `can_spawn`, turns, spend, provider, model, a one-line role summary (the first non-empty line of the prompt, 100 characters), the last progress summary and timestamps. Sorted by name. ### `create_agent(hcl)` Adds one agent to the running swarm. `hcl` must contain exactly one `agent` block and nothing else. It is decoded against the run's configuration, so `provider.x` and `topic.x` resolve. `count` and `for_each` are rejected. `inputs` and `depends_on` are allowed and resolve against existing instances. The caller becomes the parent, the child starts `pending`, and its depth is the caller's plus one. Checks, each a 409 unless noted: | Code | Reason | | --- | --- | | `spawn_not_allowed` | The caller's `can_spawn` is false | | `depth_limit` | The child's depth would exceed 3 | | `tools_not_allowed` | The child lists a tool its parent does not have | | `model_not_allowed` | The child's provider or model differs from the parent's and no declared agent uses it | | `agent_exists` | The name is taken | | 422, with diagnostics | Not exactly one `agent` block, `count` or `for_each` used, or a reference does not resolve | The overseer follows a different rule, because it has no tools: its child's tools, provider and model must each appear on at least one declared agent. A child may declare `can_spawn = true`; it then follows the parent-subset rule for its own children. There is no limit on how many agents exist. `--max-processes` leaves extra agents `pending`, and spend is bounded by `max_cost_usd`. The tool is registered only for callers with `can_spawn`, but it is checked on every call, so hiding it is a convenience. ### `stop_agent(name, reason)` Stops the named agent, children first, depth-first. A runner may stop only agents it created; the overseer may stop its own children and any agent in `stuck`. Terminal states are idempotent. Error: `not_parent`. ### `report_progress(summary)` Records what is done and what is next, at most 4 KB. It resets the stuck timer and returns a `stuck` agent to `running`. The latest summary is what `list_agents`, `convoy status` and the overseer show for the agent. ### `finish(output)` Ends the agent with its output, at most 256 KB. The server checks the output against the agent's declared `output` type. A mismatch is a 422 `output_mismatch` with the path of the bad field; the agent stays running and the model can try again. On success the agent becomes `done`, the controller evaluates `done_when` and the gates of dependent agents, and the next `wake` tells the runner to exit. The overseer is rejected with `the overseer does not finish; the server ends the swarm`, and the tool is not registered on its session. ### `note_progress(text)` Overseer only. Publishes to the built-in `progress` topic as `overseer`. It exists separately from `publish` so the overseer's prompt can say "always end with note_progress" and the server can check it: if a turn ends without a note, the server publishes `[overseer ended its turn without a note]` on its behalf. It is not `report_progress`, which stores a summary on the agent's own row. ## Errors you will see | Code | Status | From | | --- | --- | --- | | `not_writer` | 403 | `publish` | | `topic_not_found` | 404 | `read_topic`, `publish` | | `body_too_large` | 413 | `publish` | | `topic_limit` | 409 | `create_topic` | | `spawn_not_allowed`, `depth_limit`, `tools_not_allowed`, `model_not_allowed`, `agent_exists` | 409 | `create_agent` | | `not_parent` | 403 | `stop_agent` | | `output_mismatch` | 422 | `finish` | | `overseer_cannot_finish` | 403 | `finish` | | `run_ended` | 409 | any write after the run is terminal | ## Tool names in each SDK In the Claude Agent SDK the tools are named `mcp__convoy__`. In the OpenAI Agents SDK they appear under the MCP server named `convoy`. SDK built-in tools such as `bash` and `web_search` are separate and come from the agent's `tools` list; see [Runner](/docs/runtime/runner/#tool-name-mapping). --- # Web UI > convoyd serves a browser UI on its own port. It shows every swarm and run as a live graph of agents and topics, each agent's reasoning and tool calls, and the message board, with the same controls as the CLI. convoyd serves a web UI at `/` on the same port as its API. It is built into the `convoyd` binary, so there is nothing else to install or run. It covers every swarm on the server and every past run, not only live ones. A finished run opens in the same views, showing its final state. ## Open it Start convoyd, then open `http://127.0.0.1:7070/`, or run: ```console $ convoy ui # the list of swarms $ convoy ui edge_chips # the latest run of edge_chips ``` convoyd logs the address at start: `{"msg":"web ui","ui":"http://127.0.0.1:7070/"}`. See [convoy ui](/docs/cli/ui/). | Page | Path | | --- | --- | | Swarms | `/` | | Runs of a swarm | `/s/{swarm}` | | A run's graph | `/s/{swarm}/r/{run}` | | A run's board | `/s/{swarm}/r/{run}/board` | | One agent | `/s/{swarm}/r/{run}/a/{agent}` | `{run}` is a run number or `latest`. Agent names with brackets, such as `researcher[nvidia]`, are URL-encoded. ## Views ### Swarms One row per swarm: its latest run's number and status, start time and duration, spend against the budget, and agent counts by status. Rows refresh every 5 seconds while a run is going. A row opens the latest run's graph, and the swarm's page lists every run. ### Graph A run's agents and topics as a live graph. The header shows the goal, the status, elapsed time against `max_runtime`, spend against `max_cost_usd`, the `done_when` text, and a **Stop swarm** button. Agents are cards colored by status, with their model, turns, spend, and the tool they are calling while they run. The overseer has its own border. Topics are a different shape, with their message counts. `for_each` instances of one agent are grouped in a frame named after the block. | Edge | Between | Style | Meaning | | --- | --- | --- | --- | | Dependency | agent to agent | solid grey | The agent waits for the other's output, through `inputs` or `depends_on` | | Spawn | parent to child | dashed purple | The parent created the child with `create_agent` | | Publish | agent to topic | blue, wider with more messages | The agent published to the topic | | Read | topic to agent | teal, wider with more messages read | The agent read the topic with `read_topic` | | Watch | topic to agent | dotted, faint teal | The agent watches the topic but has read nothing from it yet | A pending run shows the declared graph with every agent grey. As the run goes, spawned agents appear next to their parents and runtime topics join the topic lane, and existing nodes keep their places. A dot travels from sender to topic for each message, and on to the recipient when it is addressed. The legend toggles each edge type. Clicking an agent opens it in a side panel. Clicking a topic opens the board filtered to it. ### Agent The header shows the agent's status, model, parent and children, dependencies, turns of `max_turns`, tokens and spend, timing, and end reason. **Stop agent** stops it and its children; **Message** opens the composer addressed to it. | Tab | Shows | | --- | --- | | Transcript | The agent's turns: what woke each one, its assistant text, reasoning, tool calls with their results, and errors. Follows the live tail | | Messages | Everything the agent sent and everything addressed to it | | Spec | Prompt, tools, writes, watches, output type, inputs, `can_spawn`, and the system prompt | | Output | The `finish` payload | | Progress | Its `report_progress` summaries | | Logs | The runner's log lines | Swarm tools link out from the transcript: a `publish` call to its message on the board, a `create_agent` call to the child, a `finish` call to the Output tab. ### Board Topics on the left, with their writers and watchers. Messages in the middle in sequence order, with sender, recipient, replies, and filters. On the right, a matrix of who talks to whom: one row per sender, one column per topic or addressed agent, each cell a message count. A second mode shows each agent's read position on each topic. The composer posts as `human` to any topic, optionally addressed to one agent, like [`convoy say`](/docs/cli/say/). ## Transcripts Each runner streams its agent's transcript to convoyd while the agent works, and convoyd stores it with the run. | Item | What it is | | --- | --- | | `system` | The system prompt, once | | `input` | What started each turn: the task, a continue nudge, or the unread summary | | `text` | Assistant text | | `reasoning` | Thinking or reasoning summaries, when the model produces them | | `tool_call` | A tool the model called, with its arguments | | `tool_result` | What the tool returned | | `error` | An error that ended a turn | Items appear when the SDK finishes each block; text is not streamed token by token. A field over 64 KB (256 KB for the system prompt) is cut and marked with its original size. Tool names are Convoy's names on every SDK, such as `web_search` and `publish`. Reasoning appears only when the model returns it. Without it, the text between tool calls is usually a good account of the agent's thinking. A transcript holds everything the agent's tools returned. If an agent's `bash` prints an environment variable or a file with a secret, the transcript has it. Only people can read transcripts: runner tokens get 403 `people_only`, so one agent cannot read another's. A transcript failure never affects the agent: the runner retries, then drops the batch and logs it. The run's board and events stay the record of what happened. ## Access The UI calls the same [HTTP API](/docs/architecture/api/) as the CLI, as `human`. - **Local, no token.** With `--token` unset, a browser on the same machine needs no login. convoyd refuses tokenless requests whose `Host` is not `localhost` or a loopback address, and requests another site's page sends, so a web page you visit cannot stop your swarms or message your agents. - **With `--token`.** The UI asks for the token once and keeps it in the browser. It is sent as `Authorization: Bearer`, never in a URL. Sign out clears it. The UI refuses an agent's runner token. Every UI page is served with a content security policy that allows only convoyd's own scripts and forbids framing. The controls are the CLI's: stop the swarm, stop an agent, post a message. They act on the latest run while it is active. ## Headless servers `--no-ui` (or `CONVOYD_NO_UI=1`) leaves the UI off. The API is unchanged, and `convoy ui` reports that the server does not serve it. ## Try it without a model A checkout of the repository has a demo swarm that runs on the runner's scripted fake driver, with no model and no API key. It needs Go and the runner's environment (`cd runner && uv sync`). ```sh webui/e2e/demo/serve.sh # convoyd on port 7071, then the demo swarm ``` Open `http://127.0.0.1:7071/s/edge_chips/r/latest`. The run takes about 45 seconds: three researchers publish findings, a writer waits for them, spawns a fact checker and sends drafts to a critic, and the critic approves the second draft. Run the script again for a fresh run. ## Related - [convoyd](/docs/runtime/) - [HTTP API](/docs/architecture/api/) - [convoy watch](/docs/cli/watch/) --- # Durability > What happens when something dies today, what the post-MVP release will guarantee instead, what is stored from day one to make that possible, and the three acceptance tests. The MVP does not recover from failures. It marks the agent or the run `failed` and stops. It does store everything recovery needs, so adding recovery later changes behavior, not the schema. Durability means a failure at any point leaves the run able to continue from where it was. The MVP's claims are about the language and about teams, not about surviving crashes, so durability is table stakes that waits for the release after. ## Failures: now and later | Failure | MVP behavior | Post-MVP guarantee | | --- | --- | --- | | A runner dies mid-turn | The agent is `failed` with `runner_error`. The run continues without it; the overseer is told on `system` | The controller starts a new runner that resumes the same SDK session by its stored session id, with the work folder as it was. The interrupted turn is retried from its input | | `convoyd` dies mid-turn | On the next start, every active run is marked `failed` with `server_restart` and leftover runner processes are killed | On the next start, convoyd reloads every active run, re-adopts or restarts each runner, and resumes from stored state. No message is lost or delivered twice, and spend is not reset | | The budget is hit mid-turn | Every agent is stopped with reason `budget`, outputs are kept | The same, plus a run can be continued with a raised budget | ## Stored from day one Every change is written as it happens. For each agent: - its SDK session id (the Claude Agent SDK's `session_id`; for the OpenAI Agents SDK, the session id plus the last response id), - its read cursor on every topic and its wake state, - its turn count and the priced usage of every turn, - its process handle, and its status. For each run: its spec (the stored bundle), spend, and the event log. The runner contributes by reporting the session id on every `wake`, and by leaving its work folder and `session.db` in place when it exits. The process backend stores an opaque process id so a later `Reattach` can adopt a runner that outlived a convoyd restart; the MVP has no such path, and every runner of an active run dies with the run. Recovery will resume the real SDK session from these values, not restart from a summary. The change is to the controller's start-up path and its exit rules, described on [Controller](/docs/runtime/controller/#recovery-on-restart). ## Acceptance tests The durability release is done when all three pass: 1. **Runner kill.** Run `kill -9` on a random runner mid-turn. It resumes its session and the swarm still reaches `done_when`. 2. **Server kill.** Run `kill -9` on `convoyd` mid-run, then start it. Runners are re-adopted or resumed, no message is lost or duplicated, and spend is unchanged. 3. **Budget mid-turn.** Hit the budget mid-turn. Everything stops with reason `budget`, outputs are kept, and overshoot is at most one turn per running agent. All three run against a local `openai_compatible` model so they cost nothing. ## What the MVP does on a restart On start, before serving requests, convoyd sets every non-terminal agent of every active run to `failed` with `end_reason = server_restart`, revokes their tokens, sets the run to `failed` with the same reason, and kills every stored process id. A new `convoy run` starts a fresh run. The failed run stays readable with `convoy status --run N`. The details are on [Controller](/docs/runtime/controller/#recovery-on-restart). --- # Overview > The components of Convoy, what each owns, what talks to what, and the path a convoy run takes from your terminal to a running agent. Convoy has three programs and one language. The `convoy` CLI validates files and calls the server. The `convoyd` server holds all state and runs the control loop. A Python **runner** process, one per agent, wraps an agent SDK. The DSL package, `dsl`, is shared by the CLI and the server, so a file that validates on your laptop validates on the server with the same code. ## The parts | Part | What it does | MVP choice | | --- | --- | --- | | [`convoy` CLI](/docs/cli/) | Generates swarm files from a goal, validates them, sends them, shows status | Go, single binary | | [API server](/docs/architecture/api/) | Holds every swarm, agent, topic and message. The only way anything changes | Go, REST plus SSE, plus an MCP endpoint for agents | | State store | Agent specs and status, an append-only event log, the messages | SQLite | | [Controller](/docs/runtime/controller/) | Every few seconds and on every event, compares what is running with what is declared, then starts or stops agents and enforces limits and the budget | Go | | [Message board](/docs/runtime/board/) | Topics as append-only logs, one read cursor per agent per topic, messages optionally addressed to one agent | Tables in the state store, streamed to `convoy watch` over SSE | | [Runner](/docs/runtime/runner/) | One process per agent. Runs the SDK session, waits on the server between turns, reports each turn's token usage | Python, one driver per SDK | | [Overseer](/docs/concepts/overseer/) | A built-in agent that reads the board, judges progress against the goal, and creates, stops or instructs agents | A runner with a fixed prompt, started by convoyd | | [DSL](/docs/dsl/) | Parsing, decoding, `for_each` expansion, references, validation, the dependency graph, provider type manifests and the three built-in types, the bundle format | Go packages, HCL via `hcl/v2` | ## What talks to what | From | To | How | | --- | --- | --- | | CLI | convoyd | HTTP under `/v1`, JSON bodies, SSE for `watch`. Types and client in the public `api` package | | convoyd | runner | Starts a process through the process backend; writes `start.json` into its work folder; sends stop through the `wake` response, then `SIGTERM` | | runner | convoyd | REST for `wake`, `GET /agents`, `GET /topics` | | model (inside the SDK) | convoyd | MCP over Streamable HTTP at `/v1/swarms/{name}/mcp` | | controller | board | Publishes to `system`; signals stop to a blocked `wake` | | controller, handlers | store | Transactions that write state and events together | | overseer | convoyd | The same MCP tools as any agent, plus `note_progress` | Two rules follow. The CLI and the runners never talk to each other. And no component reaches into another's internals: every meeting point is a public Go package or a versioned wire contract, listed on [Seams and contracts](/docs/architecture/contracts/). ## A convoy run, end to end ### The CLI validates and bundles `convoy run` loads the folder with the `dsl` package and validates it. It then builds a **bundle**: every `.cvy` file, every file named by `file()`, and the non-secret `env()` values. API keys are never read or sent. ```json { "format_version": 1, "files": {"main.cvy": "...", "prompts/writer.md": "..."}, "env": {} } ``` ### PUT /v1/swarms/{name} The CLI sends the bundle. The server checks the format version, loads the bundle with the same `dsl` code, and runs its own checks: the name matches, no run of this swarm is active (`swarm_active`), an overseer is declared or defaulted (`overseer_missing`), every provider key variable is set in convoyd's environment (`missing_env`), and every model has a price when a budget is set (`unpriced_model`). Provider types that are not built in are resolved first, from convoyd's store or their git repository, and a driver plugin is started once in check mode (`provider_check_failed`); the run records the version and digest of each. ```http PUT /v1/swarms/edge_chips HTTP/1.1 Authorization: Bearer ``` ### One transaction creates the run The server inserts a run with the next number and status `pending`, one `agents` row per instance (also `pending`), the declared topics plus `progress` and `system`, and the overseer's row. It emits `run.created` and answers 201 with the run number and the agent list. ```json {"name": "edge_chips", "run": 1, "status": "pending", "agents": ["..."]} ``` ### The controller starts the run On its next pass the controller sets the run `running`, emits `run.started`, and posts `swarm started` to `system`. It starts the overseer first, then every agent whose `inputs` and `depends_on` are satisfied, as long as fewer than `--max-processes` runners are alive. For each: mint a token, build `start.json`, create the work folder, exec the runner. ```text .convoy/work/edge_chips/1/researcher__nvidia__/start.json ``` ### Runners turn, wake, and call tools Each runner reads `start.json`, builds its system prompt, and runs the first turn. The model calls swarm tools over MCP: `publish`, `read_topic`, `report_progress`, `finish`. When the turn ends the runner calls `wake` with the turn's usage. The server prices the turn, adds it to the run's spend, and holds the call until the board has news, a stop, or 30 seconds pass. ```http POST /v1/swarms/edge_chips/agents/writer/wake ``` ### The run ends After every event the controller checks the budget, `max_runtime` and `done_when`. When one fires, it stops every agent through the stop sequence, keeps all outputs, and emits `run.ended`. The CLI, which exited long ago, can read the result with `convoy status`. ```console $ convoy status edge_chips ``` Meanwhile `convoy watch` holds one SSE connection to `GET /v1/swarms/{name}/watch`. It receives the same ordered event log the controller reads, so the terminal view needs no polling. ## Repository and processes One repository and one Go module hold everything, laid out so each component can later move out. See [Repository layout](/docs/architecture/repository/). For the server's internals, see [convoyd](/docs/runtime/). --- # Repository layout > One repository and one Go module, arranged so that any top-level component can later become its own module or move to its own repository. For the MVP, Convoy is one repository, `github.com/convoyharness/convoy`, with one Go module of the same path, so every change lands in one commit and nothing has to be tagged in order. Import paths are standard GitHub paths; there is no custom import domain. The layout is designed so that any top-level component can later become its own Go module inside this repository, which keeps its import path, or move to its own repository, public or private, which changes it. See [Moving a component out](#moving-a-component-out). ## Layout ```text convoy/ one go.mod: module github.com/convoyharness/convoy dsl/ everything that understands a .cvy file config/ the swarm types, re-exported by dsl parse/ decode/ eval/ graph/ validate/ bundle/ prices/ manifest/ provider type manifests and the three built-in types types/ type expressions as text hcldiags/ diagnostics and their renderer (public) internal/{dag,hclfuncs,didyoumean} spec/ REFERENCE.md and tools.json, generated api/ wire types for the HTTP API and the start file client/ Go client for the HTTP API contract/ golden JSON the runner tests against sdk/ proc/ the process Backend interface proctest/ a fake backend for tests cli/ the convoy command; cli.Main is its only export internal/{commands,goalgen,render,examples} server/ convoyd; server.Run is its only export internal/{httpapi,store,board,controller,overseer,proclocal,providers} internal/{clock,spec,runcfg} cmd/convoy/main.go calls cli.Main cmd/convoyd/main.go parses flags, calls server.Run runner/ the Python runner and plugin SDK, with its own pyproject.toml examples/ the sample swarms, a reference provider plugin, and the Commit0 acceptance tooling website/ this site boundaries_test.go enforces rule 1 contracts_test.go checks the runner's and the website's contract copies (rule 2) examples_test.go loads examples/ and the CLI's examples with dsl.Load integration_test.go convoyd with the real Python runner and its fake driver integration_providers_test.go a preset and a driver plugin, pushed and run end to end ``` ## Three rules ### Rule 1: dependencies point only toward what could be public A public repository cannot depend on a private one. So the packages that could be published sit at the bottom of the import graph, and the ones that might stay private sit at the top. | Package tree | May import (inside Convoy) | Third-party dependencies | | --- | --- | --- | | `dsl/...` | nothing outside `dsl/` | `hcl/v2`, `go-cty`, `afero`, `go-versions` (provider version constraints), and the extractions' small dependencies | | `api/...` | `dsl/bundle`, `dsl/hcldiags` | standard library only | | `sdk/...` | nothing | standard library only | | `cli/...` | `dsl`, `api` | `urfave/cli/v3`, the two model SDKs | | `server/...` | `dsl`, `api`, `sdk` | SQLite, the MCP SDK | | `cmd/convoy` | `cli` | | | `cmd/convoyd` | `server` | | | `runner/` | no Go code; wire contracts only | Python packages | `cli` and `server` never import each other. Whatever is later kept closed is at the top of the graph, so extracting a component never forces something private into the open. ### boundaries_test `boundaries_test.go` at the repository root enforces the table. It runs `go list -deps -json ./...` and fails on any `github.com/convoyharness/convoy/...` import not allowed above, and on any new third-party dependency of `dsl`, `api` or `sdk` that is not in its allowlist. ### Rule 2: every seam is a public Go package or a versioned wire contract No component reaches into another's internals. A component that consumes a contract file (the runner) keeps a copy of it, not a path into another component's tree. `contracts_test.go` fails when a copy differs from its source, and `make contracts` refreshes the copies. The full list of seams is on [Seams and contracts](/docs/architecture/contracts/). ### Rule 3: each component has its own internal/ There is no repository-wide `internal/` directory. Each component's private code is under its own `internal/` (`cli/internal/`, `server/internal/`, `dsl/internal/`), so Go's `internal` rule stops one component from importing another's private packages without any tooling. `cli` and `server` each export one entry point, which `cmd/` calls. Tests follow the same boundary: a package's tests read only files under its own directory. Tests that need files from several components (`examples_test.go`, `contracts_test.go`, and convoyd's end-to-end test in `server/`) say so and sit at the root or with the component that puts the others together. ## Moving a component out There are two steps, taken separately and only when needed: - **Its own module, same repository.** Add a `go.mod` at the component root (for example `module github.com/convoyharness/convoy/dsl`) and tag it with the directory prefix (`dsl/v0.1.0`). The import path does not change, so no consumer notices. This is enough to version a component independently. - **Its own repository.** Needed to make a component public while the rest stays private, or the reverse. The import path changes to the new repository's path. Before anything outside Convoy imports the component, that is a find-and-replace. After, it is a breaking change for those importers, so do it before the first outside user if possible. Moving to a new repository: 1. `git filter-repo --path /` creates the new repository with that directory's history only. Commit messages travel with it, so write commits that touch `dsl/`, `api/`, `sdk/`, `cli/` or `runner/` as if they were already public. 2. Add a `go.mod` with the new path (for example `module github.com/convoyharness/dsl`), tag `v0.x.0`, and replace the directory in this repository with a `require` of that version. 3. Rewrite imports from `github.com/convoyharness/convoy/` to the new path, here and in any outside project. For a private repository, consumers set `GOPRIVATE=github.com/convoyharness/` and authenticate to git. 4. Move any copied contract files the component consumed into its own tree, and keep the boundaries table as the new repository's dependency rule. Likely order: `sdk/proc` first, when the first out-of-tree sandbox backend is written; `dsl` when an outside tool, such as an editor plugin or a module registry, needs it. Until a component has an outside consumer, it stays here. ## Packages extracted from OpenTofu Convoy's language is HCL, and OpenTofu already solved several of the problems around it. Four packages are taken from it. All sit under `dsl/` as packages of that module, not separate modules, until an outside project needs one. | Package | Origin in OpenTofu | What it is | | --- | --- | --- | | `dsl/hcldiags` | `internal/tfdiags` and the diagnostic renderer from `internal/command/format` | Diagnostics with source ranges, severity, and terminal rendering with code snippets. Public, because `dsl` returns these types and the CLI and server render them | | `dsl/internal/dag` | `internal/dag` | Directed acyclic graph: vertices, edges, cycle detection, topological order, parallel walk | | `dsl/internal/hclfuncs` | `internal/lang/funcs` (a subset) and the table in `internal/lang/functions.go` | The expression functions available in `.cvy` files | | `dsl/internal/didyoumean` | `internal/didyoumean` | Name suggestions for typos in block names and attributes | Each keeps OpenTofu's MPL-2.0 license and per-file headers, with a LICENSE and a NOTICE file in the package directory naming the origin commit. MPL-2.0 is file-scoped, so new files in those packages and everything else in the repository can be under any license. ## Shared conventions - Go 1.25 or newer (`hcl/v2` v2.25 requires it). The module pins `hcl/v2` v2.25 and `go-cty` v1.19, the versions OpenTofu pins today. - Every error shown to a person is a diagnostic with a source range when one exists. Plain `error` values never reach the terminal. - Identifiers in the DSL match `^[a-zA-Z_][a-zA-Z0-9_]*$`. Agent instance names add a bracketed key: `researcher[nvidia]`. - JSON on the wire uses `snake_case` keys. Timestamps are RFC 3339 in UTC. Durations are Go duration strings. - Every HTTP error body is `{"error": {"code": "", "message": ""}}`. --- # Seams and contracts > Every place two Convoy components meet, how each is versioned, and the formats that cross each boundary: the bundle, start.json, check mode, tools.json, provider manifests and the process backend interface. A **seam** is a place where two components meet. In Convoy each seam is either a public Go package or a versioned wire contract. Nothing reaches into another component's internals. Version numbers exist so that, once components ship from separate repositories, an old one meeting a new one fails clearly instead of misbehaving. ## The seams | Seam | Form | Version field | | --- | --- | --- | | Everything that reads `.cvy` files to `dsl` | Public Go packages, including `dsl/hcldiags` | Go module version | | CLI to server | HTTP under `/v1`; types and client in the public `api` package | The `/v1` path | | CLI to server bundle | `bundle.Bundle` JSON | `format_version` | | Server to runner, and to a driver plugin | `start.json`, check mode, REST `wake`, MCP, exit codes. Golden JSON in `api/contract/` | `contract` | | Provider type to convoyd and the CLI | `convoy-provider.hcl`, compiled to `manifest.Manifest` JSON, which convoyd stores and serves | `format` | | `dsl` tool catalog to runner tool table | `dsl/spec/tools.json`, generated from the built-in provider manifests | `version` | | Server to process backends | Public `sdk/proc.Backend` interface | Go module version | ## Versioning policy Bump a version only for a change an older peer would misread. Additions it can ignore do not bump it. - **`format_version`** (bundle) is 1. The server rejects any version outside `SupportedFormats` with 422 `bundle_version_unsupported`, naming the supported ones. It checks before parsing, so an older server never guesses at a newer bundle. The CLI and server ship together in the MVP; the field is for when they do not. - **`contract`** (runner contract) is 2. The runner contract is the shape of `start.json`, check mode, the runner's exit codes, the `wake` request and response, and `tools.json`. A runner that does not support the version exits 2 with a log line naming both versions. Version 2 carries the provider type's configuration and adds check mode. A driver plugin lists the versions it supports in its manifest's `contracts`, and convoyd refuses one with none in common. - **`format`** (provider manifest) is 1. A server rejects a manifest whose `format` it does not know. - **`version`** in `tools.json` changes when the file's shape changes, not when a tool is added. - **`/v1`** is the HTTP API version. A component that consumes a contract file keeps a copy of it. `contracts_test.go` fails when a copy differs from its source. ## The bundle What `convoy run` sends and convoyd stores with the run. ```json title="bundle.Bundle" { "format_version": 1, "files": {"main.cvy": "...", "prompts/writer.md": "..."}, "env": {"REPORT_REGION": "emea"} } ``` | Field | Content | | --- | --- | | `format_version` | `CurrentFormat`, 1 when built by this CLI | | `files` | Path relative to the folder to contents. Every `.cvy` file and every file named by a `file()` call | | `env` | Only the variables that `env()` calls reference, read on the laptop | `env()` is for values that are not secret: they are stored with the run and returned by the API. API keys are never in the bundle; a provider's `api_key` only names a variable in convoyd's environment. The server evaluates the same files with `Bundle.Env` standing in for the environment. Nothing else from your machine reaches it. The bundle's hash (sha256 over the format version, sorted files and env keys) is stored with each run so runs can be compared. The server does not trust the CLI's validation: it loads the bundle again and rejects the `PUT` with rendered diagnostics if there are errors. ## start.json Instead of passing a large first turn through the environment, the controller builds `start.json` and hands it to the backend as `ExecSpec.Files["start.json"]`. The backend places it in the agent's workspace before the runner starts. Locally that is `.convoy/work////start.json`. The Go type is `api.StartFile`; the version constant is `api.RunnerContract`. ```json title="start.json" { "contract": 2, "swarm": {"name": "edge_chips", "run": 3, "goal": "...", "done_when": "agent.critic.output.approved == true"}, "agent": {"name": "writer", "prompt": "", "output_schema": {}, "provider": {"driver": "openai_compatible", "source": "acme/acme", "version": "1.4.2", "model": "acme-large-1", "config": {"base_url": "https://api.acme.example/v1", "headers": {"X-Acme-Tier": "priority"}}, "settings": {"temperature": 0.2}}, "writes": ["drafts"], "watches": ["review"], "tools": ["web_search"], "max_turns": 50, "can_spawn": false}, "inputs": {"findings": []}, "server": {"url": "http://127.0.0.1:7070", "mcp_url": "http://127.0.0.1:7070/v1/swarms/edge_chips/mcp"} } ``` `output_schema` and `inputs` are `null` when the agent has no `output` or `inputs`. In `provider`, `driver` is the built-in type whose driver the runner selects, empty for a driver plugin; `config` is what the driver receives, and `settings` holds only the settings that are set. `server.url` is the address the runner uses to reach convoyd: `http://127.0.0.1:` by default, or `--public-url`. The token and the provider key are passed in the environment as `CONVOY_TOKEN` and the variable the provider type names, never written to disk. ### Check mode The runner command with `--check` in place of `--start-file` loads its driver, confirms its SDK imports, prints one line, and exits 0. convoyd runs a driver plugin this way before a run's agents start. ```json title="check.json" {"contracts": [2], "runner_version": "0.2.0"} ``` Golden copies of `start.json`, `check.json`, `wake_request.json` and `wake_response.json` live in `api/contract/`, written from the Go types, and the runner's tests read copies of them. ## Provider manifests A [provider type](/docs/providers/) is one file, `convoy-provider.hcl`. Package `dsl/manifest` parses it with the same HCL toolkit as `.cvy` files and compiles it to `manifest.Manifest`, whose JSON is what convoyd stores and what `/v1/providers` serves, so the CLI never parses HCL it did not read from disk. The three built-in types are manifests embedded in `dsl/manifest`. See [Writing a provider type](/docs/providers/writing/#the-manifest). ## tools.json The Python runner does not read Go, so the tool catalog crosses as data. `go generate` in `dsl/spec` writes `tools.json` from the built-in types' manifests, and a staleness test fails when it is out of date. The key `by_sdk` is kept, keyed by built-in type. ```json title="tools.json" { "version": 1, "by_sdk": { "claude_agent_sdk": ["web_search", "bash", "read_file", "write_file", "edit_file"], "openai_agents": ["web_search", "bash", "read_file", "write_file", "edit_file", "code_interpreter", "file_search"], "openai_compatible": ["bash", "read_file", "write_file", "edit_file"] }, "swarm_tools": ["list_topics", "read_topic", "publish", "watch_topic", "create_topic", "list_agents", "create_agent", "stop_agent", "report_progress", "finish"] } ``` The runner's `test_contract` loads its copy and fails if a DSL name listed for an SDK has no row in the runner's table, or the table names a tool the file does not list. See [Runner](/docs/runtime/runner/#tool-name-mapping). ## Process backend The package `sdk/proc` is public because out-of-tree backends implement it. It imports only the standard library. ```go title="sdk/proc/proc.go" type Backend interface { Create(ctx context.Context, spec CreateSpec) (Handle, error) // make the agent's workspace Exec(ctx context.Context, h Handle, cmd ExecSpec) (Process, error) // write cmd.Files, then start cmd.Argv Kill(ctx context.Context, processID string) error // by stored ID, even from before a restart Destroy(ctx context.Context, h Handle) error // kill and remove } type CreateSpec struct{ Swarm string; Run int; Agent string } type ExecSpec struct { Argv []string Env map[string]string Files map[string][]byte // path relative to the workspace root; written before Argv starts } type Process interface { ID() string // opaque to convoyd: a pid locally, a container or sandbox id elsewhere Wait() <-chan ExitStatus Logs() io.ReadCloser // combined stdout and stderr Kill() error } ``` Rules every backend follows, so a remote sandbox can implement the same interface: - **No shared filesystem.** Everything the runner needs arrives in `ExecSpec.Files` and `ExecSpec.Env`. convoyd never reads the workspace. - **HTTP only.** The runner reaches convoyd over HTTP at `server.url` and `server.mcp_url`. The exit status and logs come back through `Process`. Nothing else crosses. - **Opaque identifiers.** `Handle` and `Process.ID()` are stored and passed back unchanged. - **Runner availability is the backend's job.** The runner command must exist in the workspace: locally `convoyd` unpacks its built-in runner and starts it with `uv`, and a container or sandbox has it baked into the image. The runner command is `[--runner, "--start-file", "start.json"]` for a built-in type or a preset. For a driver plugin it is the manifest's `command`, with `{package}` replaced by the package folder, then `--start-file start.json`. ### The local backend `server/internal/proclocal` is the MVP backend. `Create` makes `////`. `Exec` writes the files, then runs the command in that folder with a clean environment (`PATH`, `HOME`, `CONVOY_TOKEN`, and the variables the provider type names, such as its key) and its own process group, so `Kill` can signal the group. Stdout and stderr go to `agent.log` events in 4 KB chunks. `ID()` is the pid. `Destroy` kills the group and leaves the folder; `convoyd gc` removes folders of ended runs. ### Future sandbox plugins Post-MVP, the interface gains `Reattach(ctx, h, processID) (Process, error)` so a backend can adopt a runner that outlived a convoyd restart. Out-of-tree backends, such as a Docker or remote sandbox backend, implement the same interface without changing the DSL. A backend whose processes run on another host requires `--public-url`. ## The store interface Everything above storage depends on `store.Store`, not on `database/sql`. It is internal to the server, so it is not a public seam, but it is a contract: any backend must pass the suite in `store/storetest`, which checks atomic rollback, compare-and-set status updates, gapless increasing `seq` per run, atomic turn accounting, durability across reopen and concurrent transactions. The MVP ships only SQLite. See [convoyd](/docs/runtime/#storage). --- # HTTP API > Every convoyd endpoint grouped by resource, with method, path, caller, body, responses and errors, plus authentication and the MCP endpoint. All state changes go through this API. The CLI, the runners and the overseer use the same endpoints. Paths are under `/v1`. Request and response bodies are JSON, with `snake_case` keys, RFC 3339 UTC timestamps and Go duration strings. Request and response types are the structs in the public `api` package, which the Go client also uses. Every endpoint under `/v1/swarms/{name}` names a **swarm**, not a run. Every `GET` there accepts `?run=N` and defaults to the latest run. Every write acts on the latest run and returns 409 `run_ended` when that run is terminal, except `:stop`, which is idempotent, and a transcript append, which is accepted while the agent's token is valid. ## Authentication | Caller | Credential | Identity | | --- | --- | --- | | CLI on the same machine | None, when convoyd listens on loopback and `--token` is empty | `human`, all runs | | CLI otherwise | `Authorization: Bearer ` | `human`, all runs | | Runner and overseer | `Authorization: Bearer `, minted when the process starts | That agent, in that run | A missing or revoked token is 401. A token for a run that is not the latest run of `{name}` is 403. A runner token is revoked when its runner process exits. Agent-only endpoints (`progress`, `finish`, `wake`, `watches`, and the transcript append) require the token's agent to match `{a}`. The [Web UI](/docs/runtime/web-ui/)'s reads (the swarm list, the graph snapshot and transcript reads) are for people only: a runner token gets 403 `people_only`. The sender of every message and the creator of every agent come from the token, never from the body. ## Errors Every error is `{"error": {"code": "", "message": "", "diagnostics": [...]}}`. `diagnostics` appears on validation failures, rendered as structured objects with source ranges. | Status | Codes | | --- | --- | | 400 | `name_mismatch`, `bad_item` (a malformed transcript item) | | 401 | missing or revoked token | | 403 | wrong run, wrong agent, `not_writer`, `not_parent`, `overseer_cannot_finish`, `bad_host`, `cross_origin`, `people_only` | | 404 | unknown swarm, run, agent; `topic_not_found` | | 409 | `swarm_active`, `run_ended`, `topic_limit`, `spawn_not_allowed`, `depth_limit`, `tools_not_allowed`, `model_not_allowed`, `agent_exists` | | 413 | `body_too_large` | | 422 | invalid bundle (with diagnostics), `bundle_version_unsupported`, `overseer_missing`, `missing_env`, `unpriced_model`, `output_mismatch` | ## Swarms | Method and path | Caller | Purpose | | --- | --- | --- | | `GET /v1/swarms` | People (Web UI) | Every swarm with its latest run | | `GET /v1/whoami` | Anyone | Who the caller is | | `PUT /v1/swarms/{name}` | CLI (`run`) | Create a run from a bundle | | `GET /v1/swarms/{name}` | CLI (`status`) | State of the latest run, or `?run=N` | | `GET /v1/swarms/{name}/runs` | CLI | Every run of the swarm | | `POST /v1/swarms/{name}:stop` | CLI (`stop`) | Stop the active run | | `GET /v1/swarms/{name}/watch?after=N` | CLI (`watch`) | SSE event stream | | `GET /v1/swarms/{name}/graph` | People (Web UI) | Graph snapshot of a run | ### `GET /v1/swarms` People only. 200 `[{name, runs, latest: {run, status, goal, created_at, started_at, ended_at, end_reason, elapsed_seconds, spend_usd, max_cost_usd, agents_total, agent_counts}}]`, one per swarm that has a run, the most recent run first. `agent_counts` maps a status to a count. ### `GET /v1/whoami` 200 `{agent, swarm?, run?}`: `{"agent": "human"}` for a person, or a runner token's agent, swarm and run number. ### `PUT /v1/swarms/{name}` Body: a `bundle.Bundle` (`format_version`, `files`, `env`). Query: `dry_run=true`. 1. If `format_version` is unsupported: 422 `bundle_version_unsupported`. Otherwise load the bundle, resolving each provider's type through the provider store and fetching a version the server does not hold; errors are 422 with diagnostics, and a type that cannot be resolved is TS016 among them. A fetch that takes longer than `--provider-timeout` is 504 `provider_timeout`. 2. The swarm name in the files must equal `{name}`, else 400 `name_mismatch`. 3. If the swarm's latest run is `pending` or `running`: 409 `swarm_active` with the run number and status. Nothing changes. Wait for the run to end or call `convoy stop`. 4. Resolve the overseer: the swarm's `overseer` attribute, else the `--overseer-*` flags, else 422 `overseer_missing`. 5. Server-side checks, each a 422 with diagnostics: every variable a provider reads, such as its `api_key`, is set in convoyd's environment (`missing_env`, naming the variable and never a value); when `max_cost_usd` is set, every model, the overseer's included, has a price (`unpriced_model`). Unless `dry_run` is set, every driver plugin the swarm names is started once in check mode; a failure is 422 `provider_check_failed` with the end of its output, and no run is created. 6. With `dry_run=true`, stop here and return 200 with the agent list that would be created. 7. In one transaction: insert the swarm if new; a run with `number = previous + 1` and status `pending`, recording `providers`, the type version and digest each provider block resolved to; one `agents` row per instance, `pending`; the declared topics plus `progress` and `system`; the overseer row. Emit `run.created`, then `topic.created` for each topic and `agent.created` for the overseer and each declared agent. Response: 201 `RunResponse{name, run, status, agents, providers}`. Each entry of `providers` is `{name, source, constraint, version, digest, kind, runner_version}`; `version` and `digest` are empty for a built-in type, and `runner_version` is what a driver plugin's check reported. There is no in-place update of a running swarm. A changed bundle takes effect as a new run after the current one ends. Earlier runs, with their boards, outputs and spend, stay readable with `?run=N`. ### `GET /v1/swarms/{name}` 200 with the run: `name`, `run`, `runs_total`, `status`, `goal`, `done_when` (source text), `max_runtime`, `max_cost_usd`, `spend_usd`, `unpriced_turns`, `overseer` (`provider`, `provider_source`, `provider_version`, `driver`, `provider_sdk`, `model`, `config`, `settings`, `env`, `can_spawn`, `source`, `price`), `providers` (as in `RunResponse`), `created_at`, `started_at`, `ended_at`, `end_reason`, `end_detail`, `elapsed`, `agent_counts` (status to count), and `progress` (the last 5 messages of the `progress` topic). 404 if unknown. `end_reason` is one of `done`, `budget`, `max_runtime`, `failed`, `stopped`, `server_restart`, or null while active. `spend_usd` is what actually happened, so a run stopped by its budget can show more than `max_cost_usd`. This is the body behind `convoy status --json`. ### `GET /v1/swarms/{name}/runs` 200 `[RunSummary{run, status, started_at, ended_at, end_reason, spend_usd}]`, newest first. ### `POST /v1/swarms/{name}:stop` Body `{reason}`. If the latest run is active, stops every non-terminal agent through the controller's stop path (kills processes, revokes tokens), sets the run `stopped` with `end_reason = stopped`, and emits `run.ended`. Idempotent on a terminal run. 200 with the run. ### `GET /v1/swarms/{name}/watch?after=N` Server-sent events over one run's event log. 1. Sends every event with `seq > N` as `id: `, `event: `, `data: `. 2. Subscribes to the in-process broadcaster and forwards new events as they commit. 3. Sends `: keepalive` every 15 seconds. 4. Ends after forwarding `run.ended`, or when the client disconnects. The `data` object is `{seq, type, swarm, run, agent, at, payload}`. `agent.log` events are skipped unless `logs=1`. Event types are listed on [convoyd](/docs/runtime/#event-log). ### `GET /v1/swarms/{name}/graph` People only. 200 `{seq, run, agents, topics, flows}`: one run's agents (status, parent, `input_deps`, watches, writes, turns, spend, last tool call), topics (message counts, first and last `seq`), and message flows (`writes` per sender and topic, `reads` per agent cursor with read and unread counts, `addressed` per sender, topic and recipient), read in one transaction with the event `seq` they reflect. `run` is the body of `GET /v1/swarms/{name}`. A client folds `watch?after=` into it to stay current. ## Agents | Method and path | Caller | Purpose | | --- | --- | --- | | `GET /v1/swarms/{name}/agents` | CLI, runners, overseer | List agents | | `POST /v1/swarms/{name}/agents` | Runners with `can_spawn`, overseer | Create an agent | | `GET /v1/swarms/{name}/agents/{a}` | CLI | Full detail | | `POST /v1/swarms/{name}/agents/{a}:stop` | CLI, overseer, parent | Stop an agent and its children | | `POST /v1/swarms/{name}/agents/{a}/progress` | Runner (`report_progress`) | Record a progress summary | | `POST /v1/swarms/{name}/agents/{a}:finish` | Runner (`finish`) | End the agent with its output | | `POST /v1/swarms/{name}/agents/{a}/wake` | Runner | Long poll for the next turn | | `POST /v1/swarms/{name}/agents/{a}/watches` | Runner (`watch_topic`) | Add a watched topic | | `POST /v1/swarms/{name}/agents/{a}/transcript` | Runner | Append transcript items | | `GET /v1/swarms/{name}/agents/{a}/transcript` | People (Web UI) | Read the agent's transcript | | `GET /v1/swarms/{name}/agents/{a}/transcript/watch` | People (Web UI) | SSE of new transcript items | ### `GET .../agents` 200 `[AgentSummary{name, status, parent, declared, can_spawn, turns, spend_usd, provider, sdk, source, version, model, role_summary, last_progress, started_at, ended_at}]`, sorted by name. `role_summary` is the first non-empty line of the prompt, trimmed to 100 characters. ### `POST .../agents` Body `{hcl: string}`. Caller must be a runner or the overseer. The HCL must contain exactly one `agent` block (422 otherwise). It is decoded against the run's configuration; `count` and `for_each` are rejected. Checks, each a 409: | Code | Reason | | --- | --- | | `spawn_not_allowed` | The caller's `can_spawn` is false | | `depth_limit` | The caller's depth plus one exceeds 3 | | `tools_not_allowed` | The child's tools are not a subset of its parent's | | `model_not_allowed` | The child's provider or model is not the parent's and no declared agent uses it | | `agent_exists` | The name is taken | The child's `tools` and `settings` are checked against its provider's type, in the version the run recorded; a mismatch is 422 `invalid_agent` with diagnostics. For the overseer, tools, provider and model are each checked against the union over declared agents. On success the row is inserted `pending` with `parent` set to the caller and `declared = 0`, `agent.created` is emitted, and the response is 201 with the `AgentSummary`. There is no limit on the number of agents; `--max-processes` bounds concurrency. ### `GET .../agents/{a}` 200 `AgentDetail{AgentSummary, spec, progress_reports, turns, output, children, sdk_session_id}`. `spec.provider` is the resolved `ProviderSpec`: `name`, `source`, `version`, `digest`, `driver`, `sdk` (deprecated), `model`, `config` (what the driver receives, never a key), `settings` (the agent's resolved settings), `env` (the variable set in the runner, mapped to the variable read from convoyd's environment; names only), and `price`. ### `POST .../agents/{a}:stop` Body `{reason}`. Caller must be the CLI, the overseer, or the agent's parent. Terminal states are idempotent. Stops children first, depth-first, then the agent. 200. ### `POST .../agents/{a}/progress` Body `{summary}`, at most 4 KB. Caller must be `{a}`. Stores the report, updates `last_progress_at`, emits `agent.progress`. A `stuck` agent returns to `running`. 201 `{seq}`. ### `POST .../agents/{a}:finish` Body `{output}`, JSON, at most 256 KB. Caller must be `{a}`. 1. The output is checked against the agent's declared `output` type. A mismatch is 422 `output_mismatch` with the path; the agent stays running. 2. In one transaction: store the output, set `done`, emit `agent.finished`. 3. After commit, signal the controller, which evaluates `done_when` and the gates. 4. 200 `{status: "done"}`. The runner exits after its next `wake`. ### `POST .../agents/{a}/wake` Body: `{last_turn: {input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, sdk_cost_usd?} | null, session?: {sdk_session_id, last_response_id?}}`. 1. If `session` differs from the stored ids, store both and emit `agent.session`. 2. If `last_turn` is not null, in one transaction: record the turn with its cost from the price table, set `idle`, set `last_turn_at`, emit `agent.turn_ended`. Then signal the controller to check the budget. 3. Block on the board. When it returns a turn, set `running` and emit `agent.turn_started`. An agent with empty `watches` does not block; it returns at once with `continue: true`. Responses: `{woken: true, continue?, addressed, unread, delta}`, `{stop: true, reason}`, or `{woken: false}` after 30 seconds. See [Message board](/docs/runtime/board/#wake). ### `POST .../agents/{a}/watches` Body `{topic}`. Adds the topic to the agent's watches. Messages published to it afterward can give the agent a turn; its read cursor is unchanged. Emits `agent.watches` when the set changes. 201. ### `POST .../agents/{a}/transcript` Body `{items: [...]}`, at most 8 MiB. Caller must be `{a}`. Each item has `idx` (per agent, from 1), `turn`, `kind` (`system`, `input`, `text`, `reasoning`, `tool_call`, `tool_result` or `error`), `at`, and the kind's fields: `text`, `redacted`, `call_id`, `tool`, `input`, `output`, `is_error`, and `truncated` with the original `bytes` when the runner cut it. Items already stored are skipped, so a retried batch stores nothing twice. One `agent.tool_called` event is emitted per newly stored `tool_call` while the run is active. 400 `bad_item` for an unknown kind, `idx` below 1, a `tool_call` without `tool`, or an oversized field. 200 `{stored: n}`. ### `GET .../agents/{a}/transcript?turn=T&after=I&limit=L` People only. 200 `{items, next}` in `idx` order. `limit` defaults to 500, at most 2000. `next` is the `after` value for the next page, 0 when there is none. ### `GET .../agents/{a}/transcript/watch?after=I` People only. Server-sent events, one per item: `id: `, `event: item`, `data: `, with keepalives. Ends once the agent has ended and its runner process has exited. ## Provider types For people only: a runner token gets 403 `people_only`. The paths carry no source, because an address contains slashes. See [Provider types](/docs/providers/). | Method and path | Body | Purpose | | --- | --- | --- | | `GET /v1/providers?source=&version=&manifest=true` | | 200 `[ProviderInfo{source, version, digest, kind, origin, created_at, builtin, manifest?}]`: the built-in types first, then installed versions by source, newest first | | `POST /v1/providers:resolve` | `{requirements: [{source, version}]}` | Resolves each, fetching a type the server does not hold. Runs no provider code. 200 `{providers: [{source, constraint, version, digest, kind, manifest}], errors: [{source, constraint, code, message, diagnostics?}]}`; one failure does not fail the others | | `POST /v1/providers:pull` | `{source, version?}` | Fetches the highest version that meets the constraint unless it is installed, and checks a driver plugin. 200 `ProviderInfo` with the manifest and `check` | | `POST /v1/providers:push` | `{source, version, files: {path: text}}`, at most 32 MiB | Installs a package from uploaded files, origin `push`, then checks a driver plugin. Replaces a pushed version of the same number. 201 `ProviderInfo` | | `POST /v1/providers:remove` | `{source, version}` | Deletes the version's row and package folder. 200 | `manifest` is the type's compiled manifest as JSON, so a client never parses HCL it did not read from disk. Errors: | Status | Code | Meaning | | --- | --- | --- | | 404 | `provider_not_found` | No repository at the address, or no such installed version | | 409 | `provider_in_use` | An active run recorded the version (`remove`, or a `push` over it) | | 409 | `provider_exists` | A `push` over a version that came from git | | 409 | `provider_digest_mismatch` | The tag moved since convoyd fetched it; the stored version is kept | | 422 | `provider_manifest_invalid` | The manifest has errors (with diagnostics), is missing, or the package has a symbolic link | | 422 | `provider_incompatible` | The manifest's name differs from the address, or a driver plugin supports no runner contract convoyd speaks | | 422 | `provider_check_failed` | A driver plugin's check did not exit 0 or report a supported contract | | 422 | `provider_version_not_found` | No tag meets the constraint; the message lists up to ten versions | | 504 | `provider_timeout` | A fetch took longer than `--provider-timeout`; it continues | ## Topics and messages | Method and path | Caller | Purpose | | --- | --- | --- | | `GET /v1/swarms/{name}/topics` | CLI, runners | Every topic: name, description, writers, watchers, count, the caller's unread | | `POST /v1/swarms/{name}/topics` | Runners | Body `{name, description}`. Creates the topic and adds it to the caller's `writes` | | `POST /v1/swarms/{name}/topics/{t}/messages` | Runners, CLI (`say`) | Body `{body, to?, reply_to?}`. Appends a message | | `GET /v1/swarms/{name}/topics/{t}/messages?after=N&limit=M` | Runners, CLI | Messages with `seq > N`, oldest first | The server supplies the identity and the `writes` allowlist. A `GET` of messages from a runner advances that agent's read cursor to the highest `seq` returned, and `after` defaults to the cursor; a read from the CLI does not move any cursor. `limit` defaults to 50 and is capped at 200. Publish errors are `not_writer`, `topic_not_found` and `body_too_large`. See [Message board](/docs/runtime/board/). ## MCP ### `POST /v1/swarms/{name}/mcp` The Streamable HTTP MCP endpoint for the swarm tools, one instance per active run. Runners reach it through their SDK with the agent's bearer token. Each tool calls the same Go function as the REST handler for that operation, so identity and permission rules are identical. | Tool | REST equivalent | | --- | --- | | `list_topics` | `GET /topics` | | `read_topic` | `GET /topics/{t}/messages` | | `publish` | `POST /topics/{t}/messages` | | `watch_topic` | `POST /agents/{me}/watches` | | `create_topic` | `POST /topics` | | `list_agents` | `GET /agents` | | `create_agent` | `POST /agents`, registered only for callers with `can_spawn` | | `stop_agent` | `POST /agents/{name}:stop` | | `report_progress` | `POST /agents/{me}/progress` | | `finish` | `POST /agents/{me}:finish`, not registered for the overseer | | `note_progress` | publish to `progress`, registered only for the overseer | Tool errors come back as MCP results with `isError: true`. Inputs and behavior of each tool are on [Swarm tools](/docs/runtime/swarm-tools/). --- # Overview > Three swarms to copy and run with one API key, then five larger ones shaped after long-horizon benchmarks. The `examples` folder in the repository starts with three swarms you can copy and run. Each is one folder: a `main.cvy`, a Markdown prompt per agent, and a README. Each needs one API key, Anthropic or OpenAI, and nothing else. | Example | Shape | What you get | What it teaches | |---|---|---|---| | `writer_critic` | two agents in a loop | a short piece of writing, approved by a critic | topics, `watches` and `writes`, typed `output`, `done_when` | | `research_team` | parallel researchers, a writer, an editor | a sourced briefing in `report.md` | `for_each`, `inputs` as the dependency graph, tools, a numeric `done_when` | | `code_team` | a planner, two coders, a reviewer | a tested Python package in `./workspace` | `count`, addressed messages, a `done_when` backed by a passing test suite | ## Running one Start `convoyd` with a key in its environment ([install](/docs/install/) covers getting it): ```sh export ANTHROPIC_API_KEY=sk-ant-... # or: export OPENAI_API_KEY=sk-... convoyd ``` Then, in another terminal: ```sh cd examples/writer_critic convoy run convoy watch writer_critic # the swarm's name is the label of its swarm block ``` Run `convoy` from inside the example's folder. `research_team` and `code_team` write their results there. ## Anthropic or OpenAI Every one of the three declares a single provider, and its block carries both choices: ```hcl provider "llm" { source = "claude_agent_sdk" # "openai_agents" model = "claude-sonnet-5-5" # "gpt-6.1-sol" } ``` As written they use an Anthropic key. For an OpenAI key, change those two lines to the values in the comments. The agents inherit the provider's model, and the tools they use (`web_search`, `bash`, `read_file`, `write_file`, `edit_file`) have the same names on both, so nothing else in the file changes. ## Benchmark swarms `examples/benchmarks` holds five larger swarms and one baseline, one per long-horizon benchmark. Each is a complete `convoy run` target: a `main.cvy` (plus other `.cvy` files where the sample shows merging), a `prompts` folder, and a README that maps the swarm to its benchmark and lists what the folder assumes about the machine. They were chosen so that each shows a different shape of the language. Every benchmark folder passes [`convoy validate`](/docs/cli/validate/) with zero errors, and zero warnings except one expected `TS051` on the solo arm. Each needs its benchmark's own setup (a checkout, a simulator, a task folder) before a run does anything useful, and none has been run end to end yet. ### The five shapes | Folder | Benchmark | Shape | `done_when` | |---|---|---|---| | `01_paperbench_replication` | PaperBench | fan-out, fan-in, then a judge loop | the judge approves | | `02_commit0_library` | Commit0 | task board with a worker pool | 95% of the real test suite passes | | `02_commit0_library/solo` | Commit0 | one agent, same budget | 95% of the real test suite passes | | `03_vending_bench` | Vending-Bench 2 | self-sustaining daily loop | day 365 or bankrupt | | `04_swe_lancer_bounty` | SWE-Lancer | competition, pick, implement, test | the end-to-end tests pass | | `05_tau2_pass_k_loop` | τ²-bench | improvement loop, then a held-out gate | held-out pass^4 gain of 10 points | ### Which features each one leans on | Feature | Where it appears | |---|---| | `for_each` over a map | PaperBench builders, τ²-bench runners | | `for_each` over `toset()` | Commit0 implementers | | Typed, nested `output` | every folder | | `values(agent.x)[*].output` | PaperBench experimenter | | `depends_on` | PaperBench judge, SWE-Lancer QA | | `inputs` diamond | SWE-Lancer manager | | `can_spawn` and `create_agent` | Commit0 implementers; switched off in the solo arm | | Three SDKs in one swarm | Vending-Bench, SWE-Lancer | | Multi-file configuration | Vending-Bench | | `vars` as experiment knobs | τ²-bench | ### Conventions shared by every benchmark folder - Every `swarm` block declares its `overseer = { provider, model }` and a `max_cost_usd`. The overseer's spend counts toward the cap. There is no `max_agents`; `convoyd --max-processes` limits concurrency. - `api_key` names an environment variable that `convoyd` reads from its own environment. Keys never travel in the bundle. - Only agents with `can_spawn = true` may call `create_agent` (Commit0's implementers). The overseer may spawn unless its block sets `can_spawn = false`. - Agents call `report_progress(summary)` after each meaningful step. The overseer and `convoy status` read it. - A turn starts with an unread summary of the board. Messages addressed to the agent arrive in full; everything else the agent pulls with `read_topic`. - The first line of each prompt file is the role summary that `list_agents` shows. The rest becomes the YOUR JOB section of the agent's system prompt. - `{{name}}` in a prompt is replaced from the agent's `vars`. Everything else in the prompt is literal. - Paths the agents share (a checkout, a workspace, a runs folder) come in through `env("...")` inside `vars`. `convoy run` reads those variables on the laptop and ships them with the bundle; a missing one fails before anything starts. - Every agent that watches a topic has an explicit `max_turns`. An agent that watches nothing takes continue turns until it calls `finish` or reaches `max_turns`; most of them finish in their first turn. - Every topic has at least one declared writer and one declared watcher, so `convoy validate` is clean of the unused-topic warnings. - Every `human` topic has a watcher, so `convoy say human "..." --to ` reaches someone. The exception is the Commit0 solo arm, whose one agent watches nothing and is reached with `--to solo`; it gets the one expected `TS051` warning. - A provider running a local model declares `price = { input = 0, output = 0 }`, since the built-in price table only knows hosted models and every swarm sets `max_cost_usd`. - Model names follow the proposal's convention (`claude-opus-5`, `claude-sonnet-5`, `gpt-6.1-sol`, an Ollama tag). Each is set in its agent block. ### Running any of them ```sh cd examples/benchmarks/ convoy validate # offline; checks every rule in the validation reference convoy run # sends the folder to convoyd convoy watch # the swarm name is the label of the swarm block convoy say human "" --to ``` See [`convoy validate`](/docs/cli/validate/), [`convoy run`](/docs/cli/run/), [`convoy watch`](/docs/cli/watch/) and [`convoy say`](/docs/cli/say/). Each example page lists the environment variables and tools its folder needs. --- # Writer and critic > The smallest useful swarm. Two agents and one loop, in about thirty lines, done when the critic approves. This is the place to start. A writer drafts what the goal asks for. A critic scores each draft and sends numbered notes back. The swarm is done when the critic approves. The folder is `examples/writer_critic`. ```text writer ──drafts──> critic ^──── review ─────┘ ``` It takes about 40 seconds. Measured runs cost $0.10 on `claude-sonnet-5-5` and $0.03 on `gpt-6.1-sol`. ## Run it With [`convoyd` running](/docs/quickstart/): ```sh cd examples/writer_critic convoy run convoy watch writer_critic ``` [`convoy watch`](/docs/cli/watch/) shows the two agents and the board as drafts and notes go back and forth. When the critic approves, the run ends and prints the result: ```console run 1 ended: DONE result critic approved true score 9 final A race condition happens when a program's result depends on ... ``` [`convoy ui writer_critic`](/docs/cli/ui/) opens the same run in the browser, with each agent's full transcript. ## The swarm file ```hcl title="main.cvy" # The smallest useful swarm: two agents and one loop. # # writer ──drafts──> critic # ^──── review ─────┘ # # The writer drafts. The critic scores each draft and sends notes back. The # swarm is done when the critic approves. Change the goal and run it again. swarm "writer_critic" { goal = "Explain what a race condition is to a new programmer, in under 150 words, with one concrete example" done_when = agent.critic.output.approved max_runtime = "10m" max_cost_usd = 1 overseer = { provider = provider.llm, can_spawn = false } } # One API key is enough. With an OpenAI key, use the values in the comments. provider "llm" { source = "claude_agent_sdk" # "openai_agents" model = "claude-sonnet-5-5" # "gpt-6.1-sol" } topic "drafts" { description = "The writer's drafts, in full. The newest one counts" } topic "review" { description = "The critic's score and numbered notes on the newest draft" } agent "writer" { provider = provider.llm prompt = file("prompts/writer.md") writes = [topic.drafts] watches = [topic.review] max_turns = 6 } agent "critic" { provider = provider.llm prompt = file("prompts/critic.md") watches = [topic.drafts] writes = [topic.review] output = { approved = bool, score = number, final = string } max_turns = 6 } ``` | Block | What it says | |---|---| | `swarm` | The goal, when the swarm is done (`done_when`), and the limits: ten minutes and one dollar | | `provider` | Which SDK runs the agents, and the model they use | | `topic` | Two channels on the message board, `drafts` and `review` | | `agent "writer"` | Writes to `drafts`. A message on `review` gives it a turn | | `agent "critic"` | A message on `drafts` gives it a turn. It writes to `review` and finishes with a typed `output` | ## Why it loops The loop is not written anywhere as a loop. It comes from who `watches` what: the writer's draft wakes the critic, and the critic's notes wake the writer. See [the message board](/docs/concepts/board/). `done_when = agent.critic.output.approved` reads the critic's output. The critic calling `finish` with `approved = true` is what ends the run. If that never happens, `max_runtime` or `max_cost_usd` ends it instead. See [budgets](/docs/concepts/budgets/). ## The prompts Prompts are plain Markdown. The first line is the one-line role other agents see; the rest is the agent's job. ```md title="prompts/critic.md" Scores each draft against the swarm goal and approves the first one that is good enough. You review drafts of the piece the swarm goal describes. If your turn starts and "drafts" has nothing new, end the turn. A new draft wakes you. For the newest draft on "drafts": 1. Score it from 0 to 10 on three things: it meets every constraint in the goal (length, audience, format), it is accurate, and it is clear. 2. Below 8: publish the score and at most three numbered, specific fixes to "review", then end your turn. 3. 8 or above: call finish with approved = true, the score, and the approved draft, word for word, as final. A first draft can always be tightened, so send one round of notes before you approve anything. On your third review, approve if the draft meets the goal's constraints. ``` The prompts take their task from the swarm's `goal`, so changing the goal line is enough to give the pair a different job. ## Use an OpenAI key instead Change the two lines of the `provider` block to the values in their comments: ```hcl provider "llm" { source = "openai_agents" model = "gpt-6.1-sol" } ``` Nothing else changes. `convoyd` needs `OPENAI_API_KEY` in its environment instead of `ANTHROPIC_API_KEY`. ## Change it - **A different job.** Change the `goal` and run again. - **Talk to it while it runs.** `convoy say writer_critic review "Use a bank account in the example" --to writer` posts to the board as a person and wakes the writer. See [`convoy say`](/docs/cli/say/). - **A cheaper critic.** Add `model = "claude-haiku-5-5"` to the `critic` block. An agent's `model` wins over its provider's. - **A stricter bar.** Add `&& agent.critic.output.score >= 9` to `done_when`. Next: [the research team](/docs/examples/research-team/) adds parallel agents, a dependency graph, and tools. --- # Research team > Three researchers search the web in parallel, a writer turns their findings into a briefing, and an editor sends it back until it scores 8 out of 10. Three researchers search the web at the same time, one per option. When all three have finished, a writer turns their findings into a two-page briefing. An editor scores it and sends it back until it reaches 8 out of 10. The folder is `examples/research_team`. ```text researcher["pgvector"] ─┐ researcher["qdrant"] ─┼─inputs─> writer ──drafts──> editor researcher["milvus"] ─┘ ^──── review ─────┘ ``` The result is a sourced briefing, `report.md`, in the folder you ran `convoy` from. Measured runs took two to four minutes and cost about $0.46 on `claude-sonnet-5-5` and $0.55 on `gpt-6.1-sol`, most of it spent by the three researchers. ## Run it With [`convoyd` running](/docs/quickstart/): ```sh cd examples/research_team convoy run convoy watch research_team # or: convoy ui research_team ``` When the run ends, `report.md` is the briefing, and `convoy status research_team` shows what each agent did and what it cost. ## The swarm file ```hcl title="main.cvy" # A research team. Researchers search the web at the same time, a writer turns # what they found into a briefing, and an editor sends it back until it scores # 8 out of 10. # # researcher["pgvector"] ─┐ # researcher["qdrant"] ─┼─inputs─> writer ──drafts──> editor # researcher["milvus"] ─┘ ^──── review ─────┘ # # The briefing is saved as report.md in the folder you run convoy from. swarm "research_team" { goal = "A sourced two-page briefing: which open-source vector database should a five-person team pick: pgvector, Qdrant, or Milvus?" done_when = agent.editor.output.score >= 8 max_runtime = "20m" max_cost_usd = 3 overseer = { provider = provider.llm, can_spawn = false } } # One API key is enough. With an OpenAI key, use the values in the comments. provider "llm" { source = "claude_agent_sdk" # "openai_agents" model = "claude-sonnet-5-5" # "gpt-6.1-sol" } topic "drafts" { description = "Writer: a draft is saved. Its number and what changed since the last one" } topic "review" { description = "Editor: the score and numbered fixes for the newest draft" } # One researcher per option, all running at once. Add a line to add a researcher. agent "researcher" { for_each = { pgvector = "pgvector, the Postgres extension" qdrant = "Qdrant" milvus = "Milvus" } provider = provider.llm prompt = file("prompts/researcher.md") vars = { subject = each.value } tools = ["web_search"] output = { subject = string, summary = string, facts = list(string), sources = list(string) } max_turns = 4 } # Starts when every researcher has finished, with their outputs as its input. agent "writer" { provider = provider.llm prompt = file("prompts/writer.md") vars = { report = "${env("PWD")}/report.md" } tools = ["write_file"] inputs = { research = values(agent.researcher)[*].output } writes = [topic.drafts] watches = [topic.review] max_turns = 6 } agent "editor" { provider = provider.llm prompt = file("prompts/editor.md") vars = { report = "${env("PWD")}/report.md" } tools = ["read_file"] watches = [topic.drafts] writes = [topic.review] output = { score = number, verdict = string } max_turns = 6 } ``` ## What it adds - **`for_each` makes several agents from one block.** The map has one entry per option, so there are three researchers, named `researcher["pgvector"]` and so on. `each.value` goes into the prompt through `vars`. Add a line to the map and there is a fourth. See [agents](/docs/dsl/agent/). - **`inputs` is the dependency graph.** The writer's `inputs` reads every researcher's `output`, so the writer starts only when all of them have finished, and their outputs arrive as JSON in its first turn. Nobody wrote "wait for the researchers". - **`output` is typed.** A researcher has to finish with a subject, a summary, a list of facts, and a list of sources. `convoyd` checks the payload against the declared shape, so the writer can rely on it. - **`tools` are per agent.** The researchers get `web_search`, the writer `write_file`, the editor `read_file`. The swarm tools (the board, `finish`, `report_progress`) are always there and are not listed. `done_when = agent.editor.output.score >= 8` is an ordinary expression over an agent's output. `env("PWD")` is the folder you ran `convoy run` from. That is how the writer and the editor agree on where `report.md` is. ## Use an OpenAI key instead Change the two lines of the `provider` block to the values in their comments: ```hcl provider "llm" { source = "openai_agents" model = "gpt-6.1-sol" } ``` The tool names are the same on both providers, so nothing else changes. `convoyd` needs `OPENAI_API_KEY` in its environment instead of `ANTHROPIC_API_KEY`. ## Change it - **A different question.** Change the `goal` and the `for_each` map together: one entry per thing to research. - **Mix models.** Give the editor a stronger model with `model = "claude-opus-5-5"` in its block, or add a second `provider` block and put the researchers on it. A swarm can mix providers freely. - **Steer it.** `convoy say research_team review "Weigh operational cost more heavily" --to writer`. Next: [the code team](/docs/examples/code-team/) adds a worker pool, addressed messages, and a `done_when` backed by a test suite. --- # Code team > A planner splits a small project, two coders build their halves at the same time, and a reviewer runs the tests until the whole suite passes. A planner splits a small project in two and sends each coder its half. The coders build at the same time in one shared folder. A reviewer runs the whole test suite, tries the program, and sends each failure back to the coder who owns the file. The swarm is done when everything passes. The folder is `examples/code_team`. ```text planner ──work──> coder[0], coder[1] ──done──> reviewer │ ^──────── review ───────────┘ └───────────────── inputs ─────────────────────┘ ``` The result is a working, tested Python package in `./workspace`. Measured runs took one to two minutes and cost about $0.17 on `claude-sonnet-5-5` and $0.14 on `gpt-6.1-sol`, for a package with fifteen to thirty passing tests. The coders and the reviewer have the `bash` tool, with your user's permissions and no sandbox. They are told to stay inside `./workspace`. Read the prompts before you point this at anything you care about. ## Run it With [`convoyd` running](/docs/quickstart/): ```sh cd examples/code_team convoy run convoy watch code_team # or: convoy ui code_team ``` When the run ends, do not take the reviewer's word for it. Run the tests and the program yourself: ```sh cd workspace uv run --no-project --with pytest python -m pytest -q python -m wordfreq ../README.md ``` ## The swarm file ```hcl title="main.cvy" # A small engineering team. A planner splits the job, two coders build their # halves at the same time, and a reviewer runs the tests and sends each # failure back to the coder who owns it. Done when the whole suite passes. # # planner ──work──> coder[0], coder[1] ──done──> reviewer # │ ^──────── review ───────────┘ # └───────────────── inputs ─────────────────────┘ # # The code is written to ./workspace in the folder you run convoy from. swarm "code_team" { goal = "Build wordfreq, a Python command-line tool with pytest tests. `python -m wordfreq FILE` prints the file's word count, its reading time at 200 words a minute, and its ten most frequent words." done_when = agent.reviewer.output.approved max_runtime = "30m" max_cost_usd = 5 overseer = { provider = provider.llm, can_spawn = false } } # One API key is enough. With an OpenAI key, use the values in the comments. provider "llm" { source = "claude_agent_sdk" # "openai_agents" model = "claude-sonnet-5-5" # "gpt-6.1-sol" } topic "work" { description = "Planner to one coder: the files that coder owns, what they must do, and what the other coder provides" } topic "done" { description = "Coders: my part is ready. Files, number of tests, last line of the test run" } topic "review" { description = "Reviewer to one coder: the failing tests in that coder's files, with the first error of each" } # Designs the split, sends each coder its task, and finishes with the # ownership map the reviewer routes failures by. agent "planner" { provider = provider.llm prompt = file("prompts/planner.md") writes = [topic.work] output = { owners = map(string), run = string, notes = string } max_turns = 3 } # Two coders from one block. They start at once, wait for a task addressed to # them, and are woken again by anything the reviewer sends back. agent "coder" { count = 2 provider = provider.llm prompt = file("prompts/coder.md") vars = { dir = "${env("PWD")}/workspace" test = "uv run --no-project --with pytest python -m pytest -q" } tools = ["bash", "read_file", "write_file", "edit_file"] writes = [topic.done] watches = [topic.work, topic.review] max_turns = 8 } # Starts when the planner finishes, then loops with the coders through the # board. Its approval ends the swarm. agent "reviewer" { provider = provider.llm prompt = file("prompts/reviewer.md") vars = { dir = "${env("PWD")}/workspace" test = "uv run --no-project --with pytest python -m pytest -q" } tools = ["bash", "read_file"] inputs = { plan = agent.planner.output } writes = [topic.review] watches = [topic.done] output = { approved = bool, passed = number, total = number, notes = string } max_turns = 10 } ``` ## What it adds - **`count` makes a pool.** `count = 2` creates `coder[0]` and `coder[1]` from one block. - **Messages can be addressed.** The planner publishes one task per coder with `to` set, and the reviewer sends each failure to the coder whose file is at fault. Everyone can read the board, but an addressed message wakes only its recipient. See [the message board](/docs/concepts/board/). - **`done_when` rests on something real.** The reviewer approves only after it has run the suite and the program in that turn, so `agent.reviewer.output.approved` means the tests passed. - **One agent can be in the graph and in a loop.** The reviewer starts when the planner finishes (`inputs`), then goes round with the coders through the `done` and `review` topics. ## The reviewer's prompt ```md title="prompts/reviewer.md" Runs the whole test suite when coders report done, sends failures to their owners, and approves when everything passes. Your input `plan` is the planner's output. `plan.owners` maps every file to the coder that owns it, and `plan.run` is the command that runs the finished program. The shared project folder is {{dir}}. You read and run code there. You never edit it. EACH TURN Read what is new on "done" first. 1. If a coder named in `plan.owners` has not posted to "done" yet, end your turn. The next post wakes you. 2. Run the whole suite: cd {{dir}} && {{test}} 3. Try the program the way a user would: write a short text file, run `plan.run` on it, and check the output against the swarm goal. 4. For each failing test or wrong output, publish one message to "review" with `to` set to the owner of the file at fault, from `plan.owners`: the failing test ids and the first error line of each, or the command you ran and what it printed. Then end your turn and wait for the fix. 5. When every test passes and the program does what the goal says, call finish with approved = true, passed and total from the test output, and one sentence of notes. Never approve with zero tests, and never approve a suite you did not run in this turn. ``` `{{dir}}` and `{{test}}` are replaced from the agent's `vars`. ## Use an OpenAI key instead Change the two lines of the `provider` block to the values in their comments: ```hcl provider "llm" { source = "openai_agents" model = "gpt-6.1-sol" } ``` `bash`, `read_file`, `write_file`, and `edit_file` exist on both providers, so nothing else changes. `convoyd` needs `OPENAI_API_KEY` in its environment instead of `ANTHROPIC_API_KEY`. ## Change it - **Build something else.** Change the `goal`. The planner designs the split from it, so any small Python package works: a Markdown table formatter, a unit converter, a log summarizer. - **Steer it.** `convoy say code_team review "Add a --top N flag" --to "coder[1]"`. - **Put the planner on a bigger model.** Add `model = "claude-opus-5-5"` to the `planner` block. For larger swarms shaped after long-horizon benchmarks, see [the benchmark swarms](/docs/examples/#benchmark-swarms). --- # PaperBench replication > Replicate an ICML 2024 paper from scratch with a reader, four parallel builders, an experimenter, and a judge on a different model. The shape here is a dependency graph that fans out and back in, with a review loop at the end. The folder is `examples/benchmarks/01_paperbench_replication`. ## The benchmark [PaperBench](https://github.com/openai/preparedness/tree/main/project/paperbench) (OpenAI) gives an agent one of 20 ICML 2024 papers and asks for a from-scratch replication: code, execution, and results. A rubric co-written with the authors breaks each paper into hundreds of weighted leaves of three kinds: Code Development, Execution, and Result Match. The canonical budget is 24 hours per attempt. Human ML PhDs score about 41% in that time; the best published agents, about 26%. The paper used here is `semantic-self-consistency`. Its rubric covers three datasets, the generator models and their decoding limits, two featurizers, the methods of Section 4, and the experiments of Sections 5.1 and 5.2. ## Why this shape A replication has natural stages. Someone has to read the paper once and write the plan; the plan splits into independent workstreams; the pieces must exist before the experiments run; and a grader that did none of the work decides whether the result holds. The graph (`inputs`, `depends_on`) carries the work forward and never cycles. The board carries the review loop: `results` wakes the judge, `gaps` wakes the experimenter. ```text reader ──> builder[data, generators, featurizers, methods] ──> experimenter <──> judge results ──> <── gaps ``` | Agent | Model | Starts when | Finishes when | |---|---|---|---| | `reader` | Opus | swarm starts | plan written, typed output returned | | `builder[*]` (4 instances) | Sonnet | reader is done (`inputs`) | its workstream passes its smoke test | | `experimenter` | Sonnet | all four builders are done (`inputs`) | never; stopped when the swarm ends | | `judge` | Opus | all four builders are done (`depends_on`) | `approved = true`, or it gives up after 8 rounds | `done_when = agent.judge.output.approved == true`. ## The swarm file ```hcl title="main.cvy" # PaperBench: replicate an ICML 2024 paper from scratch. # # Paper: "semantic-self-consistency", one of the 20 PaperBench papers. Its rubric # checks the datasets, the generator models, the featurizers, the methods of # Section 4, and whether the experiments of Sections 5.1 and 5.2 reproduce the # paper's conclusions. A human expert takes days. # # Shape: a dependency graph that fans out and back in, with a judge loop at the end. # # reader ──> builder[data, generators, featurizers, methods] ──> experimenter <──> judge # # The graph (inputs, depends_on) carries work forward and never cycles. The board # (results, gaps) carries the review loop. The swarm ends when the judge, grading # against the rubric on a different model than the one that did the work, says # the replication is approved. swarm "paperbench_ssc" { goal = <<-EOT Replicate the ICML 2024 paper "Semantic Self-Consistency" from scratch: data pipeline, generator models, featurizers, every method in Section 4, and the experiments of Sections 5.1 and 5.2, so that the reproduced results support the paper's conclusions. EOT done_when = agent.judge.output.approved == true max_runtime = "24h" # PaperBench's canonical budget per attempt max_cost_usd = 400 overseer = { provider = provider.anthropic model = "claude-sonnet-5" } } provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" } topic "results" { description = "Experimenter: a completed run of Sections 5.1 and 5.2, with the results table path and the headline numbers next to the paper's" } topic "gaps" { description = "Judge: rubric requirements not met yet, one message per grading round, addressed to the experimenter" } topic "human" { description = "Blocked on a person: API keys, GPU quota, or a choice the paper leaves open" } # Stage 1. One agent reads the paper and writes the plan everyone else builds from. agent "reader" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/reader.md") vars = { paper = "semantic-self-consistency" workspace = env("PAPERBENCH_WORKSPACE") } tools = ["read_file", "bash"] writes = [topic.human] output = { summary = string contributions = list(string) acceptance = map(string) # keyed by workstream: what must exist when it is done compute = string } } # Stage 2. Four builders from one block. The map key is the workstream and the # value is its brief; each.key and each.value reach the prompt through vars. # Every instance starts the moment the reader finishes, because of inputs. agent "builder" { for_each = { data = "Section 3 and the appendix: the AQuA-RAT test split (254 samples), the StrategyQA test split (687), the full SVAMP set (1000), and the k-shot prompt for each dataset" generators = "Section 3.1: every generator model with top-p = 1 and the per-dataset max-new-token limits, plus the parsing extraction that pulls an answer out of a response" featurizers = "Section 3.2: RoBERTa-base and SciBERT embeddings for a response string" methods = "Section 4: the top-prob and self-consistency baselines, semantic self-consistency, and the KNN, isolation forest, and SVM outlier removal" } provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/builder.md") vars = { workstream = each.key brief = each.value workspace = env("PAPERBENCH_WORKSPACE") } tools = ["bash", "read_file", "write_file", "edit_file"] inputs = { plan = agent.reader.output } writes = [topic.human] output = { module = string entrypoints = list(string) smoke_test = string notes = string } } # Stage 3. Starts when all four builders are done. Runs the experiments, then # stays alive to fix whatever the judge finds. agent "experimenter" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/experimenter.md") vars = { workspace = env("PAPERBENCH_WORKSPACE") } tools = ["bash", "read_file", "write_file", "edit_file"] inputs = { plan = agent.reader.output components = values(agent.builder)[*].output # every instance of a for_each agent } writes = [topic.results, topic.human] watches = [topic.gaps, topic.human] max_turns = 30 } # Stage 4. The judge grades against the rubric. It runs a different model than # the agents that did the work, the cheap form of an independent judge, and its # finish is the only thing that can end the swarm. agent "judge" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/judge.md") vars = { workspace = env("PAPERBENCH_WORKSPACE") rubric = env("PAPERBENCH_RUBRIC") } tools = ["read_file", "bash"] inputs = { plan = agent.reader.output } depends_on = [agent.builder] # every builder instance, not one of them watches = [topic.results] writes = [topic.gaps] output = { approved = bool score = number # weighted share of rubric requirements met, 0 to 1 missing = list(string) rounds = number } max_turns = 10 } ``` ## Key prompts The reader's prompt fixes the contract with the builders: its `acceptance` map must have exactly the four workstream keys. ```text title="prompts/reader.md (excerpt)" WORKSTREAMS Four builders start the moment you finish, one per workstream: data, generators, featurizers, methods. Your `acceptance` map must have exactly those four keys. Each value is that workstream's definition of done: the file paths that must exist, the functions that must be callable, the numbers that must match the paper (dataset sizes, hyperparameters, token limits). Write it so a builder who has never seen the paper can finish from your text alone. ``` The judge's prompt sets the approval rule and the give-up rule. Only its `finish` can end the swarm. ```text title="prompts/judge.md (excerpt)" APPROVAL Call finish with approved = true only when all three hold: - every Code Development and Execution requirement is met; - both Result Match requirements, Sections 5.1 and 5.2, hold: the reproduced numbers support the paper's conclusions within the tolerance the rubric or the addendum gives; - score >= 0.75. If after 8 rounds the score has stopped improving, publish a last "gaps" message marked FINAL, then finish with approved = false and the honest score. The swarm then ends without meeting done_when, which is the right outcome for an unfinished replication. ``` ## How a run unfolds 1. The controller creates `reader`, four `builder` instances, `experimenter`, `judge`, and the overseer, all Pending. Only `reader` has no unmet `inputs` or `depends_on`, so it starts first. 2. The reader reads the paper, checks the machine, writes `PLAN.md`, and finishes with a typed output: `summary`, `contributions`, `acceptance` keyed by workstream, and `compute`. If something is missing (a key, a dataset), it publishes once to `human` and finishes anyway. 3. The reader is Done, so the four builders' `inputs` are satisfied and all four start at once. Each receives the plan as JSON on its first turn, and `{{workstream}}` and `{{brief}}` come from its `for_each` entry. Each builds its module and smoke test and finishes with `module`, `entrypoints`, `smoke_test`, and `notes`. 4. When the fourth builder finishes, the experimenter starts with `plan` and `components` (the list of all four builder outputs), and the judge starts because `depends_on = [agent.builder]` resolves to every instance. The judge reads the rubric once, reports its structure, and waits. 5. The experimenter runs Sections 5.1 and 5.2 and publishes to `results`. That wakes the judge. 6. Each grading round, the judge reads the code (not the summary), walks the rubric leaf by leaf, computes a weighted `score`, and publishes one message to `gaps` addressed to the experimenter. The message wakes the experimenter, which fixes and publishes to `results` again. 7. The loop ends when the judge calls `finish` with `approved = true` and a score of at least 0.75. If the score stops improving after 8 rounds, it finishes with `approved = false`, and the run ends without meeting `done_when`. 8. Any limit ends the run first if reached: `max_runtime = "24h"` or `max_cost_usd = 400`. ## DSL features shown - [`for_each`](/docs/dsl/agent/) over a map: the key names the workstream, the value is its brief, and both reach the prompt through `vars`. - Typed, nested `output` on the reader (`map(string)`, `list(string)`) that downstream agents receive as JSON on their first turn. - Fan-in with `values(agent.builder)[*].output`, the idiom for every instance of a `for_each` agent. See [references and functions](/docs/dsl/expressions/). - `depends_on = [agent.builder]` on the judge, which resolves to every builder instance. - A judge on a different model from the workers, whose typed `output` is the only thing `done_when` reads. See [`swarm`](/docs/dsl/swarm/). - `env()` inside `vars` to hand every agent one shared workspace path. - Agents that finish in one turn (reader, builders) next to agents that live on the board (experimenter, judge). See [agents and turns](/docs/concepts/agents/) and [topics and the board](/docs/concepts/board/). ## Run it You need a PaperBench checkout with the paper hydrated, a GPU machine, and `convoyd` running. ```sh export ANTHROPIC_API_KEY=... # in convoyd's environment: api_key names this variable export PAPERBENCH_WORKSPACE=/srv/paperbench/semantic-self-consistency # paper/ and agent.env live here export PAPERBENCH_RUBRIC=/srv/paperbench/grading/semantic-self-consistency/rubric.json mkdir -p $PAPERBENCH_WORKSPACE/paper $(dirname $PAPERBENCH_RUBRIC) cp /data/papers/semantic-self-consistency/{paper.md,paper.pdf,blacklist.txt,addendum.md} $PAPERBENCH_WORKSPACE/paper/ cp /data/papers/semantic-self-consistency/rubric.json $PAPERBENCH_RUBRIC convoy validate convoy run convoy watch paperbench_ssc convoy say paperbench_ssc human "HF_TOKEN is in agent.env now" --to experimenter ``` ## Machine assumptions - All agents run on one machine and share `$PAPERBENCH_WORKSPACE`. Convoy's MVP work folders are per agent, so the shared checkout is passed by path. The rubric lives outside the workspace and only the judge's prompt names it; the separation is by convention until the sandbox backend lands. - The judge is Claude Opus 5 reading the code directly. PaperBench's own judge runs in a separate container over the executed submission. An OpenAI judge in this swarm would need a shared artifact store, which the MVP does not have. - Grading follows PaperBench's rubric kinds but not its scoring code. Run the official judge on `$PAPERBENCH_WORKSPACE` afterwards for the comparable number. --- # Commit0 library > Rebuild simpy from its spec with a lead, a pool of four implementers, and an integrator, and compare it with a one-agent baseline at the same budget. The shape here is a task board with a worker pool. The folders are `examples/benchmarks/02_commit0_library` (the team) and `examples/benchmarks/02_commit0_library/solo` (one agent). ## The benchmark [Commit0](https://commit-0.github.io/) asks an agent to rebuild one of 54 real Python libraries from commit zero. It gets the specification, the source tree with every function stubbed (signature and docstring, no body), and the library's real unit-test suite. The score is the share of tests that pass. Libraries range from 38 tests to 40,000, and no published agent has fully reproduced one. The library used here is `simpy`, discrete-event simulation: a core event loop, event types, resources (container, resource, store), real-time mode, and utilities. It has clean module boundaries, so modules can be owned. ## Why this shape Rebuilding a library is parallel work with one shared oracle. Modules can be written independently, but the real test suite only tells the truth when everything is assembled. So one agent decomposes the stub tree and assigns each module, a pool of identical workers implements, and one integrator runs the whole suite on every build and routes failures back to the owner. ```text lead ──tasks──> implementer[0..3] ──builds──> integrator │ ^ │ │ └───────── failures ────────────┘ └── inputs: who owns what ────────────────────────────┘ ``` | Agent | Model | Starts when | Lives | |---|---|---|---| | `lead` | Opus | swarm starts | one turn: maps modules, assigns them, finishes with the owner map | | `implementer[*]` (4) | Sonnet | swarm starts | on the board: woken by assignments and by failures addressed to them | | `integrator` | Sonnet | lead is done (`inputs`) | on the board: runs the real suite on every build, finishes at 95% | `done_when = agent.integrator.output.pass_rate >= 0.95`. ## The team: main.cvy ```hcl title="main.cvy" # Commit0: build a whole library from its specification until the test suite passes. # # Library: simpy (discrete-event simulation), one of the 54 Commit0 libraries. # Commit0 gives a spec, a source tree of function stubs with docstrings and no # bodies, and the library's real unit-test suite. The score is the share of # tests that pass. # # Shape: a task board. # # lead ──tasks──> implementer[0..3] ──builds──> integrator # │ ^ │ # │ └───────── failures ────────────┘ # └── inputs: who owns what ────────────────────────────┘ # # The lead decomposes the stub tree into modules and assigns each one by # publishing to "tasks" with "to" set to one implementer. The implementers are # an anonymous pool: one block, four instances, the same prompt. The integrator # starts when the lead's assignment map exists, runs the real suite on every # build, and routes failures back to the owner. The swarm ends when the suite # passes. swarm "commit0_simpy" { goal = "Rebuild the simpy library from the Commit0 specification and stubs until at least 95 percent of its unit tests pass and lint is clean" done_when = agent.integrator.output.pass_rate >= 0.95 max_runtime = "12h" max_cost_usd = 150 overseer = { provider = provider.anthropic model = "claude-sonnet-5" } } provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" } topic "tasks" { description = "Lead: one module assignment per message, addressed to the implementer that owns it: module, public names, the tests that cover it, what it depends on" } topic "builds" { description = "Implementers: a module is ready to test. Module path, files touched, the test ids it should pass" } topic "failures" { description = "Integrator: failing tests or lint for one module, addressed to its owner, with the test ids and the first assertion of each" } topic "human" { description = "Spec ambiguities only a person can settle" } # Runs once. Reads the spec and the stub tree, assigns modules, finishes with # the owner map that the integrator needs to route failures. agent "lead" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/lead.md") vars = { repo = env("COMMIT0_REPO_DIR") library = "simpy" workers = "implementer[0], implementer[1], implementer[2], implementer[3]" } tools = ["bash", "read_file"] writes = [topic.tasks, topic.human] output = { owners = map(string) # module path -> implementer instance name order = list(string) # module paths, leaves first notes = string } } # One block, four identical workers. Each instance learns its own name through # vars and acts only on messages addressed to it. agent "implementer" { count = 4 provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/implementer.md") vars = { me = "implementer[${count.index}]" repo = env("COMMIT0_REPO_DIR") library = "simpy" } tools = ["bash", "read_file", "write_file", "edit_file"] writes = [topic.builds, topic.human] watches = [topic.tasks, topic.failures] max_turns = 60 can_spawn = true # may create a helper for an oversized module } # Starts when the lead is done (a graph edge), then cycles with the # implementers through the board (not a graph edge). Its finish ends the swarm. agent "integrator" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/integrator.md") vars = { repo = env("COMMIT0_REPO_DIR") library = "simpy" } tools = ["bash", "read_file"] inputs = { assignments = agent.lead.output } writes = [topic.failures, topic.human] watches = [topic.builds, topic.human] output = { passed = number total = number pass_rate = number lint_clean = bool } max_turns = 80 } ``` ## Key prompts The lead assigns one module per message, addressed with `to`. The pool is anonymous; routing is a field on `publish`, not a runtime list in the DSL, because `count` is static. ```text title="prompts/lead.md (excerpt)" 3. Assign. For each module publish ONE message to "tasks" with "to" set to the owner. The owners are exactly: {{workers}}. Each message says: the module path, its public names, the test ids that cover it, what it depends on and who owns that, and the spec sections the implementer must read. One module per message so the owner can report progress per module. 4. Where the spec and the tests disagree, the tests win; say so in the message. Where only a person can settle it (a removed feature, a licence question), publish to "human" and move on. ``` The integrator keeps the owner map from its first input and uses it to route. ```text title="prompts/integrator.md (excerpt)" EACH TURN 1. Run the whole suite, not just the module announced: cd {{repo}} && commit0 test {{repo}} --backend local --timeout 1800 then lint: `commit0 lint {{repo}}`. Save the output under {{repo}}/.integrator/run-.txt so you can diff runs. 2. Count: passed, total, pass_rate = passed / total. Call report_progress with those numbers and the run id. That number is what everyone watches. 3. For every module with failing tests, publish ONE message to "failures" with "to" set to owners[module]: the failing test ids, the first assertion line of each, and whether the failure looks like it belongs to a dependency owned by someone else (then address that owner instead and say why). 4. A module whose tests all pass gets no message. Silence means good. ``` ## How a run unfolds 1. The controller creates the lead, four implementers, the integrator, and the overseer. The lead and the implementers have no `inputs`, so all five start. The implementers have nothing addressed to them yet and idle on the board; the integrator stays Pending until the lead finishes. 2. The lead reads the spec and the stub tree, groups the modules into four workloads of similar size, and publishes one message per module to `tasks`, each with `to` set to an owner such as `implementer[1]`. It finishes with `owners` (module to instance), `order` (leaves first), and `notes`. 3. Each assignment wakes its addressed implementer, which implements the bodies, runs that module's tests, and publishes to `builds`. An implementer that finds a module too large may call `create_agent` for a helper, because `can_spawn = true`. The child can only use the parent's tools, provider, and model, and stops when the parent stops. 4. The lead is Done, so the integrator starts with `assignments`. Each `builds` message wakes it. It runs the whole suite and lint, reports the pass rate, and publishes a message to `failures` addressed to the owner of each failing module. 5. A failure message wakes its owner, which fixes and publishes to `builds` again. Four implementers edit one checkout; ownership is per module, so they do not collide, and the integrator's full-suite run is what catches a signature change under someone else's module. 6. The integrator calls `finish` when `pass_rate >= 0.95` and lint is clean. That makes `done_when` true and the run ends. 7. A person can intervene at any point: `convoy say commit0_simpy human "skip the rt module" --to integrator`. ## The solo arm `solo/` is the same job for one agent: same provider, model, tools, `max_runtime`, and `max_cost_usd`, with spawning off for the agent and the overseer. | | Team | Solo | |---|---|---| | Provider, model, tools | Sonnet with bash, read, write, edit for the workers | the same | | `max_runtime` | 12h | 12h | | `max_cost_usd` | 150 | 150 | | Overseer | Sonnet, spend counts | Sonnet, spend counts, `can_spawn = false` | | Can grow | implementers have `can_spawn = true` | no agent can spawn | The team's lead runs on Opus; that is part of what the team design buys with the same budget. ```hcl title="solo/main.cvy" # Commit0, solo arm: the same job as ../main.cvy, done by one agent. # # This is the baseline for the MVP's acceptance test: does a declared team beat # one agent at the same budget? Everything the team has, this agent has: the # same provider, model, and tools as the team's implementers, the same # max_runtime, and the same max_cost_usd. The overseer runs here too and its # spend counts, as in the team arm. Neither the agent nor the overseer may # create agents, so the solo arm stays one agent for the whole run. # # The score is not taken from this file. After the run, the library's real test # suite is run on the checkout by a script outside convoy, for both arms. swarm "commit0_simpy_solo" { goal = "Rebuild the simpy library from the Commit0 specification and stubs until at least 95 percent of its unit tests pass and lint is clean" done_when = agent.solo.output.pass_rate >= 0.95 max_runtime = "12h" max_cost_usd = 150 overseer = { provider = provider.anthropic model = "claude-sonnet-5" can_spawn = false } } provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" } topic "human" { description = "Spec ambiguities only a person can settle" } # One agent does the lead's, the implementers', and the integrator's work. It # watches nothing, so it never waits: each time it ends a turn without calling # finish it gets a continue turn, until it finishes or reaches max_turns. A # person steers it with `convoy say commit0_simpy_solo human "..." --to solo`; # addressed messages arrive at the start of its next turn. agent "solo" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/solo.md") vars = { repo = env("COMMIT0_REPO_DIR") library = "simpy" } tools = ["bash", "read_file", "write_file", "edit_file"] writes = [topic.human] watches = [] can_spawn = false output = { passed = number total = number pass_rate = number lint_clean = bool } max_turns = 200 } ``` The solo agent watches nothing, so it never waits. Each time it ends a turn without calling `finish` it gets a continue turn, until it finishes or reaches `max_turns`. A person steers it with `--to solo`. This is the one swarm that gets the expected `TS051` warning from [`convoy validate`](/docs/cli/validate/), because its `human` topic has no watcher. ## The MVP acceptance test The two folders are the MVP's acceptance test. The MVP is done when it can answer one question on one Commit0 library: does a declared team beat one agent at the same budget? - Two swarm folders: the team and the solo arm. Both use the same model, tools, `max_runtime`, and `max_cost_usd`, and run on the same `convoyd`. - Each is run 3 times, each on a fresh checkout so the arms never share files. - After each run, a script outside Convoy runs the library's real test suite and records the pass rate. The swarm's own `done_when` decides when to stop; it is not trusted as the score. - The report is one row per run: pass rate, dollars spent, wall-clock time, and end reason (`done`, `budget`, `max_runtime`), taken from `convoy status --json`. Convoy's job is to run both arms identically and report spend honestly. Scoring stays outside it. The MVP is done regardless of which arm wins; the answer is the result. ```sh title="one solo run" export COMMIT0_REPO_DIR=/srv/commit0/runs/solo-1/simpy commit0 setup simpy --base-dir /srv/commit0/runs/solo-1 convoy validate convoy run convoy status commit0_simpy_solo --json # spend, elapsed time, end reason ``` ## DSL features shown - The task-board shape: one agent publishes tasks, a pool watches for them. Assignment is decided at runtime by the lead; the pool is `toset(["a", "b", "c", "d"])` and routing is the `to` field of `publish`. See [`agent`](/docs/dsl/agent/). - An anonymous worker pool: one block with `count = 4` and `vars = { me = "implementer[${count.index}]" }` so each knows its own name. - A graph edge and a board loop on the same agent: the integrator starts from the lead's typed `output` and then cycles with the implementers through `builds` and `failures`. See [topics and the board](/docs/concepts/board/). - Long-lived agents with explicit `max_turns`, next to a single-turn agent without one. - `create_agent` from a prompt, gated by `can_spawn = true`. See [spawning agents](/docs/concepts/spawning/). - A person in the loop through the `human` topic and [`convoy say`](/docs/cli/say/). ## Run the team ```sh pip install commit0 export COMMIT0_REPO_DIR=/srv/commit0/repos/simpy commit0 setup simpy --base-dir /srv/commit0/repos # one repository is a valid split; "lite" and "all" also work commit0 build export ANTHROPIC_API_KEY=... # in convoyd's environment: api_key names this variable convoy validate convoy run convoy watch commit0_simpy ``` ## Machine assumptions - The integrator runs `commit0 test --backend local`. Commit0's default backend is Modal; change the prompt if you run there. - The 95% bar is a choice for this sample. Commit0's own score is the raw pass share, and the integrator's output carries `passed` and `total`, so the official number is in the finish payload too. - Four implementers edit one checkout on one machine. --- # Vending-Bench > Run a vending machine for a simulated year with three agents on three SDKs, a loop that sustains itself through the board, and week-long limits. The shape here is a long-lived operations loop. The folder is `examples/benchmarks/03_vending_bench`, and it is the one sample split across several files. ## The benchmark [Vending-Bench 2](https://andonlabs.com/evals/vending-bench-2) (Andon Labs) hands the agent a vending machine, $500, and a $2 daily fee, and scores the bank balance after one simulated year. Suppliers and customers are other LLMs: suppliers quote bad prices, bait and switch, or vanish after payment, and customers email for refunds. Payments are irreversible. A run is 3,000 to 6,000 messages and tens of millions of tokens. It is built to catch slow derailment: forgotten orders, a belief the numbers refute, meltdown loops. The best models today end the year around $16k; Andon estimates a good strategy is worth about $63k. ## Why this shape What the benchmark measures is not any one decision but whether the agent stays coherent for a year. Convoy's answer is to split the roles so that no single context has to carry the year. One agent has the hands, one keeps the books from the board alone, and one audits weekly for drift. Nobody schedules the next day: the board does. ```text operator ──daily_log──> bookkeeper ──ledger──> operator one cycle per simulated day ──weekly──> auditor ──directives──> operator ──alerts──> operator ``` | Agent | SDK · model | Tools | Role | |---|---|---|---| | `operator` | Claude Agent SDK · Opus | `bash` into the simulator | the hands: one turn is one simulated day | | `bookkeeper` | local Ollama (`openai_compatible`) | none | the books: reconciles every day from the board alone | | `auditor` | OpenAI Agents SDK · GPT | none | the second pair of eyes: a weekly drift check, one directive at most | `done_when = agent.operator.output.day >= 365 || agent.operator.output.bankrupt == true`. ## The swarm files Every `*.cvy` file in the folder is merged, so block order and file boundaries do not matter. `main.cvy` holds the swarm and the agents. ```hcl title="main.cvy" # Vending-Bench 2: run a vending machine business for a simulated year. # # The benchmark gives the agent $500, charges $2 a day, and scores the bank # balance after one simulated year. Suppliers are other LLMs that quote bad # prices, bait and switch, or vanish after being paid; payments are final; # customers email for refunds. A run is 3,000 to 6,000 messages. What it # measures is not any one decision but whether the agent stays coherent for a # year: no forgotten orders, no chasing a mistaken belief, no meltdown loops. # # Shape: a long-lived operations loop that sustains itself through the board. # # operator ──daily_log──> bookkeeper ──ledger──> operator one cycle per simulated day # ──weekly──> auditor ──directives──> operator # ──alerts──> operator # # Nobody schedules the next day. The operator's evening report wakes the # bookkeeper; the bookkeeper's reconciliation wakes the operator for the # morning. The three agents run on three providers: the hands are Claude # with bash, the books are a local model with no tools at all, the auditor is # an OpenAI model that only reads the board. # # This file holds the swarm and the agents. providers.cvy and topics.cvy are # merged in, as every *.cvy file in the folder is. swarm "vending_year" { goal = <<-EOT Run the Vending-Bench 2 machine for a full simulated year and end with the highest bank balance possible without going bankrupt. Keep every order, delivery, and payment accounted for all year. EOT done_when = agent.operator.output.day >= 365 || agent.operator.output.bankrupt == true max_runtime = "168h" max_cost_usd = 300 overseer = { provider = provider.anthropic model = "claude-sonnet-5" } } # The hands. One turn is one simulated day. A progress report every day keeps # the overseer and convoy status current on where the year stands. agent "operator" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/operator.md") vars = { sim = env("VENDING_SIM_URL") approval_limit = "300" # single payments above this wait for a person on "human" } tools = ["bash"] writes = [topic.daily_log, topic.human] watches = [topic.ledger, topic.alerts, topic.directives, topic.human] output = { day = number balance = number bankrupt = bool best_sellers = list(string) } max_turns = 1500 } # The books. A local model given no tools: the board is its memory and # its only interface. It cannot reach the simulator, so no supplier can talk it # into anything. agent "bookkeeper" { provider = provider.local model = "qwen3:32b" prompt = file("prompts/bookkeeper.md") writes = [topic.ledger, topic.weekly, topic.alerts] watches = [topic.daily_log] max_turns = 800 } # The second pair of eyes. A different vendor's model that reads the weekly # summary and looks for drift: repeated losing strategies, orders placed twice, # beliefs the numbers do not support. It can only publish directives. agent "auditor" { provider = provider.openai model = "gpt-6.1-sol" prompt = file("prompts/auditor.md") writes = [topic.directives, topic.human] watches = [topic.weekly, topic.alerts] max_turns = 120 } ``` `providers.cvy` declares one provider per SDK. The `local` provider has a zero price, and the agent on it lists no tools, since the price table only knows hosted models. ```hcl title="providers.cvy" # Three providers, one per built-in type, in one swarm. An agent names one # with provider., and the built-in tools it may list depend on the # provider's type (its source). provider "anthropic" { source = "claude_agent_sdk" # offers web_search, bash, read_file, write_file, edit_file api_key = "ANTHROPIC_API_KEY" } provider "openai" { source = "openai_agents" # hosted web_search, code_interpreter, file_search, and the local tools api_key = "OPENAI_API_KEY" } provider "local" { source = "openai_compatible" # offers bash and the file tools; the bookkeeper lists none base_url = "http://localhost:11434/v1" # Ollama, or any Chat Completions endpoint price = { input = 0, output = 0 } # runs locally; not in the built-in price table } ``` `topics.cvy` is the board. Cadence is encoded in topics. ```hcl title="topics.cvy" # The board. One topic per kind of message. Cadence is encoded in topics: # daily_log and ledger move once a day, weekly once a week, alerts and # directives only when something is wrong. topic "daily_log" { description = "Operator, end of each simulated day: day, balance, sales, orders placed, payments made, deliveries received, prices changed" } topic "ledger" { description = "Bookkeeper, after each daily log: the reconciled line for the day and every open order with its expected delivery day. Wakes the operator for the next morning" } topic "weekly" { description = "Bookkeeper, every seventh day: the week in numbers, the cash trend, inventory turns, anything that did not reconcile" } topic "alerts" { description = "Bookkeeper to operator: a paid order with no delivery past its date, a duplicate order, a balance that does not match the log" } topic "directives" { description = "Auditor to operator: one specific change of course, with the ledger evidence for it" } topic "human" { description = "A payment above the approval limit, or a decision the operator should not make alone" } ``` ## Key prompts The operator's prompt defines the day. One turn is one day, and the message it publishes at the end is the bookkeeper's only input. ```text title="prompts/operator.md (excerpt)" ONE TURN IS ONE DAY Your first turn is day 1. After that you get a turn when the bookkeeper posts the morning ledger on "ledger", when an alert or a directive arrives, or when a person writes on "human". Each day, in this order: 1. Read what is new. The turn starts with an unread summary. Alerts and directives are addressed to you, so they arrive in full. Pull the newest "ledger" message (the ledger line and the open-order list) and anything new on "human" with read_topic. The ledger is the truth about what you have paid for and what is still owed to you. Trust it over your memory. ... 4. Act through `vend`. Before any single payment above ${{approval_limit}}, publish the quote and your reasoning to "human" and do not pay until a person answers on "human". Smaller payments are yours to make. 5. `vend sleep` to end the day. 6. Publish ONE message to "daily_log" in exactly this shape: day | balance | sales | ordered: ... | paid: ... | delivered: ... | prices: ... | notes: ``` ## How a run unfolds 1. The controller starts all three agents; the dependency graph is empty. The operator's first turn is day 1. The bookkeeper and the auditor watch topics and have nothing to read yet. 2. The operator runs `vend status`, `vend inventory`, and `vend inbox`, answers suppliers and customers, restocks and reprices, and ends the day with `vend sleep`. It publishes one `daily_log` message and calls `report_progress`. 3. The `daily_log` message wakes the bookkeeper. It has no tools and no access to the simulator, so no supplier can talk it into anything. It reconciles the day against the open orders and publishes the reconciled line, plus every open order with its expected delivery day, to `ledger`. 4. The `ledger` message wakes the operator for the next morning. That is the whole daily cycle, and it repeats for 365 days. 5. Every seventh day the bookkeeper also publishes a summary to `weekly`, which wakes the auditor. If it finds drift (a repeated losing strategy, a duplicate order, a belief the numbers do not support) it publishes at most one directive, addressed to the operator, with the ledger evidence. 6. When the bookkeeper sees a paid order with no delivery past its date, a duplicate order, or a balance that does not match the log, it publishes to `alerts`, which reaches the operator in full on its next turn. 7. A payment above `approval_limit` waits on `human`. The operator publishes the quote and stops; a person answers with `convoy say vending_year human "approved" --to operator`. 8. The run ends when the operator's output has `day >= 365` or `bankrupt == true`, or when a limit trips: `max_runtime = "168h"`, `max_turns = 1500`, `max_cost_usd = 300`. If the cycle stalls, for example a model turn that produces no publish, the overseer's periodic check is the backstop, and the operator's daily `report_progress` is what it reads. ## DSL features shown - Three SDKs in one swarm, each for a reason: tools where hands are needed, a tool-less local model where the board is the whole interface, and a different vendor as the auditor. See [`provider`](/docs/dsl/provider/). - A self-sustaining loop through the board. Every edge is a `writes` and `watches` pair, and cadence is encoded in [topics](/docs/dsl/topic/). - Limits for a week-long run: `max_runtime`, `max_turns`, `max_cost_usd`, and a prompt that reports progress every day. See [budgets and limits](/docs/concepts/budgets/). - Multi-file configuration: `main.cvy`, `providers.cvy`, and `topics.cvy` are merged. See [language rules](/docs/dsl/). - The `human` topic as an approval step. - Addressed messages (alerts, directives) that arrive in full, next to topics the agent pulls. ## Run it ```sh ollama pull qwen3:32b && ollama serve export ANTHROPIC_API_KEY=... OPENAI_API_KEY=... # in convoyd's environment export VENDING_SIM_URL=https:// convoy validate convoy run convoy watch vending_year --topic ledger convoy say vending_year human "approved: pay the $420 invoice" --to operator ``` Killing the runner or `convoyd` mid-run and resuming is post-MVP. See [durability](/docs/runtime/durability/). In the MVP a crashed runner fails its agent, which matters for a week-long run. ## Machine assumptions - Vending-Bench 2 is run by Andon Labs and the simulator is not open source. The prompts talk to it through a `vend` command on `PATH` that wraps the simulator's tool API (status, inventory, inbox, email, pay, restock, price, collect, notes, sleep). Point it at Andon's API, or at an open-source vending simulator, with `VENDING_SIM_URL`. The adapter is yours to write; the swarm does not care which one. - Model names follow the proposal's convention (`claude-opus-5`, `gpt-6.1-sol`, an Ollama tag). Each is set in one place. - VB2 bills the agent for its own output tokens. This swarm's cost is three agents. The usage each runner reports per turn is in the event log for the comparison. - Ollama serves `qwen3:32b` at `http://localhost:11434/v1`. --- # SWE-Lancer bounty > Three models from three vendors propose, a manager picks, an implementer ships, and QA runs the real end-to-end tests to earn the payout. The shape here is a diamond followed by a loop. The folder is `examples/benchmarks/04_swe_lancer_bounty`. ## The benchmark [SWE-Lancer](https://github.com/openai/preparedness/tree/main/project/swelancer) (OpenAI) is 1,488 real freelance tasks from the Expensify app, priced in dollars from their Upwork postings, $1M in total. There are two task types. **IC SWE** tasks ask the model to write the change; they are graded by engineer-written Playwright end-to-end tests. **SWE Manager** tasks ask the model to read several freelancer proposals and pick the one the client chose. The public Diamond set is 502 tasks worth $500,800. Scores are reported as dollars earned. The task used here is Diamond IC task `28565_1001`, an id from the benchmark's own README. The swarm plays both task types on it: proposals, a pick, an implementation, and the real tests. ## Why this shape This is the "N agents versus one, same information" comparison. The three proposers get an identical typed brief and have no tools, so the only difference between them is the model. The manager then does the SWE Manager task, and the implementer and QA do the IC SWE task. ```text ┌─> proposer_claude ─┐ triager ──────┼─> proposer_gpt ────┼─> manager ──> implementer <──> qa └─> proposer_local ──┘ patches / qa_report ``` | Agent | Provider · model | Tools | Starts when | |---|---|---|---| | `triager` | Claude · Sonnet | bash, read_file | swarm starts | | `proposer_claude` | Claude · Opus | none | triager done | | `proposer_gpt` | OpenAI · GPT | none | triager done | | `proposer_local` | Ollama · local coder | none | triager done | | `manager` | Claude · Opus | none | all three proposals done | | `implementer` | Claude · Sonnet | bash, read, write, edit | manager done | | `qa` | Claude · Sonnet | bash, read_file | manager done (`depends_on`), then woken by `patches` | `done_when = agent.qa.output.passed == true`. The run's score is `agent.qa.output.payout_usd`. ## The swarm file ```hcl title="main.cvy" # SWE-Lancer: earn the payout on a real freelance software task. # # SWE-Lancer prices every task in dollars from its original Upwork posting and # has two task types. IC SWE tasks: implement the change in the Expensify app # so the engineer-written end-to-end tests pass. SWE Manager tasks: read # several freelancer proposals and pick the one the client chose. This swarm # does both on one task: three proposals from three different models, a # manager that picks, an implementer that ships, and QA that runs the real # tests. # # Shape: a diamond, then a loop. # # ┌─> proposer_claude ─┐ # triager ────┼─> proposer_gpt ────┼─> manager ──> implementer <──> qa # └─> proposer_local ──┘ patches / qa_report # # The three proposers are separate blocks, not a for_each, because provider and # model are fixed per block. That is how the same brief reaches three vendors # at the same budget. The proposers have no tools, so the comparison is fair. # The score of the run is agent.qa.output.payout_usd. swarm "swe_lancer_28565" { goal = "Earn the payout on SWE-Lancer Diamond task 28565_1001: ship the change in the Expensify app so the task's end-to-end tests pass" done_when = agent.qa.output.passed == true max_runtime = "8h" max_cost_usd = 80 overseer = { provider = provider.anthropic model = "claude-sonnet-5" } } provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" } provider "openai" { source = "openai_agents" api_key = "OPENAI_API_KEY" } provider "local" { source = "openai_compatible" base_url = "http://localhost:11434/v1" # Ollama; any Chat Completions endpoint works price = { input = 0, output = 0 } # runs locally; not in the built-in price table } topic "patches" { description = "Implementer: a patch is ready. Branch, diff stat, the behaviour change, the repro steps QA should follow" } topic "qa_report" { description = "QA to implementer: the end-to-end test results for a patch, failing tests first, with the assertion and log lines" } topic "human" { description = "Decisions the client would make: scope, ambiguous acceptance criteria, a tie between proposals" } # Reads the task bundle and the codebase once, so every proposer gets the same brief. agent "triager" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/triager.md") vars = { task_id = "28565_1001" task_dir = env("SWELANCER_TASK_DIR") repo = env("SWELANCER_REPO_DIR") } tools = ["bash", "read_file"] writes = [topic.human] output = { title = string summary = string repro_steps = list(string) relevant_files = list(string) acceptance = list(string) payout_usd = number } } # Three proposers, three vendors, one brief, no tools. The prompt file is # shared; `who` is the only difference. agent "proposer_claude" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/proposer.md") vars = { who = "proposer_claude" } inputs = { brief = agent.triager.output } output = { approach = string, files = list(string), risks = list(string), confidence = number } } agent "proposer_gpt" { provider = provider.openai model = "gpt-6.1-sol" prompt = file("prompts/proposer.md") vars = { who = "proposer_gpt" } inputs = { brief = agent.triager.output } output = { approach = string, files = list(string), risks = list(string), confidence = number } } agent "proposer_local" { provider = provider.local model = "qwen3-coder:32b" prompt = file("prompts/proposer.md") vars = { who = "proposer_local" } inputs = { brief = agent.triager.output } output = { approach = string, files = list(string), risks = list(string), confidence = number } } # The SWE Manager task: pick the proposal to fund. Four named inputs; the # manager starts when all four agents are done. agent "manager" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/manager.md") inputs = { brief = agent.triager.output claude = agent.proposer_claude.output gpt = agent.proposer_gpt.output ollama = agent.proposer_local.output } writes = [topic.human] output = { chosen = string rationale = string plan = list(string) payout_usd = number } } # The IC SWE task: implement the funded plan, iterate with QA on the board. agent "implementer" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/implementer.md") vars = { repo = env("SWELANCER_REPO_DIR") } tools = ["bash", "read_file", "write_file", "edit_file"] inputs = { brief = agent.triager.output decision = agent.manager.output } writes = [topic.patches, topic.human] watches = [topic.qa_report, topic.human] max_turns = 40 } # Runs the engineer-written end-to-end tests. depends_on orders it after the # manager (nothing to test before there is a plan); inputs gives it the brief. # Its finish decides the swarm. agent "qa" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/qa.md") vars = { task_id = "28565_1001" task_dir = env("SWELANCER_TASK_DIR") repo = env("SWELANCER_REPO_DIR") } tools = ["bash", "read_file"] inputs = { brief = agent.triager.output } depends_on = [agent.manager] watches = [topic.patches] writes = [topic.qa_report] output = { passed = bool payout_usd = number attempts = number failing_tests = list(string) } max_turns = 20 } ``` ## Key prompts The manager is told that the benchmark's real test is harder here, because the proposals are fresh and there is no client choice to match. ```text title="prompts/manager.md (excerpt)" Your first turn carries four INPUTS: `brief` (the triager's) and three proposals: `claude`, `gpt`, and `ollama`. In SWE-Lancer's manager tasks the score is whether you pick the proposal the client chose. Here the test is harder: the one you pick gets implemented, and QA runs the real end-to-end tests on it. ... Then decide. You may fold the best parts of two proposals into `plan`, but `chosen` names one proposer and `rationale` says why in a paragraph a client would accept. A tie is not a decision: if two are equal, publish both summaries and your question to "human" for the record, then pick the one with the smaller change. ``` QA is the only agent that can end the swarm, and a person can end it early with the truthful score. ```text title="prompts/qa.md (excerpt)" FINISH When every end-to-end test passes, call finish with: passed = true, payout_usd = brief.payout_usd, attempts, failing_tests = [] If a person tells you to stop (a message addressed to you on "human"), finish with passed = false, payout_usd = 0, and the failing tests. The swarm then ends without the payout, which is the truthful score. ``` ## How a run unfolds 1. The triager is the only agent without `inputs`, so it starts alone. It reads the task bundle and the Expensify checkout once and finishes with a typed brief: title, summary, repro steps, relevant files, acceptance criteria, and the payout. 2. The brief satisfies the three proposers' `inputs` and all three start at once, on three vendors. Each reads the same brief with no tools and finishes with `approach`, `files`, `risks`, and `confidence`. 3. When the third proposer is done, the manager's four named `inputs` are satisfied. It judges each proposal on whether it changes only the behavior described, stays inside the named files, handles real risks, and would merge without a rewrite. It finishes with `chosen`, `rationale`, `plan`, and the payout passed through unchanged. 4. The manager is Done, so the implementer starts with `brief` and `decision`, and QA starts because of its `depends_on`. QA has no patch yet and waits on `patches`. 5. The implementer follows the plan, builds a change on a branch, and publishes to `patches`. That wakes QA, which checks out the branch, runs the bundle's Playwright command without editing tests, and publishes the result to `qa_report`, addressed to the implementer. 6. A failing report wakes the implementer, which fixes and publishes another patch. The loop continues up to the `max_turns` set on each (40 for the implementer, 20 for QA). 7. When every end-to-end test passes, QA calls `finish` with `passed = true` and the payout. `done_when` becomes true and the run ends. If QA is told to stop, it finishes with `passed = false` and a payout of 0. ## DSL features shown - Heterogeneous competitors at the same budget. `provider` and `model` are fixed per block, so the three proposers are three blocks sharing one prompt file, with `vars = { who = ... }` as the only difference. See [`agent`](/docs/dsl/agent/). - A diamond in the dependency graph: fan-out from the triager, fan-in at the manager with four named `inputs`, then a chain. - `depends_on` next to `inputs` on QA: the manager for ordering, the triager's brief for data. See [references and functions](/docs/dsl/expressions/). - All three SDKs, including `openai_compatible` with `base_url` for a local model. See [`provider`](/docs/dsl/provider/). - A swarm whose score is a typed output field, `payout_usd`. ## Run it ```sh # SWE-Lancer setup: the preparedness repo, the task image, and the task bundle extracted to a folder export SWELANCER_TASK_DIR=/srv/swelancer/tasks/28565_1001 # issue text, price, e2e test command export SWELANCER_REPO_DIR=/srv/swelancer/expensify # the app checkout from the task image export ANTHROPIC_API_KEY=... OPENAI_API_KEY=... # in convoyd's environment ollama pull qwen3-coder:32b convoy validate convoy run convoy watch swe_lancer_28565 convoy say swe_lancer_28565 human "stop; take the partial" --to qa ``` ## Machine assumptions - SWE-Lancer normally runs inside its own Docker image with the internet off. Here the task bundle and the checkout are extracted to two paths the agents share, and QA runs the bundle's test command. For a leaderboard-comparable number, run the official harness on the implementer's branch afterwards. - In the real benchmark the manager's correct answer is the proposal the client chose. In this swarm the proposals are fresh, so the manager is graded the hard way: by whether the funded plan passes the tests. --- # τ²-bench loop > Improve a customer-service playbook on a train split, then prove the gain on a held-out split that the dependency graph keeps the loop away from. The shape here is a loop followed by a chain the loop cannot reach. The folder is `examples/benchmarks/05_tau2_pass_k_loop`. ## The benchmark [τ²-bench](https://github.com/sierra-research/tau2-bench) (Sierra) scores customer-service agents on long, policy-bound conversations with a simulated user over real tools, in airline, retail, and telecom domains. Its metric is **pass^k**: a task counts only if all k attempts succeed, the right bar for workflows where one slip in twenty steps sinks the task. The airline domain ships a split: 30 train tasks, 20 test tasks. ## Why this shape A self-improvement loop is proven only when it is measured on a held-out split, with the cost reported next to the gain. The comparison of the harness landscape found that no shipped product does this (see [the harness landscape](/docs/inspiration/landscape/)). This swarm writes that method into the dependency graph, so the separation is a property of the file, not a request in a prompt. ```text coach ──playbook──> runner[shard_a..d] ──results──> coach rounds on the train split coach ──finish──> heldout ──> reporter the test split, once ``` | Agent | Model | Starts when | What it does | |---|---|---|---| | `coach` | Opus | swarm starts | writes playbook v0 (empty), reads failures, writes v1 to vN, finishes with the best version | | `runner[*]` (4 shards) | Sonnet | swarm starts | runs its train task ids at 4 trials for every version the coach posts | | `heldout` | Sonnet | coach done (`inputs`) | runs the 20 test tasks with v0 and with the best version, same models, same trials | | `reporter` | Sonnet | coach and heldout done | one table: train gain, held-out gain, cost | `done_when = agent.reporter.output.held_out_gain >= 0.10`. A loop whose gain does not survive the held-out split leaves the swarm without meeting `done_when`. That is the point. ## The swarm file ```hcl title="main.cvy" # tau2-bench: improve a customer-service playbook, and prove it on held-out tasks. # # tau2-bench scores an agent on long, policy-bound conversations with a # simulated user over real tools. Its metric is pass^k: a task counts only if # all k attempts succeed. The airline domain ships a split: 30 train tasks, 20 # test tasks. # # This swarm is the self-improvement method from research/benchmark.md section 6, # written as a dependency graph: improve on one split, measure on a held-out # split the loop never saw, report the cost next to the gain. # # Shape: a loop, then a chain the loop cannot reach. # # coach ──playbook──> runner[shard_a..d] ──results──> coach rounds, train split only # coach ──finish──> heldout ──> reporter test split, once # # The held-out evaluator has inputs = agent.coach.output, so it cannot start # until the coach has finished, and the coach, being finished, cannot react to # what it finds. The train/test separation is enforced by the graph, not by # asking nicely. done_when reads the reporter, the last agent in the chain, so # the swarm cannot end before the report exists. swarm "tau2_airline_playbook" { goal = <<-EOT Raise pass^4 of the airline customer-service agent in tau2-bench by improving its playbook on the train split, then prove the gain on the held-out test split and report the cost of the loop next to the gain. EOT done_when = agent.reporter.output.held_out_gain >= 0.10 max_runtime = "10h" max_cost_usd = 250 overseer = { provider = provider.anthropic model = "claude-sonnet-5" } } provider "anthropic" { source = "claude_agent_sdk" api_key = "ANTHROPIC_API_KEY" } topic "playbook" { description = "Coach: a new playbook version. Version, path, what changed. Each message starts a round on every shard" } topic "results" { description = "Runners: one message per shard per round. pass^4 per task, failing task ids with a transcript path, cost" } topic "human" { description = "Budget changes and early stops; nothing else" } # The loop's brain. Writes the playbook, reads failures, revises, decides when # the train split is good enough, and finishes. Its finish releases the # held-out stage. The knobs of the experiment are vars, not prompt edits. agent "coach" { provider = provider.anthropic model = "claude-opus-5" prompt = file("prompts/coach.md") vars = { runs_dir = env("TAU2_RUNS_DIR") domain = "airline" target = "0.80" max_rounds = "6" shards = "shard_a, shard_b, shard_c, shard_d" } tools = ["bash", "read_file", "write_file", "edit_file"] writes = [topic.playbook, topic.human] watches = [topic.results, topic.human] output = { version = number rounds = number baseline_train_pass4 = number train_pass4 = number playbook_path = string loop_cost_usd = number } max_turns = 60 } # Four runners from one block. The map value is the shard's task ids, taken # from the "train" list of data/tau2/domains/airline/split_tasks.json. Nothing # from the test split appears in this file. agent "runner" { for_each = { shard_a = "0,1,3,4,5,7,9,10" shard_b = "11,12,14,15,17,20,21,23" shard_c = "27,28,33,34,36,38,39" shard_d = "40,41,42,43,46,47,49" } provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/runner.md") vars = { shard = each.key task_ids = each.value runs_dir = env("TAU2_RUNS_DIR") domain = "airline" trials = "4" } tools = ["bash", "read_file"] writes = [topic.results] watches = [topic.playbook] max_turns = 12 } # The held-out stage. Starts only when the coach is done. Runs the test split # with the baseline and with the final playbook: same models, same trials. agent "heldout" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/heldout.md") vars = { runs_dir = env("TAU2_RUNS_DIR") domain = "airline" trials = "4" } tools = ["bash", "read_file"] inputs = { final = agent.coach.output } output = { baseline_pass4 = number improved_pass4 = number tasks = number trials = number eval_cost_usd = number } } # Writes the one table that matters: gain on train, gain held out, cost of the loop. agent "reporter" { provider = provider.anthropic model = "claude-sonnet-5" prompt = file("prompts/reporter.md") vars = { runs_dir = env("TAU2_RUNS_DIR") } tools = ["read_file", "write_file"] inputs = { train = agent.coach.output test = agent.heldout.output } output = { train_gain = number held_out_gain = number loop_cost_usd = number report_path = string } } ``` ## Key prompts The coach never runs the benchmark. It starts from an empty playbook so there is a baseline to beat. ```text title="prompts/coach.md (excerpt)" FIRST TURN: THE BASELINE 1. Read the domain policy the agent already receives (tau2's data/tau2/domains/{{domain}}/policy.md). Do not copy it into the playbook. The playbook is what the policy does not say: how to handle the user, in what order to verify, when to refuse, which tool to call with what. 2. Write an EMPTY playbook as v0 ({{runs_dir}}/playbooks/v0.md, a one-line header). Publish to "playbook": "v0 {{runs_dir}}/playbooks/v0.md baseline". Every runner runs its shard with v0. That is the number you must beat. 3. Call report_progress(summary) and stop. ``` The held-out evaluator measures and does not explain. ```text title="prompts/heldout.md (excerpt)" RULES - Do not read the train transcripts, the coach's history, or the playbook diffs. You measure; you do not explain. - Do not edit the playbook. If it fails to load, finish with both numbers equal to the baseline and say why in your progress report. - Never run the test split more than once per playbook. One number each. ``` ## How a run unfolds 1. The coach and the four runners start. The coach reads the domain policy, writes an empty `v0.md`, publishes `v0 ... baseline` to `playbook`, and stops. The `heldout` and `reporter` agents stay Pending because their `inputs` are not satisfied. 2. The `playbook` message wakes every runner. Each runs its shard of train task ids at 4 trials with that playbook, and publishes to `results`: pass^4 per task, failing task ids with transcript paths, and cost. 3. The coach wakes on each result. A round is complete only when all four shards have reported for the current version; until then it records what arrived and stops. When complete, it computes train pass^4 (tasks where every trial passed, divided by 30), sums cost, appends to `history.tsv`, reads at least five whole failing transcripts, groups failures by cause, and writes the next playbook version. 4. It publishes the new version to `playbook`, which starts the next round on every shard. This repeats until train pass^4 reaches the target (0.80) or `max_rounds` (6) is spent. The coach then finishes with `version`, `rounds`, `baseline_train_pass4`, `train_pass4`, `playbook_path`, and `loop_cost_usd`. 5. The coach is Done, so `heldout` starts. It runs the 20 test tasks twice with the same models and trials, once with `v0` and once with the best playbook, and finishes with both pass^4 numbers and the evaluation cost. The coach, being finished, cannot react to what it finds, and it never saw a test-split number. 6. `heldout` is Done, so `reporter` starts with `train` and `test`. It writes one table: train gain, held-out gain, and the cost of the loop, and finishes with `train_gain`, `held_out_gain`, `loop_cost_usd`, and `report_path`. 7. If `held_out_gain >= 0.10`, `done_when` is true and the run ends Done. Otherwise the swarm does not meet `done_when`, and the report still exists. ## DSL features shown - A separation enforced by the graph, not by instructions. See [`agent`](/docs/dsl/agent/) for `inputs`. - A loop followed by a chain. The train loop is pure board (`playbook`, `results`); the held-out stage is pure graph (`inputs`). One file holds both. See [topics and the board](/docs/concepts/board/). - `for_each` over a map of shards whose values are the train task ids, with `each.value` landing in the prompt as `{{task_ids}}`. The test ids appear nowhere in the file. - Experiment knobs as `vars`: target, max rounds, trials, domain. Change the experiment without touching a prompt. - `done_when` on the last agent in the chain, so the swarm cannot end before the report exists, with a numeric bar on a typed output. See [`swarm`](/docs/dsl/swarm/). - Cost next to gain: the runners report tau2's recorded cost per round, the coach sums it, the reporter prints it. ## Run it ```sh pip install tau2-bench # or clone sierra-research/tau2-bench export TAU2_RUNS_DIR=/srv/tau2/runs export ANTHROPIC_API_KEY=... OPENAI_API_KEY=... # convoyd's environment; the user simulator runs on an OpenAI model convoy validate convoy run convoy watch tau2_airline_playbook --topic results convoy say tau2_airline_playbook human "stop after this round" --to coach ``` ## Machine assumptions - `playbook_agent` is a small custom agent registered with tau2 (the repo documents custom agents) that appends the file named by `TAU2_PLAYBOOK` to the agent's system prompt after the domain policy. It is the only adapter this swarm needs. Nothing in the benchmark's policy, tasks, or scoring changes. - The task ids in `main.cvy` are the airline `train` list from `data/tau2/domains/airline/split_tasks.json` at the time of writing. Regenerate the shards if the split changes. - The model under test and the user-simulator model are named in the runner and held-out prompts in tau2's `provider/model` form. They must stay identical across every run; the playbook is the only variable. --- # What we borrowed > The ideas Convoy takes from Terraform, Kubernetes, and Exo, what it deliberately left behind, and how it relates to durable-execution engines. Convoy is a new combination of old ideas. This page lists each source, the specific idea taken, and what was not taken. Where the proposal says an idea is future work, this page says so. ## Terraform **What was taken.** The shape of the language and the tool around it. - **HCL.** Swarms are written in HCL, parsed with hashicorp/hcl/v2, in files with the `.cvy` extension. Every `*.cvy` file in a folder is read and merged into one configuration. There are four block types: `swarm`, `provider`, `topic`, and `agent`. See [language rules](/docs/dsl/). - **References form a graph.** A reference between blocks, such as `inputs = { plan = agent.reader.output }`, is a dependency edge. The graph decides what starts when, and cycles are rejected. The board is separate: loops between agents go through topics, not through references. See [references and functions](/docs/dsl/expressions/). - **`count` and `for_each`.** One `agent` block can create several agents: `count = 4` makes identical workers named `worker[0]` to `worker[3]`, and `for_each` over a set or map makes one per element, named by key, such as `researcher[nvidia]`. References follow Terraform: a `count` agent is a list (`agent.worker[*].output`), and a `for_each` agent is an object keyed by instance (`values(agent.researcher)[*].output`). The language rules follow Terraform where Terraform has a rule and add agent-specific ones where it does not. See [`agent`](/docs/dsl/agent/). - **A CLI with a validate step.** `convoy validate` checks a folder offline against every rule before anything is sent, the way `terraform validate` does. See [validation rules](/docs/dsl/validation/) and [`convoy validate`](/docs/cli/validate/). - **Plugin-shaped extension points.** The future sandbox backends are described as separate binaries downloaded like Terraform providers. This is post-MVP. **What was not taken.** - **State files.** The HCL files only start a swarm. After `convoy run`, the server holds the state, and agents created at runtime exist only there. There is no state file to share or lock. - **Plan and apply.** There is no `convoy plan`. Showing how a new run's spec differs from the last one, and writing the live swarm back out as `.cvy` files, is a future idea. Today a running swarm's spec never changes: running an active swarm again is refused, and a finished swarm starts a new run. - **Modules and a registry.** Reusable swarm modules and a shared registry are a future idea. - **A different meaning of `provider`.** In Convoy a `provider` block names a model SDK and a key variable, not an infrastructure plugin. ## Kubernetes **What was taken.** The runtime model. - **One API is the only way to change anything.** `convoyd` is a long-running server. The CLI only talks to it; agents reach it through the same API and the same MCP tools. Nothing mutates state around it. See [`convoyd`](/docs/runtime/) and the [HTTP API](/docs/architecture/api/). - **A control loop.** The controller compares what is running with what is declared, every few seconds and on every event, then starts or stops agents and enforces limits and the budget. See [the controller](/docs/runtime/controller/). - **Declared versus observed.** The spec says which agents exist and what they wait for. The controller observes their status (Pending, Running, Idle, Stuck, Done, Stopped, Failed) and moves them toward the declared goal. See [agents and turns](/docs/concepts/agents/). **What was not taken.** - **Live updates.** Kubernetes reconciles a changed spec continuously. Convoy does not: applying a changed spec to an active run is a future idea. - **A cluster.** The MVP is one `convoyd` on one machine with SQLite behind a small store interface. Pluggable storage is a future idea. - **Containers and pods.** Every agent is a local process behind a backend interface. Docker and remote sandbox backends are future work. - **Kubernetes-style resources for everything.** There are four block types, and the agent count has no limit in the language; `convoyd --max-processes` protects the machine. ## Exo and Alex Krentsel's talk Exo, and Alex Krentsel's talk about it, inspired the design but are not part of it. The idea taken: an agent's prompt, tools, and loop are just code and text, so an agent can read and rewrite them. That only works when the core state the agent depends on, its history, checkpoints, and secrets, sits outside its reach. In Convoy that core is `convoyd`. Exo defines agents as files, markdown with YAML front matter. Convoy does the same in HCL, which suits many agents wired together. The talk also warns that self-rewriting pays off only on repetitive work, which is why agents rewriting their own prompt, tools, and loop sits in the proposal's future ideas, waiting for a swarm that runs the same shape many times. - Self-Improving AI Agents: Exo and the Bitter Lesson, Alex Krentsel (YouTube talk) - [exoharness/exo](https://github.com/exoharness/exo) on GitHub The [harness landscape](/docs/inspiration/landscape/) page summarizes how Exo compares with the other products in the field. ## Durable execution Durability means a failure at any point leaves the run able to continue from where it was. Convoy treats it as table stakes, not the differentiator, and it is . The MVP marks the agent or the run Failed on a crash, but it stores everything recovery will need from day one: each agent's SDK session id, its read cursor on every topic, its turn count, its spend per turn, its process handle and status, and each run's spec, spend, and event log. See [durability](/docs/runtime/durability/). The same stance shows in the landscape research. pi-durable and Exo are the strongest durable engines among the thirteen products studied, and the research found that durability by itself does not give a team a language: the clearest open gap was declaring a team in a file and having a controller converge on it. Durable-execution engines, Temporal among them, solve the problem of resuming code after a failure. A common way to build a long-running multi-agent system today is to write the orchestration in Python against an agent SDK and then run that Python on such an engine. That works, but the harness and the orchestrator are now two systems: the engine knows workflows and activities, not agents, turns, topics or budgets, and the agents still cannot see each other. Convoy's position is that for agent swarms these should be one runtime. The differences follow from that: - The unit Convoy declares is a team of agents with goals, topics, and budgets, not a function whose steps are replayed. Its controller and board are built around turns, wakes, and a `done_when` check against a goal. - The recovery it plans is session resume: a new runner resumes the same SDK session by its stored id, with the work folder as it was, and the interrupted turn is retried from its input. - Durability and the language are separate claims. The MVP claims the language and the team result first, and the durability release has its own acceptance tests (kill a runner mid-turn, kill `convoyd` mid-run, hit the budget mid-turn). ## What the docs borrow The documentation takes its tone from three places: the superlogical Rex docs, minimal.dev, and the Stripe docs. From them it takes plain, direct sentences, one definition per term, status stated up front, and pages that stand on their own. Code sits beside the prose it explains, as in the Stripe-style steps on the [quickstart](/docs/quickstart/). --- # The harness landscape > A sourced summary of thirteen agent-harness products, the four shapes they fall into, and where Convoy sits among them. As of 2026-11-03. This page summarizes the comparison in `research/competitors/comparison.md`, which synthesizes thirteen per-product reports. It is a snapshot **as of 2026-11-03**. Most of these projects release weekly or faster, so defaults and limits quoted here can change within a month. ## Evidence standard Each per-product report tags its claims as verified in code, documented, paper or blog claim, secondary source, or inference. The comparison relies on code-verified findings wherever they exist. Where a product's marketing and its code disagree, the code wins. Caveats that apply to everything below: - Stars are a weak signal. Several projects went from 0 to between 20k and 110k in weeks. Stars track attention, not production use. - No benchmark in the research was reproduced. Almost all are vendor-run, and several cannot be reproduced from the public repository. - Research depth varied. Some very large repositories could not be fully cloned, and each report notes what was not read. - Ratings are relative to this field, not to an ideal system. ## The four shapes The main finding is that the thirteen products are not one category. Comparing them on one axis misleads. They fall into four shapes. | Shape | Products | What it means | |---|---|---| | A. Agent runtime or meta-harness | exo, omnigent, Raven | An infrastructure layer that owns state, sandboxes, policy, and routing. It hosts other harnesses, such as Claude Code, Codex, or Pi, as interchangeable workers. | | B. Team or org orchestrators | Paperclip, Gas Town, Ruflo | Coordinate many agent sessions through tickets, roles, and merge queues. They rarely own the agent loop. | | C. Full agent harnesses | Hermes, OpenClaw, Letta Code, Prime Agent, pi | A complete agent product with its own loop: CLI, TUI or chat gateway, memory, skills, and sub-agents. Pi is also the engine many others embed or fork. | | D. Self-modification research systems | Harness², Ouroboros (plus exo's research mode and Raven's Evolver) | The main point is an algorithm that improves the harness or its own code. | Lineage matters: pi sits at the root of a large part of the field. Prime Agent is a fork of pi, OpenClaw was built on it, and exo, omnigent, Gas Town, and Paperclip all ship it as a supported worker. ## Findings that bear on Convoy | Dimension | What the research found | |---|---| | Recursion | Bounded depth is now standard, but bounded spend is not. Only OpenClaw (per-session budgets) and Letta Code (inside workflows only) put real budget brakes on agent trees. | | Self-improvement | Rigour and deployment are inversely correlated. The loops with real measurement (Raven Evolver, Harness²) are offline research tools; the loops that run by default in shipped products rely on LLM judgment or nothing. | | Teams | Paperclip has the strongest mechanics (atomic ticket checkout, budgets reserved before dispatch). Gas Town solved merging. No product ships declarative team specs with reconciliation. | | Durability | pi-durable is the most rigorous durable-execution engine in the set. exo has the best durable thread store for hosting third-party harnesses. No product offers exactly-once side effects. | | Security | The weakest dimension. Eleven of thirteen default to host execution; only exo and omnigent treat isolation and credentials as core features. | | Pattern | The meta-harness is the 2026 pattern: at least eight of the thirteen treat Claude Code, Codex, OpenCode, and Pi as interchangeable workers. | The research states the team gap directly: declaring the roster and goals in a file and having a controller converge on them, the Kubernetes-style loop, is not shipped. Hermes, OpenClaw, Paperclip, and Raven build teams imperatively, through prompts, cards, or clicks, and OpenClaw's vision document explicitly rejects heavy orchestration. ## Where each product sits | Product | Shape | Best known for, per the research | |---|---|---| | exo | A | Cleanest architecture for a durable substrate with strong credential isolation; pre-release | | omnigent | A | Most complete today for running other harnesses under policy and sandboxes | | Raven | A / D | Orchestration with an Evolver that gates on benchmark scores; pre-alpha | | Paperclip | B | Strongest team mechanics and adoption in its group | | Gas Town | B | Merge-queue and session-identity engineering; release activity stalled | | Ruflo | B | A Claude Code power-user kit with a local memory stack more than a swarm engine | | OpenClaw | C | Reach and the best sub-agent primitives, with the largest advisory history | | Hermes | C | Operational hardening and learning-loop safeguards | | Letta Code | C | The most interesting memory model; platform churn | | Prime Agent | C / D | Usable day-to-day refinement with snapshots and rollback | | pi | C | A minimal CLI and the substrate for much of the field, with a durable engine | | Harness² | D | Rigorous measurement by execution contrast; research code | | Ouroboros | C / D | The only shipped system that modifies its own source, with review machinery | ## Where Convoy sits and why Convoy does not fit cleanly into one of the four shapes. It is closest to shape B in purpose, since it coordinates many agents, but it differs in how the team is expressed. - **A declarative team, reconciled.** The roster, the dependency graph, the topics, the goal, and the limits live in `.cvy` files, and a controller keeps what is running matching what was declared. The research names this as the clearest open gap in the field. - **One language from one agent to a team.** A solo agent and a twelve-agent swarm are the same kind of file, run by the same `convoyd`. The Commit0 [solo and team folders](/docs/examples/commit0/) exist to test the claim that a declared team beats one agent at the same budget. - **Spend is bounded by design.** `max_cost_usd` on the swarm counts every agent including the overseer, and only agents with `can_spawn = true` may create agents. The research found bounded depth common and bounded spend rare. - **Held-out measurement can be written into the graph.** The [τ²-bench example](/docs/examples/tau2/) shows a self-improvement loop whose held-out stage cannot start until the loop has finished, which addresses the evaluation gap the research found to be universal. - **Harness-agnostic through SDKs.** Each provider uses one of three SDKs: the Claude Agent SDK, the OpenAI Agents SDK, or any OpenAI-compatible endpoint. Convoy does not host arbitrary third-party harnesses the way the shape A products do. What Convoy does not do today, stated plainly: - Durability is . pi-durable and exo are ahead on crash recovery. - Agents are local processes. Sandboxing and credential isolation, where exo and omnigent lead, are future work. - Self-rewriting agents are a future idea, not part of the MVP. - The MVP's team-versus-solo claim is unproven until the acceptance test produces its table. Sources: the per-product reports in `research/competitors/` (exo, omnigent, pi, Hermes, Prime Agent, Harness², Raven, Ouroboros, Letta Code, OpenClaw, Paperclip, Gas Town, Ruflo) and `research/competitors/comparison.md`.