Back to Blog

Codex Multi-Agent Setup: Cut Costs Without Guesswork

Tutorials and Guides5537
Codex Multi-Agent Setup: Cut Costs Without Guesswork

International access: https://4sapi.com
Domestic access: https://4sapi.org

Abstract

OpenAI’s October 2026 official documentation formalizes a tiered execution pattern for Codex coding agents: assign high‑stakes comprehension, architectural decision‑making and final judgement to the powerful GPT‑6.1‑Sol main‑thread agent, while delegating reconnaissance, file‑scanning, log parsing and well‑defined small‑scale modifications to lightweight GPT‑6‑Luna sub‑agents. This layered architecture concentrates high‑cost reasoning budget on critical decision points rather than routine investigative labour. Developers must understand one important caveat: delegating work to independent sub‑agents does not guarantee lower total token consumption, because each child agent runs separate inference cycles and tool calls. This article walks through practical, verifiable configuration steps, role definition, project‑level workflow rules, and audit‑ready prompting patterns. It also covers measurement methodologies to validate whether layering actually improves cost‑efficiency, alongside common configuration failures and corresponding mitigation strategies.

1. Core Concept: Main‑Thread Judgement and Limited‑Scope Sub‑Agent Work

The core principle of Codex tiered‑model operation is workload segmentation. Sub‑agents fit best for read‑heavy investigative jobs: source‑code searching, call‑chain tracing, log analysis and evidence summarization. Official documentation explicitly warns that each spawned sub‑agent triggers its own model inference and tool invocation sequence. Parallel sub‑agent fan‑out can raise overall token expenditure compared to a single monolithic agent. Therefore layered delegation delivers value only when tasks can be cleanly partitioned with clear boundaries of responsibility.

A recommended three‑role division avoids the anti‑pattern of blindly dispatching every possible task to lightweight sub‑agents.

  1. Main‑thread agent (GPT‑6.1‑Sol). Responsible for clarifying business requirements, determining overall architecture, resolving design trade‑offs, synthesizing evidence from sub‑agents and delivering final judgements. All ambiguous requirements, architectural trade‑offs and high‑risk design work must remain within the main thread.
  2. Scout sub‑agent (GPT‑6‑Luna). Read‑only investigative role: locating source files, tracing function call chains, parsing logs and aggregating factual evidence. It produces findings and file references but never alters source‑code files or proposes unvalidated modification schemes without explicit top‑level approval.
  3. Fixer sub‑agent (GPT‑6‑Luna). Executes only small, pre‑validated changes already approved by the main‑thread agent. It runs narrow, targeted validation tests after modification and returns change summaries without introducing architectural adjustments.

This separation prevents lightweight sub‑agents from making high‑impact design decisions they are not intended to handle. Reconnaissance and mechanical modification are delegated; judgement and trade‑off analysis stay with the flagship main‑thread model. Teams operating multi‑model agent workloads need consistent routing rules to manage different model endpoints efficiently.

2. Step One: Configure Main‑Thread and Sub‑Agent Defaults

Codex maintains two configuration scopes: user‑global configuration stored at ~/.codex/config.toml and project‑level configuration located at .codex/config.toml within individual code repositories. Project‑level configuration only loads when the repository is marked trusted, and takes higher priority than the global user‑level file. Always create a backup before modifying configuration files.

The minimal global user‑level configuration sets the primary main‑thread model and establishes default parameters for all newly‑spawned sub‑agents.

toml
# ~/.codex/config.toml
model = "gpt-6.1-sol"

[agents]
default_subagent_model = "gpt-6-luna"
default_subagent_reasoning_effort = "high"

According to OpenAI’s October 20‑2026 specification, gpt‑6.1‑sol targets complex multi‑step long‑duration workflows, and gpt‑6‑luna is optimised for well‑defined, repetitive, high‑frequency subtasks. Starting sub‑agents with high reasoning effort provides a safe baseline that developers can tune downwards based on real‑world output quality.

