Skip to content

Subagents: Splitting Tasks to Run in Parallel, but Only When You Ask

📚 Series Navigation: The previous article [20 Connecting External Tools via MCP] taught you how to connect external tools to Codex, allowing it to search documentation and connect services. This article shifts perspective—instead of "adding tools," it teaches you how to split tasks to run in parallel: Subagents, a group of dedicated assistants with independent models, instructions, and permissions, running concurrently and returning consolidated findings back to you.

Everyone, today let's discuss one of the most powerful—and most easily misused—features in Codex: subagents.

The name sounds advanced: "multi-agent parallel execution," making it feel like you are commanding a small squad. When I first discovered this feature, I got carried away, wishing to split every task into five or six agents running concurrently, thinking that was the "professional way to play."

But to be honest: Codex's subagents are slightly different from what you might have seen elsewhere. There is a counter-intuitive setting you must know first—they do not split tasks automatically by default. The official docs state clearly: Codex spawns subagents only when you explicitly ask it to do so. If you don't say "spawn several agents in parallel," it works sequentially as a single agent to the end. This rule decides how you use it and when you should use it.

This article covers not only how to spawn subagents, how to write custom agents, and how to select different models for different agents, but more importantly, helps you identify the line: which tasks are worth splitting to run in parallel, and which ones are just wasting tokens and adding trouble when split.

By reading this article, you will get:

  • What subagents actually are—splitting tasks to multiple specialized agents to run in parallel and consolidate results, and how it differs from a single agent working in isolation
  • The two issues it solves: context pollution (context pollution) and context rot (context rot), and the counter-intuitive line: when not to split
  • Codex's three built-in agents (default / worker / explorer), ready to use out-of-the-box
  • How to write custom agents: placing a TOML file under ~/.codex/agents/ or .codex/agents/, and what the three required fields do
  • How to select different models and reasoning efforts for different agents, giving scouts faster models and reviewers more powerful models
  • A hands-on exercise: writing a read-only scout agent, spawning it, and verifying it returns summaries without exceeding permissions

⚠️ Any specific commands, configuration keys, and default values mentioned below are subject to the official Codex documentation. Model names (like gpt-5.5) that change with versions are subject to what is actually displayed on your local system, and will not be hardcoded here.


01 Understand First: What Exactly Are Subagents?

The bottom line: Subagents are specialized agents spawned temporarily by Codex—they work in independent threads, and instead of throwing all intermediate logs and findings back to your main chat, Codex consolidates them into a single final report.

Analogy: Splitting a complex case among multiple detectives. You are the detective chief (the main chat session) with a complex case: "review this change from security, performance, and testing perspectives." These three angles do not interfere with each other, and you don't need to run three separate checks yourself. Instead, you deploy three detectives: one focusing on security vulnerabilities, one on performance, and one on test gaps. All three head out at the same time and work separately. When they finish, they don't dump hundreds of pages of files back on your desk; instead, they each submit a summary: "there are two risks in security, at X and Y." What you get in the end is a categorized summary.

These detectives have things that are "their own," isolated from your main thread. The official docs define the terms clearly:

Subagent: An agent spawned by Codex to handle a specific delegated task. Agent thread: A CLI thread of an agent, which you can view and switch between using /agent.

Breaking it down, a subagent can have several independent dimensions:

DimensionMain Agent (Your Dialogue)Subagent (The One Dispatched)
Thread / ContextRequirements, decisions, and history discussed between you and CodexAn independent agent thread of its own, focusing only on the specific task assigned to it, with details kept in its own thread
Model / Reasoning EffortThe settings used by your main sessionCan be specified separately, e.g., scouts use faster models, reviewers use stronger models (see Section 05)
Instructions (Persona)Default Codex behaviorsCustom developer_instructions you write for it, e.g., "you are only responsible for scouting, do not modify code"
Sandbox PermissionsThe sandbox policy of your active sessionInherited from your session by default, but overrideable per-agent, e.g., forcing read-only

The most critical point, which is the soul of Codex subagents: their value is "moving noisy intermediate outputs out of the main thread." The official text states: let the main agent focus on requirements, decisions, and final deliverables, while delegating noisy tasks like scouting, running tests, and parsing logs to subagents to run in parallel, with subagents returning only summaries and not raw logs.

