20. Many Agents, One Tree

A Codex agent can start other agents. Each child is an ordinary thread with a path such as /root/worker, a configuration derived from its parent’s live turn, and a mailbox. spawn_agent returns the child’s path at once; the child’s answer arrives later as a message, never as a return value, so parent and child run concurrently and talk like actors.

Some tasks split well: one agent reads the test suite while another reads the parser. Codex supports this inside one session. The model calls a tool, the harness starts a new thread for the child (see Chapter 4), and the threads exchange messages through mailboxes.

This chapter starts with the tools the model sees, follows one spawn through thread_spawn.rs, the child’s configuration, roles, and AgentControl, and then traces how messages and the final answer travel back. It ends with limits, the persisted agent graph, and the shared message board.

The picture

The parent model calls spawn_agent in the collaboration namespace; the V2 handler builds a ThreadSpawnRequest; thread_spawn prepares the child config from the live turn and sends a SpawnRequest to AgentControl, which writes an Open spawn edge to the state database, starts the child thread with a NEW_TASK message, and returns; the handler gives the model the path /root/worker at once; later the child’s finished turn reaches AgentControl, which posts a FINAL_ANSWER into the parent’s mailbox, and the parent reads it on its next sampling request.

Read the figure top to bottom in two halves. The first half happens inside one tool call: the handler hands the request to thread_spawn, which builds the child’s configuration, and AgentControl records the parent-child edge, starts the child, and returns. The model gets back only a path, /root/worker. In the second half, time has passed. The child finishes a turn, and the controller drops a FINAL_ANSWER message into the parent’s mailbox. The parent reads it on a later sampling request (see Chapter 5), or a wait_agent call wakes it.

Three versions and one namespace

Multi-agent support exists in three versions, chosen per turn as a MultiAgentVersion. Version 1 (V1) is the older tool set, Version 2 (V2) is the current runtime, and Version 3 (V3) shares V2’s runtime with a different tool list. Config::multi_agent_version_for_model picks V2 when multi_agent_v2 is on (V3 if the model catalog asks). Otherwise [agents] enabled = false disables the tools, a model catalog choice wins if present, and the deprecated multi_agent feature (Collab) selects V1.

The versions expose different tools, listed by required_child_management_tool_names and the spawn handlers in codex-rs/core/src/tools/spec_plan.rs.

Version Namespace Tools
V1 multi_agent_v1 spawn_agent, send_input, resume_agent, wait_agent, close_agent
V2 collaboration (default) spawn_agent, send_message, followup_task, wait_agent, interrupt_agent, list_agents
V3 collaboration (default) spawn_agent, send_message, stop_agent, list_agents, wait_agent

V2 tools sit in one Responses API namespace. multi_agent_v2_handler in codex-rs/core/src/tools/multi_agent_tool.rs wraps each spec in a ToolSpec::Namespace described by MULTI_AGENT_V2_NAMESPACE_DESCRIPTION, “Tools for spawning and managing sub-agents.” The constant is public so host extensions, such as the message board, can join the namespace. Its name comes from tool_namespace, default collaboration, so the model calls collaboration.spawn_agent.

The spawn tool the model sees

create_spawn_agent_tool_v2 in codex-rs/core/src/tools/handlers/multi_agents_spec.rs builds the schema. With the defaults (no user-defined roles, model overrides exposed, no service tier), the parameters are:

{
  "type": "object",
  "additionalProperties": false,
  "required": ["task_name", "message"],
  "properties": {
    "fork_turns": {"type": "string", "description": "Parent history to inherit. Defaults to `all`; use `none` to start without parent history. Only `all` and `none` are supported."},
    "message": {"type": "string", "description": "Initial plain-text task for the new agent.", "encrypted": true},
    "model": {"type": "string", "description": "Model override for the new agent. Omit unless an explicit override is needed."},
    "reasoning_effort": {"type": "string", "description": "Reasoning effort override for the new agent. Omit to inherit the parent effort."},
    "task_name": {"type": "string", "description": "Task name for the new agent. Use lowercase letters, digits, and underscores."}
  }
}