Developers should audit existing configuration entries referencing older model identifiers such as gpt‑5.5. Starting October 14 2026, Codex sessions authenticated via ChatGPT login ceased access to gpt‑5.5. API‑key‑based sessions remain unaffected by this deprecation notice. Actual model availability is subject to account permissions, client version and staged roll‑out status and cannot be assumed purely from configuration text.

3. Step Two: Create Two Specialised Custom Sub‑Agent Definitions

Default configuration values apply when no explicit agent specification is supplied. To stabilise behaviour across sessions, define dedicated custom agent profiles with fixed identity, description and hard‑coded developer instructions. Custom agent files require three mandatory fields: name, description, and developer_instructions. Model identifier and reasoning intensity can also be overridden independently per‑agent.

Create the scout agent file at ~/.codex/agents/scout.toml:

toml
name = "scout"
description = "Read‑only reconnaissance: locate files, trace code paths, read logs and aggregate factual evidence."
model = "gpt-6-luna"
model_reasoning_effort = "high"
developer_instructions = """
Perform investigative work only; do not edit or write any source‑code files.
Use targeted symbol search before reading files; avoid full repository scanning.
Return relevant file paths, key function signatures, observed issues and supporting evidence.
Do not paste full log dumps or complete source‑code excerpts.
Never propose unvalidated modification solutions unless explicitly instructed by the main‑thread agent.
"""

Create the fixer agent file at ~/.codex/agents/fixer.toml:

toml
name = "fixer"
description = "Apply small pre‑approved modifications and run targeted validation checks."
model = "gpt-6-luna"
model_reasoning_effort = "high"
developer_instructions = """
Only execute change schemes already confirmed by the main‑thread agent.
Make minimal necessary alterations. Do not re‑architect modules or touch unrelated source files.
Stop work and report back when encountering scenarios outside the pre‑approved plan.
After completing edits run only directly‑related validation tests.
Return modified file paths, concise change summaries and test‑execution outcomes.
"""

Important limitation: role‑based developer‑instructions are prompt‑level guidance and do not constitute a hardened security sandbox. Custom agent definitions cannot override sandbox settings, approval policies or MCP server configurations inherited from the parent Codex session. Strict permission isolation must be implemented at the session‑level configuration such as enabling read‑only workspace modes, rather than relying purely on natural‑language constraints inside agent prompts.

4. Step Three: Lock Delegation Rules Inside AGENTS.md

Without persistent ground rules, the main‑thread agent frequently reverts to handling every subtask internally. Store stable project‑specific delegation logic inside AGENTS.md at repository root. This document encodes durable workflow conventions, while ad‑hoc task‑specific details remain within individual prompts.

Sample content for AGENTS.md:

markdown
## Agent Division of Labour
- Main‑thread agent: interpret requirements, formulate solution plans, make architectural judgements and aggregate final results.
- File searching, code tracing, keyword lookup, log parsing and test‑result summarisation are delegated to the scout sub‑agent.
- Small, already‑approved code modifications are delegated to the fixer sub‑agent.
- Sub‑agents return conclusions, file references and evidence; avoid dumping raw verbose output.
- Multiple sub‑agents are forbidden from concurrently modifying the identical source file.
- Architecture decisions, ambiguous requirements and tasks requiring multi‑dimensional trade‑offs are always handled on the main‑thread agent.

This mechanism does not force automatic blind delegation. Instead it supplies consistent constraints that apply every time Codex considers spawning child agents.

5. Step Four: Use Audit‑Ready Prompt Templates to Orchestrate Complete Tasks

Prompts for layered workflows must clearly articulate objectives, execution sequence, boundary constraints and acceptance criteria. Below is a practical template demonstrating a bug‑fix workflow addressing a configuration‑page state‑loss defect after page refresh.

markdown
Task: Repair the bug where saved settings are lost after page refresh.

Execution sequence:
1. Instruct scout to locate settings‑page source files, save‑request interfaces, storage keys and associated test cases; limit output to maximum 20 lines of summarised findings.
2. Main‑thread agent analyses scout evidence to identify root‑cause, list target‑files for modification and write acceptance criteria.
3. Await human confirmation of the proposed solution before invoking fixer to apply minimal‑scope changes.
4. Instruct scout to execute targeted related test suites and summarise test outcomes.
5. Main‑thread agent produces final report summarising applied edits, test evidence and residual risk items.