This determines what subagents are good at and what they are not, which we will use to make decisions in the next section.

Subagent Concept

This diagram illustrates how subagents work: the main agent splits a larger task and delegates it to multiple subagents to run in parallel. Each subagent stays in its own independent context (scouting, testing, and reading docs do not pollute each other), and returns only a summary back to the main agent—keeping the main chat clean.

💡 Summary in one sentence: Subagents are specialized agents with independent threads, models, and permissions, running in parallel and returning summaries back to the main thread; their core value is moving noisy intermediate outputs out of your main dialogue.


02 What It Resolves—and the Counter-Intuitive Boundary

Now that we know what they are, let's understand why we need them. The official docs list two issues they solve. Master these two terms, and you'll understand half of this feature.

Issue 1: Context Pollution (context pollution)

Analogy: A pile of takeout receipts mixed in with serious office files. Your main chat holds important things—requirements, constraints, and decisions. If you ask the agent to "run the entire test suite," it dumps hundreds of lines of test logs on your desk. The useful findings, like "which tests failed," are buried under pages of useless logs, forcing you to scroll to search. This is context pollution: noise drowning out the signal.

The official definition:

Context pollution (context pollution): Useful information is buried by noisy intermediate outputs.

Real scenario: Last year when debugging a third-party API, I asked Codex to try calling it repeatedly, generating pages of JSON responses. By the twelfth turn, I wanted to confirm "whether field A is required in the initial prompt," and scrolled up—only to find walls of JSON, scrolling back twenty pages before finding the instruction. At that moment, I realized: tasks generating heavy intermediate logs should never run in the main thread.

Issue 2: Context Rot (context rot)

Analogy: A meeting running too long, causing people to lose focus. For the first hour, everyone stays on topic. By the third hour, the table is cluttered with side topics and temporary details, and decision quality drops. The same applies to models—as conversations grow longer and more cluttered, model performance degrades as irrelevant details accumulate.

The official definition:

Context rot (context rot): Performance degrades as the dialogue is filled with increasingly irrelevant details.

The cure for both issues is the same: moving noisy tasks out of the main thread, delegating them to subagents to run in parallel, and letting them return only summarized takeaways. The docs share an extreme example: a document of millions of tokens can be split into chunks and delegated to multiple subagents, with each returning only synthesized bullet points back to the main thread. The main thread remains clean.

The Counter-Intuitive Boundary: Tasks You Should Not Split

Since we understand the issues, let's return to the warning: why is "splitting tasks right from the start" a mistake?

Because subagents are not free. The official docs highlight a cost: each subagent runs its own model and calls its own tools, so subagent workflows consume more tokens than equivalent single-agent runs. The more you split, the more you spend. There is also a second cost—parallel writing is far more dangerous than parallel reading:

At startup, use parallel agents for read-oriented tasks, like scouting, running tests, routing, and summarizing. Use parallel write workflows with caution, as multiple agents writing code simultaneously can conflict and increase coordination costs.

I have summarized the trade-offs into a table:

Task CategoryShould you split to subagents?Why
Scouting / running tests / parsing logs / summarizing (read-oriented, heavy logs)✅ Yes, worth splittingMoves noise out of the main thread; this is its primary domain
Multiple independent research tasks (auth / database / API investigations)✅ Yes, worth running in parallelRuns concurrently, converting sequential wait times to parallel execution
Simple modifications easily explained in one sentence❌ NoSpawning subagents consumes extra tokens and overhead, making it inefficient
Multiple agents writing to the same code block simultaneously⚠️ Use with cautionHigh risk of conflicts and coordinate overhead
Steps with sequential dependencies (A must finish before B starts)⚠️ No benefitParallel execution requires independent tasks

Real scenario: I once insisted on spawning an agent to handle a simple task like "renaming this function clearly," just to look professional. It ended up adding friction—spawning, running models, and returning results took longer than simply asking Codex in the main thread, and consumed more tokens. Since then, I have established a rule: never split tasks that can be described in a single sentence and modified immediately.