The description tells the model how paths work: “If your current task is /root/task1 and you spawn_agent with task_name”task_3” the agent will have canonical task name /root/task1/task_3.” It also promises that “its final answer will be provided to you when it finishes.” The "encrypted": true marker on message is, in the tools crate’s words, a “Responses-only marker for reviewed encrypted tool parameters”. Codex forwards such model-supplied content unwrapped as AgentMessage::Encrypted; a message from code mode or a host call is AgentMessage::Plaintext.

Two parameters are conditional. agent_type appears only when the user has defined roles, with a description that lists “Available roles:”. service_tier is added only when expose_spawn_agent_service_tier is on. The output schema is {task_name} while hide_spawn_agent_metadata keeps its default of true, and {task_name, nickname} otherwise.

One spawn, step by step

The handler

The V2 handler in codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs parses SpawnAgentArgs with deny_unknown_fields, so an unexpected argument fails the call. It turns fork_turns into a fork mode. Note that the parser is more lenient than the schema text:

if self.fork_context.is_some() {
    return Err(FunctionCallError::RespondToModel(
        "fork_context is not supported in MultiAgentV2; use fork_turns instead".to_string(),
    ));
}
// ...
if fork_turns.eq_ignore_ascii_case("none") {
    return Ok(None);
}
// Accept legacy turn counts without limiting the inherited history.
if fork_turns.eq_ignore_ascii_case("all") || fork_turns.parse::<NonZeroUsize>().is_ok() {
    return Ok(Some(SpawnAgentForkMode::FullHistory));
}

SpawnAgentForkMode has one variant, FullHistory; a fresh child is None. A legacy count such as "3" still copies the full history. The handler then calls thread_spawn::spawn.

thread_spawn.rs

codex-rs/core/src/thread_spawn.rs is shared by the native tool and by hosts that spawn children themselves. spawn rejects an empty message and calls prepare, which builds the child config with prepare_agent_spawn_config and computes the child’s path by joining task_name onto the parent’s path, or onto /root. AgentPath::join refuses root, ., .., slashes, and anything outside lowercase letters, digits, and underscores. The child’s source becomes SessionSource::SubAgent(ThreadSpawn { .. }) with the parent’s ID and a depth one greater.

spawn then sends a SpawnRequest to session.services.agent_control.spawn. The initial input is always AgentInput::Message with MessageDeliveryMode::TriggerTurn, so the child starts working at once.

The child’s configuration

prepare_agent_spawn_config in codex-rs/core/src/agent/child_config.rs starts from the parent turn’s effective config and refreshes the model, provider, reasoning effort, summary, and developer instructions from the live turn. It then applies, in order, the requested model overrides (falling back to [agents] default_subagent_model and default_subagent_reasoning_effort), the role, and any requested or shared service tier; the parent’s inherited tier is copied before the role. Last, it calls apply_spawn_agent_runtime_overrides:

fn apply_spawn_agent_runtime_overrides(
    config: &mut Config,
    turn: &TurnContext,
) -> Result<(), String> {
    config
        .permissions
        .approval_policy
        .set(turn.approval_policy())
        .map_err(|err| format!("approval_policy is invalid: {err}"))?;
    config.approvals_reviewer = turn.config.approvals_reviewer;
    #[allow(deprecated)]
    let turn_cwd = turn.cwd.clone();
    config.cwd = turn_cwd;
    config
        .permissions
        .set_permission_profile_from_session_snapshot(
            turn.config.permissions.permission_profile_state().snapshot(),
        )
        .map_err(|err| format!("permission_profile is invalid: {err}"))?;
    Ok(())
}

Because this runs after the role, the child always takes the parent turn’s approval policy, approvals reviewer, working directory, and permission profile, which is its sandbox (see Chapters 13 and 14). The doc comment names the risk: a stale copy “can make a child agent disagree with its parent about approval policy, cwd, or sandboxing.” This is capability narrowing: a child can have less authority than its parent, never more.

Roles can only switch features off

A role is a named config layer. Users declare roles as [agents.<name>] tables with description, config_file, and nickname_candidates, or as *.toml files that load_agent_roles in the agent-roles crate finds recursively under <config folder>/agents. A role file holds those fields plus ordinary config keys; unknown fields are rejected. Codex also has built-in roles: default, explorer, and worker. An awaiter role sits in a comment that reads “Awaiter is temp removed”.

