Runtime / MVP

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.

View .md

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 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.

Agent states
live · counts against budget terminal gates met wake news 20m silent progress wake finish stop · limit crash Pending Running Idle Stuck Done Stopped Failed
Select a stateClick a state to see every transition out of it, or play a typical lifetime.
Fig. 1 Agent states and what moves an agent between them.

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.

StateMeaning
pendingWaiting for inputs and depends_on to be done, or for a free process slot
runningIn a turn
idleBetween turns, waiting in wake
stuckA running agent that has not reported progress for too long. Not terminal
donefinish was accepted
stoppedStopped by a person, the overseer, a parent, a limit or the run ending
failedThe 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 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.

FromConditionToActions
pendingfirst passrunningset started_at; emit run.started; publish swarm started to system, addressed to overseer
runningmax_cost_usd set and run cost_usd >= max_cost_usdstoppedend_reason = budget; stop every non-terminal agent; emit run.ended
runningnow - started_at >= max_runtimestoppedend_reason = max_runtime; cascade; emit run.ended
runningdone_when evaluates truedoneend_reason = done; cascade; emit run.ended
runningdone_when returns a diagnosticrunningemit done_when.error, once per distinct message
runningevery agent terminal, done_when not truefailedend_reason = failed; emit run.ended with detail all agents ended without meeting done_when
runninga 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 agentsfailedend_reason = failed; detail no agent can make progress: ...
runningthe provider refused an agent’s key, or its account has no creditfailedend_reason = failed; detail agent X: and the provider’s words
runningPOST :stopstoppedend_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

FromConditionToActions
pendinggates satisfied and a process slot is freerunningstart 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).
  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

FromConditionToActions
running, stuckrunner calls wakeidleturns += 1; last_turn_at = now; price and record usage; record session ids; emit agent.turn_ended
idlewake returns newsrunninglast_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

FromConditionToActions
running, stuckreport_progress(summary)runningstore the summary; last_progress_at = now; emit agent.progress (and agent.unstuck when leaving stuck)

Limits

FromConditionToActions
running, idle, stuckturns >= max_turnsstoppedend_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

FromConditionToActions
runningnow - max(started_at, last_turn_at, last_progress_at) >= stuck_afterstuckemit 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

FromConditionToActions
running, idle, stuckprocess exited, status already donedonenone; agent.finished already exists
sameexited, a stop was requestedstoppedfinish the stop sequence
sameexited with code 4stoppedend_reason = max_turns
sameexited 0, not done, no stop requestedfailedend_reason = runner_error, detail exited 0 without finish (a runner bug, logged)
sameexited 1 or by signalfailedend_reason = runner_error, detail with the code or signal
sameexited 2failedend_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: <end_reason> 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

FromConditionToActions
running, stuckPOST :finish accepteddonestore 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.

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:

WhenMessage
Run startedswarm started; N agents pending
Every --overseer-interval (5 min) while runningtick: elapsed 00:41 of 4h; spend $3.12 of $20.00; running 2, idle 4, stuck 0, done 1, pending 0
agent.stuckagent X stuck: no progress for 20m; last progress: ...
agent.failedagent X failed: <end_reason>
agent.finishedagent X finished, plus the first 500 characters of the output
agent.blockedagent X cannot start: dependency Y is <status>

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.

Timing parameters

FlagDefaultUsed by
--tick5sPass interval
--stuck-after20mStuck rule
--stop-grace5sStop sequence step 4
--kill-grace3sSIGTERM to SIGKILL
--overseer-interval5mHeartbeat to system
--wake-timeout30sBoard Wake
--max-processes50Admission

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.

Last updated 2026-11-05
esc
    ↑↓ to move · ↵ to open
    Menu
    Get started
    IntroductionInstallQuickstartYour first swarm
    Concepts
    Swarms and runsAgents and turnsTopics and the boardThe overseerSpawning agentsBudgets and limits
    DSL
    Language rulesswarmprovidertopicagentReferences and functionsValidation rules
    Providers
    Provider typesUsing a provider typeWriting a provider type
    CLI
    Overviewconvoy goalconvoy validateconvoy runconvoy statusconvoy watchconvoy sayconvoy stopconvoy uiconvoy provider
    Runtime
    convoydControllerMessage boardRunnerSwarm tools (MCP)Web UIDurability
    Architecture
    OverviewRepository layoutSeams and contractsHTTP API
    Examples
    OverviewWriter and criticResearch teamCode teamPaperBench replicationCommit0 libraryVending-BenchSWE-Lancer bountyτ²-bench loop
    Inspiration
    What we borrowedThe harness landscape