💡 Summary in one sentence: Subagents solve "context pollution + context rot" by moving noisy, read-oriented tasks out of the main thread to run in parallel; but avoid splitting simple edits, sequential steps, or parallel writes—splitting more doesn't make it better, and over-splitting is slow, expensive, and error-prone.

The diagram below maps the decision-making process:

Subagent Flow

This diagram shows the process: first decide "should we split?" If not, keep it in the main thread; if yes and you ask for it, Codex spawns parallel agents, waits for all results, and returns a consolidated report—note the "you ask for it" step, as Codex will not split automatically.


03 Built-in Agents: Ready Out-of-the-Box

You don't need to write configurations to use subagents. Codex provides three built-in agents ready out-of-the-box.

The three built-in agents are:

Built-in AgentRoleSuitable For
defaultGeneral-purpose fallback agentDefault choice when no specific role is requested
workerExecution-focused: implementation and fixesCode writing, bug fixing, and hands-on tasks
explorerRead-only investigation: codebase explorationCode browsing, tracing execution paths, and investigation

Having agents is one thing; directing them to start is another. Remember the key rule: Codex does not split automatically, you must explicitly ask for parallel execution in your prompt. The official documentation states:

Codex does not automatically spawn subagents; it uses them only when you explicitly request subagents or parallel agent runs.

So spawning them does not require special syntax, just describing the task clearly—detailing how to split, whether to wait for all inputs, and what summaries to return. The docs suggest prompts like "spawn two agents," "delegate this work in parallel," or "use one agent per point." A well-written subagent prompt should cover three aspects: division of labor, whether to wait for all agents to finish before proceeding, and the format of the final summary.

For example, you can write in Codex:

text
Use parallel subagents to review this branch (current vs. main). Spawn one agent to check security risks, one to check test gaps, and one to check maintainability. Wait for all three to finish, and return a consolidated summary of findings with file paths.

Analogy: A director calling for multiple cameras to roll. If you don't call it, the scene is shot sequentially; if you say "roll cameras on these three scenes simultaneously, and send me the footage," the crew splits up. The command "roll simultaneously + send me the files" is your spawning instruction—the cameras (agents) are ready, waiting for your signal.

Once triggered, Codex handles the orchestration—spawning new agents, forwarding instructions, waiting for results, and closing finished threads; when multiple agents run, it waits for all requested results before returning a consolidated response.

Real scenario: The first time I used this feature to review a PR, I followed the prompt style "spawn one agent per point" and sent six review points at once. I expected to wait a long time, but the parallel runs returned results faster than asking sequentially, giving me a clean consolidated report. That was when I realized the benefit of parallel execution—it saves the wait times of sequential requests.

⚠️ A platform difference in visibility: subagent activities are visible in the Codex App and CLI, while IDE extension visibility is marked as "coming soon" in the official docs. Use the App or CLI to monitor active agents.

💡 Summary in one sentence: Three built-in agents (default / worker / explorer) are ready to use; but Codex never splits automatically, requiring you to explicitly write "spawn parallel agents, wait for all, and return a summary" to trigger them.


04 Managing Running Agents: Switching with /agent or Directing via Chat

When multiple agents run in parallel, you must be able to check their progress or change your mind. Codex provides two methods.

Method 1: Switching and Viewing with /agent

The official command is /agent (note it is singular, not /agents). Use it in the CLI to switch between active agent threads and check what a thread is doing.

text
/agent

Note that this differs from other tools—it is not a command to "run an agent," but to "view / switch threads." Spawning is done via chat prompts, while checking is done via /agent.

Method 2: Directing via Chat

It is often easier to direct them using plain language. The official docs state: you can tell Codex to control a running subagent, pause it, or close a completed agent thread. Just use plain commands like "stop that running scout agent."

Analogy: A dispatcher using a two-way radio. Multiple vehicles are out on tasks. You can switch channels to listen to a specific vehicle's report (/agent), or use the radio to broadcast "Vehicle 3, abort investigation and return" (directing via chat). The vehicles run their tasks, but you keep final control.