apply_role_to_config_inner in codex-rs/core/src/agent/role.rs filters what a role may change. It copies developer instructions, model, reasoning effort and summary, verbosity, personality, and service tier. For features it keeps only entries set to false, and only for five features: ShellTool, Apps, Plugins, MemoryTool, and RequestPermissionsTool. For skills it keeps only disables. The module comment states the rule: roles “may customize the child or reduce its capabilities, but never replace the parent session’s authority.” An omitted role resolves to DEFAULT_ROLE_NAME, "default", so a user-defined [agents.default] with a config file applies to every fresh V2 child.

Forks change the rule slightly. A V2 full-history fork without agent_type skips the role and keeps the parent’s settings; with agent_type, the role applies, and if it sets no developer instructions the child keeps the turn’s. V1 refuses the combination outright: “Full-history forked agents inherit the parent agent type; omit agent_type, or spawn without a full-history fork.”

AgentControl starts the child

AgentControl in codex-rs/core/src/agent/api.rs is a backend-neutral trait for one agent tree. Its main operations are spawn, send, take_mailbox, watch_mailbox, interrupt, list, admit_turn, record_usage, and turn_finished. The local backend is LocalAgentControl. A host can take over turn admission instead by selecting AgentRuntimeOwnership::Host at startup.

LocalAgentControl::spawn_agent_internal in agent/control/spawn.rs runs these steps:

  1. Join the tree’s membership and resolve the child’s multi-agent version.
  2. Check capacity, and for a V2 child reserve a residency slot (see Limits).
  3. Reserve the path in the registry; a reused name fails with “agent path /root/worker already exists”. Pick a nickname from the role’s nickname_candidates or a 101-name list.
  4. For a fork, copy the parent’s history (below).
  5. Write the spawn edge as Open to the agent graph store, before the child thread exists.
  6. Create the child thread and deliver its first message as a NEW_TASK.
  7. Commit the reservation and announce the new thread to subscribed clients.

For a full-history fork, a V2 child with preserve_fork_prefix on (the default) keeps every parent response item, so its prompt prefix matches the parent’s and can reuse the prompt cache. Otherwise keep_forked_rollout_item keeps system, developer, and user messages and the assistant’s partial and final answers, and drops reasoning, tool calls, tool outputs, and agent messages.

Messages, status, and the final answer

Delivery modes

Every agent message carries a MessageDeliveryMode. into_communication in agent/control/delivery.rs turns it into an InterAgentCommunication with a trigger_turn flag. The table compares the three modes.

Mode trigger_turn Rendered type Used by
QueueOnly false MESSAGE V2 send_message
WakeWorker true, except to the root MESSAGE V3 send_message
TriggerTurn true NEW_TASK spawn’s first message, followup_task

A plaintext message renders as four labeled lines, Message Type, Task name, Sender, and Payload. Mail with trigger_turn = true starts a turn for an idle recipient or joins the active one. Mail with trigger_turn = false waits in the mailbox. It starts a turn only when wake_on_agent_messages is on or the recipient has an outstanding durable sleep. Otherwise the recipient picks it up when its active turn collects pending input before the next sampling request, or at its next turn. The AgentControl doc comment is precise about what success means: “Successful delivery means accepted, not read by the model.”

Agent status

AgentStatus has seven values: PendingInit, Running, Interrupted, Completed(Option<String>), Errored(String), Shutdown, and NotFound. agent_status_from_event in agent/status.rs derives it from events. TurnStarted gives Running. TurnComplete gives Completed with the last agent message, or Errored if the turn carried an error. An abort for Interrupted or BudgetLimited gives Interrupted, and ShutdownComplete gives Shutdown. is_final treats every status except PendingInit, Running, and Interrupted as final, so an interrupted child can still take more work.

How the final answer travels

For a V2 child, the result travels through AgentControl::turn_finished. When a child turn ends with a final status, its session builds an AgentTurnOutcome and calls turn_finished, which runs notify_parent_of_terminal_turn in agent/control/completion.rs. That function formats the payload with format_inter_agent_completion_message and posts it to the parent with trigger_turn = false. The body is:

Message Type: FINAL_ANSWER
Task name: <parent path>
Sender: <child path>
Payload:
<the child's last agent message>

An errored child’s payload is “Agent errored:” plus the error, truncated to 900 tokens, and a hint to give the agent another task. A V3 child that completes sends nothing here; V3 workers report results with send_message. V1 works differently. A completion watcher waits for the child’s final status and injects a <subagent_notification> fragment with JSON {agent_path, status} into the parent without starting a turn.

A V2 child that receives a followup_task reports again when that turn ends. The parent can block on wait_agent, which takes only timeout_ms and returns {message, timed_out} with one of “Wait completed.”, “Wait interrupted by new input.”, or “Wait timed out.” It never returns the answer itself; the answer reaches the parent’s history as an agent message. Timeouts default to 30,000 ms; a request above the 3,600,000 ms maximum is rejected, and one below the 10,000 ms minimum is raised with a note.

A worked example

The scenario test child_completion_wakes_parent_after_final_answer in codex-rs/core/tests/suite/scenarios.rs records a full round trip with multi_agent_v2 and wake_on_agent_messages on. Its snapshot shows the parent’s model asking for a worker:

07:function_call/collaboration.spawn_agent:{"fork_turns":"none","message":"Check whether the release is ready.","task_name":"worker"}
08:function_call_output:{"task_name":"/root/worker"}

Line 08 is the immediate return: a path, no answer. The parent then said “I have delegated the release check.” and ended its turn. The worker’s history began with the inbound agent message; it called the test’s check_release tool and got “All release checks passed.” When its turn completed, the parent’s mailbox held:

{
  "author": "/root/worker",
  "recipient": "/root",
  "type": "agent_message",
  "content": [{"type": "input_text",
    "text": "Message Type: FINAL_ANSWER\nTask name: /root\nSender: /root/worker\nPayload:\nAll release checks passed."}]
}

With wake_on_agent_messages on, that mail started a new parent turn, and the snapshot shows it as the last input of the parent’s third request. Without the feature, the same mail would wait until the parent’s next turn or a wait_agent call.

Limits

V2 bounds children by one number, max_concurrent_threads_per_session, which counts the root. With the number of child agents allowed at once, effective_agent_max_threads and resolve_multi_agent_v2_config in codex-rs/core/src/config/mod.rs compute:

Here is the session’s thread budget including the root, is max_concurrent_threads_per_session under [features.multi_agent_v2], and is the same key under [agents] (legacy alias max_threads), which counts only spawned threads. With nothing configured, and .

In V2, caps two things, and neither is the total number of children ever spawned. ensure_execution_capacity refuses a spawn when child turns are already running. also caps child runtimes loaded in memory; when that limit is full, the spawn unloads an idle child after writing its rollout (the test residency_slot_reservation_unloads_oldest_idle_v2_agent covers this). Only when nothing can be unloaded does the spawn fail with “agent thread limit reached”.

V1 counts differently: up to spawned agents, default 6, may be open, and each counts until it is closed. V1 also limits depth: a spawn is allowed only when

where is the caller’s depth (the root is 0) and is agents.max_depth, default 1. So V1 children cannot spawn grandchildren; they get “Agent depth limit reached. Solve the task yourself.” V2 ignores depth; a non-root agent may spawn only when its model’s catalog entry supports the V2 runtime.

The agent graph and the message board

agent-graph-store

The agent-graph-store crate defines AgentGraphStore, a storage-neutral trait for “persisted thread-spawn parent/child topology”, and LocalAgentGraphStore implements it over the SQLite table thread_spawn_edges(parent_thread_id, child_thread_id PRIMARY KEY, status). Status is Open or Closed. Spawn writes the Open edge before creating the child; if the write fails, the spawn fails with “failed to persist spawned agent relationship”. Ephemeral sessions skip the write. V1’s close_agent sets the edge to Closed. On resume, restore_v2_agent_metadata walks Open descendants breadth-first, so a V2 tree’s paths and nicknames come back (see Chapter 24).

The message board