Constraints:
Do not alter API schemas; avoid rewriting unrelated modules; do not commit or push changes to remote git branches.

Completion criteria:
User‑settings persist across page refresh, relevant unit‑tests pass, git diff only contains changes strictly related to this defect.

Independent read‑oriented subtasks may run in parallel. When file‑writing operations target overlapping resources, serial execution must be enforced to prevent edit conflicts. Official documentation lists parallel exploration, testing and evidence summarisation as appropriate use‑cases for sub‑agent fan‑out, while concurrent writes carry significant collision risk.

6. How To Verify Real‑World Efficiency Gains

Tiered‑model workflows do not automatically reduce token cost. Perform controlled baseline comparison using identical business tasks before and after enabling sub‑agent layering. Record four key metrics: main‑thread task completion time, quantity of spawned sub‑agents, length of final generated output and aggregate token consumption shown on Codex usage dashboard. Evaluating efficiency cannot rely solely on shorter individual response text because sub‑agents duplicate context loading and trigger extra tool‑call cycles.

Three categories of workload generally should not be delegated to sub‑agents:

  1. Simple questions resolvable within a single brief turn.
  2. Continuous modification sequences requiring persistent full‑context awareness maintained by the main‑thread agent.
  3. Workflows where multiple agents need concurrent write‑access to one single source file.

Use Codex built‑in /status command to inspect session runtime state and expand sub‑agent execution threads. Verify the actual model identifier employed by each child agent and inspect returned payload quality. The core success metric is whether the main‑thread agent is relieved of noisy investigative work and whether produced artefacts become easier for human auditing, rather than chasing fixed token‑reduction multipliers.

7. Common Failure Modes and Troubleshooting

7.1 Sub‑agents keep spawning with main‑thread model instead of Luna

Check TOML file structure: the [agents] table header must be correctly positioned, and default_subagent_model must sit inside this section. Restart Codex. Confirm that a nearer project‑level .codex/config.toml is not overriding global user‑scope configuration values.

7.2 GPT‑6‑Luna model identifier is unavailable within current account

Model availability is governed by subscription plan, login channel, client release and staged roll‑out schedules; the presence of a config‑file name does not grant actual access. Fall back to alternative accessible lightweight models, or keep sub‑agent functions running on the main‑thread model while narrowing sub‑agent task scope to cut resource overhead.

7.3 Read‑only scout sub‑agent still edits source‑code files

Natural‑language instructions are not security controls. Enable session‑level read‑only workspace sandbox mode or run investigative sub‑agents inside isolated workspaces. Never trust prompt‑based constraints for protecting critical repositories.

7.4 Total token usage rises after enabling sub‑agent layering

Reduce sub‑agent fan‑out count, constrain output verbosity, force scout agents to return only file‑paths, symbol‑names and condensed evidence. Avoid splitting trivial tasks that the main‑thread agent could finish in one turn.

8. Conclusion

Codex tiered‑model orchestration is not a magic trick for cutting costs by blindly shifting work to cheaper models. Its real value lies in resource‑aware division of labour: reserve high‑capacity flagship‑model reasoning for requirement analysis, architectural trade‑offs and final quality validation, while offloading bounded investigative and mechanical modification work onto lightweight sub‑agents.

Developers must carefully configure global and project‑level TOML settings, define role‑specific agent profiles, codify delegation rules inside AGENTS.md, and adopt structured orchestration prompts. Equally important is measurement: run baseline comparisons to validate real‑world efficiency, and be mindful of known failure points such as configuration overriding, model‑access restrictions and the fundamental limitation that prompt instructions cannot substitute for sandbox‑level security boundaries. When implemented thoughtfully, this layered pattern can produce more auditable agent workflows and optimise reasoning spend for production coding‑agent pipelines.

Tags:CodexMulti-Agent SystemsAI CodingToken OptimizationAGENTS.mdDeveloper ToolsAPI Engineering

Recommended reading

Explore more frontier insights and industry know-how.