There is also an approval behavior to watch out for, as warned by the official docs: in the interactive CLI, approval prompts may pop up from background agent threads you are not currently viewing. If a background agent hits an operation requiring approval, the prompt will display indicating which thread sent it—you can press o to jump into that thread's context and review the action before deciding to approve, deny, or respond. In non-interactive workflows (like running scripts), operations requiring approvals will fail, throwing the error back to the parent workflow.

💡 Summary in one sentence: Manage running agents in two ways—/agent (singular) to switch threads and check progress, or direct chat commands to stop, manipulate, or close an agent. In the interactive CLI, press o to jump into a background thread prompting for approvals.


05 Custom Agents: Writing TOML Files and Customizing Models

The three built-in agents handle many tasks, but if you find yourself repeating the same instructions—like "review this code like an owner, focusing on correctness and safety"—you should save it as a custom agent that can be spawned with a simple command next time.

How to write: Save a TOML file under the agents directory, where one file defines one agent. The two locations defined officially are:

LocationWho can use itSuitable For
~/.codex/agents/All your projectsGeneral-purpose personal agents you want to use anywhere
.codex/agents/Current project onlyProject-specific agents that can be committed to Git for the team

Analogy: Creating a dedicated profile for a detective. The three built-in agents are general staff available at any time. Your TOML file defines a profile for a detective with a specific expertise—defining their name, focus, rules, and equipment (model). Once defined, you can call them by name.

A custom agent file looks like this, with only three required fields:

toml
name = "reviewer"
description = "PR reviewer focused on correctness, security, and missing tests."
developer_instructions = """
Review code like an owner.
Prioritize correctness, security, behavior regressions, and missing test coverage.
"""

The fields are detailed below:

FieldRequiredRoleKey Point
nameYesThe name Codex uses to spawn and refer to the agentThis is the identifier; keep the filename matching the name, but name determines the identity
descriptionYesUser-facing description: when to use this agentKeep it clear so you and your team recognize its role
developer_instructionsYesCore instructions defining the agent's behaviorThe agent's "persona + rules of engagement"
nickname_candidatesNoA list of nicknames used in the UIWhen spawning multiple instances of the same agent, the UI uses these to differentiate them

Other optional fields inherit from the parent session if unset: model, model_reasoning_effort, sandbox_mode, mcp_servers, and skills.config. The docs note that custom agent files are loaded as configuration layers, so you can write other config keys supported by config.toml. Additionally, a priority rule: if your custom agent shares a name with a built-in agent (e.g., explorer), your custom file overrides the built-in one.

Customizing Models and Reasoning Efforts for Agents

This is the best part of custom agents—giving each agent the most suitable brain. Two knobs:

  • model: Which model to use. The official design pattern is "use faster models for scouting, and stronger models for reviewing"—use faster, cheaper models for scanning files, summarizing, or running workers (the docs mention gpt-5.4-mini); use stronger models for review or tracing complex multi-step logic (the docs list gpt-5.4 / gpt-5.5 tiers, where gpt-5.5 is the starting point for demanding agents, and the reviewer example uses gpt-5.4). Specific model names change with versions; refer to official docs, and keep the "fast for scouting, powerful for review" pattern in mind.
  • model_reasoning_effort: Reasoning effort, three levels.
Reasoning EffortUsed ForCost
highTracing complex logic, checking assumptions, and edge cases (reviewers / security agents)Slowest and consumes most tokens, but highest quality for complex tasks
mediumBalanced default for most agentsMedium
lowStraightforward tasks focusing on speedFastest

Write them in the file to assign a fast model with low reasoning to the scout, and a powerful model with high reasoning to the reviewer:

Note on model name: the official scout example uses gpt-5.3-codex-spark (research preview for Pro users); we use gpt-5.4-mini here, which Pro users can change back.