Mailboxes connect two agents; the agent message board, a shared store of channels and posts, connects many. The agent-message-board extension (see Chapter 19) adds its discussion tools to the V2 namespace: create_channel, get_channels, list_threads, search_posts, read_thread, read_post, subscribe, unsubscribe, and post. A post notifies subscribers through ordinary agent-message scheduling. Tool arguments are capped at 128 KiB and responses at 8,000 bytes.

install_agent_message_board in agent-message-board-host mounts a board only for a V2 thread with agent_message_board or agent_message_board_mcp on, or with an explicit host connection, and picks an MCP, connected, remote, in-memory, or local SQLite backend. In MCP mode the extension adds a required streamable-HTTP MCP server named codex_message_board (see Chapter 17).

Not part of the tree: runtime-agent-instance

The runtime-agent-instance crate has nothing to do with sub-agents. Its crate comment reads “Ephemeral OpenAI runtimes: composite registration and per-request assertions.” It registers at https://auth.openai.com/agent/register and attaches an x-openai-agent-assertion header to requests, so it belongs with sign-in (see Chapter 25).

Why this design

Each choice answers one need. Mail instead of a return value lets the parent keep working while children run, at the cost of text-only results and an explicit wait. Copying the live sandbox and approval policy after any role keeps every child, which runs tools on the same machine, within the parent’s authority. The persisted graph lets resume rebuild the tree.

Status at commit 081295be9d. multi_agent_v2 STABLE, off by default. multi_agent (Collab, V1) DEPRECATED, on by default. wake_on_agent_messages, agent_message_board, and agent_message_board_mcp UNDER DEVELOPMENT, off. V3 has no feature flag of its own; a model catalog entry selects it. IMPLEMENTED: the local AgentControl backend and the SQLite agent graph store.

What breaks

Symptom Cause Check
“agent thread limit reached” child turns running, or residency full with no idle child (V2); open agents (V1) max_concurrent_threads_per_session; close V1 agents
“Agent depth limit reached. Solve the task yourself.” V1 child at agents.max_depth [agents] max_depth
“fork_context is not supported in MultiAgentV2; use fork_turns instead” V1 argument sent to V2 multi_agent_v2 feature state
“agent path /root/worker already exists” task_name reused under the same parent Choose a new task_name
“unknown agent_type ‘x’” Role not defined [agents.x] or agents/*.toml
agent_type absent from the schema No user-defined roles config.agent_roles
Idle parent never reacts to a child’s answer FINAL_ANSWER is queue-only; wake_on_agent_messages off Call wait_agent, or send a new turn
“failed to persist spawned agent relationship” State database write failed State DB health (Chapter 24)

Code map

What it is Where it lives Identifier
Agent tree backend trait codex:codex-rs/core/src/agent/api.rs pub trait AgentControl
Spawn preparation codex:codex-rs/core/src/thread_spawn.rs pub(crate) async fn prepare
V2 spawn handler codex:codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs fn fork_mode
Spawn tool schema codex:codex-rs/core/src/tools/handlers/multi_agents_spec.rs pub fn create_spawn_agent_tool_v2
Child config codex:codex-rs/core/src/agent/child_config.rs fn apply_spawn_agent_runtime_overrides
Roles codex:codex-rs/core/src/agent/role.rs pub const DEFAULT_ROLE_NAME
Result delivery codex:codex-rs/core/src/agent/control/completion.rs notify_parent_of_terminal_turn
Spawn edge store codex:codex-rs/agent-graph-store/src/store.rs pub trait AgentGraphStore

Recall check

What does spawn_agent return, and when does the child’s answer arrive?
Only the path, such as {"task_name":"/root/worker"}, at once; the answer comes later as a FINAL_ANSWER mailbox message.

Can a role give a child a looser sandbox than its parent?
No; runtime overrides copy the live approval policy and permission profile after the role, and roles can only disable features.

With nothing configured, how many V2 children can run at once, and why?
Three: the default budget of 4 counts the root, and .

Why might an idle parent not react to a child’s final answer?
The answer is queue-only mail; it starts a turn only with wake_on_agent_messages or a durable sleep.

What does the thread_spawn_edges table make possible?
Resume can rebuild a V2 tree by walking Open edges breadth-first from the root.