Codex Subagent 深度指南:什么时候该开、什么时候别开、怎么用 3 个代理并行做代码审查
格帕文士 · 深度解读 项目:OpenAI Codex CLI / Codex App Subagent 系统 核心文档:developers.openai.com/codex/subagents
一句话定义
Subagent 是 Codex 的"分身术"——主会话(parent)可以凭空生出多个独立的子会话,每个子会话有自己的上下文窗口、自己的工具调用权限、自己的模型配置。子会话并行干活,主会话等它们全部完成后,把结果汇总成一份统一报告。
这不是多线程编程,这是多模型并行推理。
为什么需要 Subagent?三个真实痛点
痛点一:上下文爆炸(Context Pollution)
想象你要审查一个 500 行 PR。单代理模式下,模型需要:
- 读取 diff(可能 200 行)
- 读取相关文件(可能 5-10 个文件,数千行)
- 搜索代码库理解调用链(可能又加载数十个文件)
- 分析安全、性能、可维护性(全部在一个上下文里做)
结果是:上下文窗口被无关信息填满,模型"疲劳",质量下降。Anthropic 社区有人做过对比实验:同一个提示词,单代理输出的洞察质量 vs 拆成子代理,差距是"night and day"。
痛点二:串行等待的浪费
单代理只能一件一件做。审查安全 → 审查性能 → 审查可维护性 → 汇总。如果每个维度需要 3 分钟,三个维度就是 9 分钟。
Subagent 模式下:三个维度同时启动,3 分钟全部完成。
痛点三:工具权限的粒度控制
你想让一个代理只读代码(安全审查),另一个代理可以写测试(覆盖率修复),第三个代理可以改架构文件。单代理模式下,权限是二元的——要么全给,要么全不给。
Subagent 模式下,每个子代理可以有自己的 sandbox_mode:read-only、workspace-write、或 danger-full-access。
Subagent 不是万能药:什么时候别开
❌ 别开的情况
1. 简单任务
子代理有固定开销。OpenAI 官方说明:每个子代理"does its own model and tool work",消耗更多 token。一个小修复(改一行配置、加一个日志)不值得开子代理。
经验法则:如果任务能在 1-2 轮对话内完成,别开。
2. 需要快速迭代的探索
子代理是异步的。主代理发出指令 → 子代理干活 → 等待完成 → 读取结果。这个循环比直接在主会话里操作慢。如果你在做"试试这个方案,不行再试另一个"的快速迭代,子代理的延迟会拖累你。
3. 敏感/机密代码
每个子代理是独立会话,意味着你的代码会被多次加载到不同的上下文窗口。如果你处理的是机密代码,子代理增加了暴露面。codex-subagent-skill 的文档明确把"sensitive/classified code"列为不适用场景。
4. 递归深度失控
Codex 默认 max_depth = 1,即子代理不能再_spawn孙子代理。如果你把 max_depth 调高,一个宽泛的指令可能导致指数级 token 消耗。官方警告:"Raising this value can turn broad delegation instructions into repeated fan-out"。
✅ 该开的情况
1. 并行审查
多维度同时审查:安全 + 性能 + 可维护性。这是 Subagent 的杀手级场景。
2. 代码库探索
让子代理去读取大量文件、搜索代码库、理解调用链,只把结论带回主会话。主会话的上下文保持干净。
3. CSV 批处理
Codex 实验性支持 spawn_agents_on_csv:一行一个任务,自动 fan-out 到多个子代理。适合审查多个文件、多个服务、多个 PR。
4. 模型分级推理(Tiered Inference)
用 GPT-5.4-mini(成本低、速度快)做扫描和探索,用 GPT-5.4(强模型)做最终判断。cost 可以差 3.3 倍。
实战:3 个子代理并行审查 ShipReady 项目
ShipReady 是一个(虚构但典型的)物流追踪平台。我们要审查它的最新 PR。三个子代理分工如下:
| 子代理 | 职责 | 模型 | 沙盒 |
|---|---|---|---|
| runtime-risk-agent | 运行时风险:竞态条件、资源泄漏、并发安全 | GPT-5.4 | read-only |
| qa-coverage-agent | 测试覆盖:缺失的测试用例、边界条件、mock 合理性 | GPT-5.4-mini | read-only |
| architecture-agent | 架构审查:耦合度、SOLID 原则、API 设计 | GPT-5.4-mini | read-only |
配置代码
.codex/config.toml:
[agents]
max_threads = 6
max_depth = 1
.codex/agents/runtime-risk.toml:
name = "runtime_risk"
description = "Runtime risk auditor: race conditions, resource leaks, concurrency safety."
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Audit the code for runtime risks.
Focus on:
- Race conditions in concurrent code (goroutines, threads, async/await)
- Resource leaks (file handles, DB connections, memory)
- Deadlocks and livelocks
- Unbounded queues or buffers
- Unsafe pointer arithmetic or shared mutable state
For each finding, include:
- File and line number
- Severity: CRITICAL / HIGH / MEDIUM / LOW
- Reproduction steps or trigger condition
- Recommended fix with code snippet
"""
.codex/agents/qa-coverage.toml:
name = "qa_coverage"
description = "Test coverage reviewer: missing tests, edge cases, mock validity."
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Review the test suite for completeness and quality.
Focus on:
- Missing unit tests for new functions
- Missing integration tests for API changes
- Edge cases not covered (null, empty, overflow, timeout)
- Mock/stub quality: do mocks hide real bugs?
- Test flakiness: non-deterministic assertions, time-dependent tests
- Mutation testing gaps: which code paths are exercised but not asserted?
For each finding, include:
- Test file that should exist or be modified
- Specific scenario missing
- Example test case in the project's testing style
"""
.codex/agents/architecture.toml:
name = "architecture"
description = "Architecture reviewer: coupling, SOLID, API design, patterns."
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Review the code from an architecture perspective.
Focus on:
- Coupling: does the change introduce new dependencies between unrelated modules?
- SOLID violations: single responsibility, open/closed, dependency inversion
- API design: are new endpoints consistent with existing patterns?
- Data flow: does sensitive data pass through too many layers?
- Patterns: are appropriate design patterns used? Anti-patterns?
- Technical debt: does the change compound existing debt or reduce it?
For each finding, include:
- Architectural principle violated (if any)
- Concrete location (file, function, struct)
- Refactoring suggestion with rationale
"""
主代理的提示词
Review the current PR (this branch vs main) for the ShipReady project.
Spawn three subagents in parallel:
1. runtime_risk: audit for race conditions, resource leaks, concurrency issues
2. qa_coverage: audit for missing tests, edge cases, test quality
3. architecture: audit for coupling, SOLID, API design, technical debt
Wait for all three to complete, then synthesize a single prioritized report.
Report format:
- Executive Summary: top 3 issues that must be fixed before merge
- Detailed Findings: grouped by agent, sorted by severity
- Action Plan: which files to modify, in what order, with owner assignment
- Risk Acceptance: any issues that are acceptable to defer (with justification)
子代理的工作流程
Codex 内部实际执行的协议(CollabAgent 系统):
- spawnAgent → 创建三个独立线程,每个加载各自的 TOML 配置
- 三个线程并行运行,各自读取代码、分析、生成报告
- wait → 主线程阻塞,直到三个子代理都调用
report_agent_job_result - closeAgent → 关闭三个子线程,释放资源
- 主线程汇总结果,生成统一报告
审查结果示例(模拟 ShipReady 场景)
runtime-risk-agent 发现:
CRITICAL:shipment_tracker.go:142—sync.Mutex在错误路径未解锁,goroutine 泄漏HIGH:db_pool.go:89— 连接池未设置最大生命周期,长时间运行后连接耗尽MEDIUM:cache.go:56— 并发 map 写,未使用sync.Map或RWMutex
qa-coverage-agent 发现:
HIGH:新增RateLimiter结构体零测试覆盖MEDIUM:边界条件缺失——tracking_id为空字符串时的行为未测试MEDIUM:mock_db.go返回硬编码结果,隐藏了真实查询的 SQL 语法错误
architecture-agent 发现:
HIGH:api/handlers/新增 3 个 handler 直接依赖sql.DB,违反依赖倒置MEDIUM:services/层与models/层循环引用,编译通过但设计异味LOW:日志结构不统一,部分用log.Printf,部分用slog
主代理如何汇总、排序、落地修复
汇总策略:
- 去重:runtime-risk-agent 和 architecture-agent 都提到
db_pool.go的问题,合并为一个条目 - 排序:CRITICAL > HIGH > MEDIUM > LOW;同等级别按"阻塞程度"排序(能否阻止 merge)
- 分类:Must Fix(阻塞)vs Should Fix(非阻塞但强烈建议)vs Nice to Have
落地修复:
- 主代理将 Must Fix 分配给
worker子代理(执行型代理)逐个修复 - 每个修复后运行测试验证
- 修复完成后重新触发三个审查代理做回归验证
Subagent 的底层机制:CollabAgent 协议
Codex 的子代理不是简单的"新开一个终端",它有自己的协议:
| 操作 | 用途 |
|---|---|
spawnAgent |
创建新子代理线程,附带提示词和配置 |
sendInput |
向运行中的子代理发送追加指令 |
resumeAgent |
重新打开已暂停/完成的代理 |
wait |
同步原语——阻塞直到指定代理完成 |
closeAgent |
终止完成的代理线程 |
每个 collabAgentToolCall 包含:
senderThreadId:父线程receiverThreadIds:目标子线程(支持广播)prompt:发送的指令agentsStates:代理状态映射(昵称 →{status, message})
UI 层用 agent_nickname 而不是线程 ID 来显示,让你知道"Atlas 完成了"而不是"thread-7f3a 完成了"。
配置要点与坑
max_threads = 6(默认)
同时打开的代理线程上限。不是"一次最多 6 个",而是"任意时刻最多 6 个未完成"。如果你一次 spawn 10 个,Codex 会排队,前 6 个完成后才启动后 4 个。
max_depth = 1(默认)
子代理不能 spawn 孙代理。这是为了防止递归失控。如果你确实需要(比如父代理 spawn 审查代理,审查代理 spawn 修复代理),可以调高,但要承担 token 爆炸的风险。
沙盒继承与覆盖
子代理默认继承父代理的沙盒策略。但你可以在 TOML 里覆盖:
sandbox_mode = "read-only" # 这个子代理只能读,即使父代理给了写权限
审批(Approvals)
交互模式下,子代理的请求会弹出审批覆盖层,显示来源线程标签。你可以按 o 打开那个线程查看详情,再决定批准/拒绝。
非交互模式下(codex exec),无法弹出新鲜审批时,操作会失败,错误返回给父工作流。
成本考量:Subagent 不是免费的
OpenAI 官方明确说:"subagent workflows consume more tokens than comparable single-agent runs"。
具体数字(参考 GPT-5.4-mini 的定价):
- GPT-5.4-mini 输入:\(0.75/M tokens - GPT-5.4 输入:\)2.50/M tokens
- 比例:3.3 倍
三个子代理并行审查,如果两个用 mini、一个用 full,成本大约是单 full 代理的 1.6 倍(但速度是 3 倍,质量更高因为上下文不污染)。
如果全部用 full,成本是单代理的 3 倍。这时候要问:时间 vs 成本 vs 质量,你的优先级是什么?
与 Claude Code Subagent 的对比
| 维度 | Codex Subagent | Claude Code Subagent |
|---|---|---|
| 并行上限 | 6(可配置) | 未公开限制 |
| 配置方式 | TOML 文件 | Markdown 文件(agent 定义) |
| 模型路由 | 内置分级(mini/spark/full) | 模型由调用者指定 |
| CSV 批处理 | 原生支持(实验性) | 无原生支持 |
| 审批继承 | 父代理实时覆盖继承 | 独立审批 |
| 深度限制 | max_depth 明确配置 |
未明确 |
| 状态追踪 | agentsStates 映射 |
TaskList 工具 |
Codex 的设计更偏向工程化:配置文件、CSV 批处理、深度限制、结构化状态追踪。Claude Code 的设计更偏向灵活性:Agent 定义简单、上下文隔离彻底、适合探索性任务。
一句话总结
Subagent 是 Codex 的"并行推理基础设施"。它解决的不是"模型不够聪明",而是"一个上下文窗口装不下所有维度"和"串行等待太浪费"。
开不开 Subagent 的决策树:
任务简单?→ 别开
需要快速迭代?→ 别开
敏感代码?→ 别开
并行审查/探索/批处理?→ 开
模型分级能省成本?→ 开
ShipReady 案例展示了最佳实践:三个专业代理并行审查,主代理汇总去重排序,worker 代理落地修复,回归验证闭环。这不是未来,这是 Codex 现在的默认能力。
参考来源:
- OpenAI Codex Subagents 官方文档: developers.openai.com/codex/subagents
- Codex CLI Subagent Skill: github.com/iipanda/codex-subagent-skill
- GPT-5.4 mini in Codex CLI: codex.danielvaughan.com/2026/03/30/gpt54-mini-codex-subagent-delegation
- 3-Perspective Code Review: termdock.com/blog/multi-agent-code-review-pipeline
- Claude Code Subagent Patterns: aicatchup.com/practices/claude-code-subagent-patterns
- Codex Subagent GitHub Discussion: github.com/openai/codex/discussions/3898
- Harnss Codex Subagent 适配: github.com/OpenSource03/harnss/issues/40
#codex #subagent #OpenAI #代码审查 #并行代理 #格帕文士 #深度解读
讨论回复
1 条回复推荐
智谱 GLM-5 已上线
我正在智谱大模型开放平台 BigModel.cn 上打造 AI 应用,智谱新一代旗舰模型 GLM-5 已上线,在推理、代码、智能体综合能力达到开源模型 SOTA 水平。