toml
# .codex/agents/explorer.toml —— Read-only Scout: Fast, cheap, no writing
name = "pr_explorer"
description = "Read-only codebase explorer for gathering evidence before changes."
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Stay in exploration mode.
Trace the real execution path, cite files and symbols, and avoid proposing fixes unless asked.
"""

Note the line sandbox_mode = "read-only"this restricts permissions for a single agent. Subagents inherit your session's sandbox settings by default, but you can explicitly restrict this scout to read-only in its agent file, preventing it from modifying files even if it wants to.

⚠️ A permissions priority pitfall: temporary runtime settings modified in your session (like /permissions or --yolo) will apply to spawned subagents—even if the agent file defines different defaults. Your active session overrides the static settings in the agent file.

There is also a global [agents] configuration governing the main switches for all subagents, written in your config.toml (not individual agent files):

Global KeyRoleDefault Value
agents.max_threadsMaximum concurrent active agent threadsDefaults to 6 if unset
agents.max_depthAgent nesting depth limit (root session is 0)Defaults to 1: allows direct subagents, blocks deeper nesting
agents.job_max_runtime_secondsDefault timeout for workers in CSV batch jobsFalls back to 1800 seconds if unset

The docs share a practical tip for max_depth: keep it at the default of 1 unless you genuinely need recursive delegation. Increasing it can trigger deep fan-out cascades, causing token usage, latency, and local resource consumption to surge. max_threads limits concurrent threads, but cannot protect against the costs and unpredictability of deep recursion.

💡 Summary in one sentence: A custom agent is a TOML file placed under ~/.codex/agents/ or .codex/agents/, requiring name, description, and developer_instructions; optional fields inherit from the parent session if unset, and you can use model + model_reasoning_effort to assign fast models to scouts and powerful models to reviewers, or restrict permissions with sandbox_mode.


06 Hands-on: Write a Read-only Scout Agent and Run It

Practice makes perfect. Below, we write a minimal custom agent and run it, verifying the flow of "scouting a file, returning summaries, and respecting read-only restrictions." It does not depend on complex environments.

We will create a simple read-only codebase scout that reads files, reports structure and issues, but does not modify files (locked via sandbox_mode = "read-only").

Step 1: Create a directory and agent path (macOS / Linux)

bash
mkdir sub-demo
cd sub-demo
mkdir -p .codex/agents

Expected: The sub-demo directory contains the .codex/agents/ path. Verify with ls .codex.

Windows users running PowerShell: mkdir sub-demo; cd sub-demo; mkdir .codex\agents -Force. Replace terminal commands like echo and cat with PowerShell equivalents.

Step 2: Write the custom agent file

Using your preferred editor, create sub-demo/.codex/agents/scout.toml and write:

toml
name = "scout"
description = "Read-only codebase scout that inspects files, reporting structure and issues without edits."
sandbox_mode = "read-only"
model_reasoning_effort = "low"
developer_instructions = """
You are a read-only codebase scout. Your job is to search and report, not modify code.
When assigned a task:
1. Read the file specified by the user.
2. List issues grouped by readability, naming, and potential bugs.
3. Suggest improvements for each, but do not modify any files.
Return only a clean summary, and do not copy blocks of code back to the main thread.
"""

Note we left out the model field—so it inherits the model from the parent session. sandbox_mode = "read-only" locks its write permissions, preventing it from modifying files, and model_reasoning_effort = "low" speeds up this light task.

Step 3: Create a file with areas for improvement for it to scout

bash
echo 'def f(a, b):
    return a / b' > calc.py

The function name f and parameters a / b are unclear, and it lacks division-by-zero checks—perfect for the scout to identify.

Expected: sub-demo contains calc.py with the two lines of code.

Step 4: Start Codex and tell it to use this agent

bash
codex

In the session, remember the rule: you must explicitly tell it to use the subagent:

text
Use the scout subagent to inspect calc.py, and return a summary of issues according to its instructions. Do not modify the file.

Expected: Codex spawns the scout subagent (visible as an active agent thread in the App or CLI, possibly with a nickname). It reads calc.py inside its read-only thread and returns only the scout summary back to the main thread—identifying the unclear function/parameter names and the missing division-by-zero check, suggesting naming and check improvements. Verify it only suggests changes and does not edit the file (enforced by read-only). Switch threads using /agent to monitor its progress if you wish.

Step 5: Verify the file was not modified

Exit Codex and check the file in your terminal:

bash
cat calc.py

(PowerShell users run type calc.py)

Expected: calc.py remains unchanged, retaining the original two lines—demonstrating the lock on permissions: because it is read-only, it can only suggest and cannot modify.

Running these steps verifies the flow: writing a TOML agent → spawning it via chat prompt → subagent working in an isolated thread → returning summaries without violating permission scopes. Custom agents follow this process with different instructions, models, and permissions.

⚠️ If Codex does not spawn the scout and instead reads the file itself, you did not make the request to use the subagent clear enough—refer to Section 03 and use explicit phrases like "spawn the scout subagent to inspect."

💡 Summary in one sentence: Write a read-only scout TOML, request "spawn the scout subagent to inspect" calc.py, and run cat to confirm the file remains untouched—verifying this isolated task execution and permission lock is key to understanding subagents.


07 Advanced: Batch Processing with CSV (Experimental)

⚠️ This feature is marked experimental and subject to change as subagent support evolves—this section briefly introduces it so you know it exists, but do not rely on it as a stable capability.

If you have a large batch of similar tasks—like checking files, PRs, or migration targets one-by-one—Codex offers spawn_agents_on_csv: it reads a CSV file, spawns a worker subagent for each row, and once the batch finishes, exports the consolidated results to a new CSV.

Analogy: Assembly line sorting. A bin of packages (rows in a CSV) is processed by a row of sorters (workers) labeling them concurrently, and once finished, is consolidated into a master list. Each worker must call report_agent_job_result exactly once to report its outcome, otherwise that row is marked as an error in the exported CSV. See the official documentation for specific parameters and usage.

Evaluating suitable scenarios:

ScenarioSuitable for spawn_agents_on_csv?Why
Reviewing dozens of PRs with identical structures✅ YesIdentical tasks on a batch of similar objects, yielding high parallel efficiency
Translating comments in dozens of files to English✅ YesRows are independent and have no sequential dependencies, ideal for CSV batching
Tasks with sequential dependencies (A must finish before B)❌ NoRows are processed concurrently, with no order guaranteed
Only three or four objects with small changes❌ NoSetting up batch jobs introduces more overhead than direct commands, making it inefficient
Concurrently writing to the same set of files⚠️ Use with cautionHigh risk of write conflicts between workers, as in Section 02

💡 Summary in one sentence: spawn_agents_on_csv (experimental) is suited for "running the same task repeatedly on a large batch of similar, independent objects" in read-only or isolated-write scenarios; avoid it for sequential steps, small batches, or concurrent writes to the same files.


08 Summary

We have explored Codex subagents—covering when to split tasks, how to spawn them, how to write custom agents, and how to verify them—establishing the boundary between parallel and sequential tasks and noting that they are only spawned when explicitly requested.

Let's review the key points:

ObjectiveAnswerKey Takeaway
What are subagents?Specialized agents with independent threads, models, and permissionsRun tasks in parallel and return summaries back to the main thread
What do they solve?Context pollution + context rotMove noisy, read-oriented logs out of the main chat
When not to splitSimple edits, sequential dependencies, parallel writesOver-splitting increases costs, delays, and conflicts
How to spawnYou must explicitly request it; Codex does not split automaticallySpecify division of labor, whether to wait, and summary formats
Built-in vs CustomThree built-in agents ready; custom agents defined in TOMLRequire name, description, and developer_instructions
Customize modelsmodel + model_reasoning_effortAssign fast models to scouts and powerful models to reviewers

You should now be able to: decide whether a task is suitable for subagents; use the three built-in agents or write custom agents under ~/.codex/agents/ with custom instructions, models, and permissions; and remember that subagents are only spawned when you ask, returning summarized conclusions to the main thread. This judgment is the key to using subagents effectively—learning the syntax takes minutes, but mastering the boundaries takes practice.

Remember: Codex subagents are powerful, but they do not make decisions for you—you control when and how to split them.


The next article [22 Agent Skills]—your ecosystem of Codex configurations is coming together: AGENTS.md defines rules, slash commands save shortcuts, MCP connects external tools, and subagents run parallel tasks. But have you noticed that writing "rules of engagement" for subagents still requires long blocks of developer_instructions? What if you could bundle these behaviors into a reusable skill called upon as needed? The next article covers how to package capabilities into Skills.