主题
Codex CLI SubAgent / Team Agent 深度调研
一、概述
Codex CLI(OpenAI 开源的终端编码 Agent,Rust 实现)支持 SubAgent 工作流——通过并行生成特化的子 Agent 来分解复杂任务,各自独立工作后汇总结果。与 Claude Code 的 SubAgent 不同,Codex 采用显式触发策略:不会自动生成 SubAgent,只在用户明确要求时才启动。
Codex 的多 Agent 体系包含两个层次:
- 内置 SubAgent 系统:CLI 原生的
spawn_agent工具 + TOML 自定义 Agent 定义 - 外部 Agents SDK 编排:通过 MCP 协议将 Codex 暴露为服务,使用 OpenAI Agents SDK 进行多 Agent 编排
二、核心架构
2.1 技术栈
Codex CLI 的 SubAgent 系统完全用 Rust 实现(codex-rs 仓库),核心文件:
| 文件 | 职责 |
|---|---|
core/src/tools/handlers/multi_agents/spawn.rs | SpawnAgentHandler——解析参数、构建配置、调用 AgentControl |
core/src/agent/control.rs | AgentControl——控制平面,线程生成/Fork/通信 |
core/src/tools/handlers/multi_agents.rs | 多 Agent 工具模块入口,注册所有 handler |
core/src/tools/handlers/multi_agents/close_agent.rs | 关闭 Agent 线程 |
core/src/tools/handlers/multi_agents/resume_agent.rs | 恢复已有 Agent |
core/src/tools/handlers/multi_agents/send_input.rs | 向 Agent 发送后续输入 |
core/src/tools/handlers/multi_agents/wait.rs | 等待 Agent 完成 |
2.2 工具集
Codex 将多 Agent 协作完全暴露为模型可调用的工具,由 LLM 自主决定何时使用:
| 工具 | 功能 |
|---|---|
spawn_agent | 生成新的子 Agent 线程 |
send_input | 向已有 Agent 发送后续输入/指令 |
resume_agent | 恢复已暂停的 Agent |
wait_agent | 阻塞等待 Agent 完成(前台等待) |
close_agent | 关闭 Agent 线程 |
spawn_agents_on_csv | 批量 CSV 处理(实验性) |
report_agent_job_result | Worker 报告 CSV 批处理结果 |
2.3 架构图
┌────────────────────────────────────────────────────┐
│ Main Agent (父线程) │
│ │
│ spawn_agent() spawn_agent() spawn_agent() │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Thread-1 │ │Thread-2 │ │Thread-3 │ │
│ │(Agent A)│ │(Agent B)│ │(Agent C)│ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ wait_agent() / 自动汇总结果 │
│ ┌──────────────────────┐ │
│ │ Consolidated Result │ │
│ └──────────────────────┘ │
└────────────────────────────────────────────────────┘三、spawn_agent 详解
3.1 参数定义
spawn_agent 的参数在 Rust 中定义为 SpawnAgentArgs:
rust
#[derive(Debug, Deserialize)]
struct SpawnAgentArgs {
message: Option<String>, // 文本消息(简单方式)
items: Option<Vec<UserInput>>, // 结构化输入项(高级方式)
agent_type: Option<String>, // 使用的 Agent 类型
model: Option<String>, // 模型覆盖
reasoning_effort: Option<ReasoningEffort>, // 推理努力程度
#[serde(default)]
fork_context: bool, // 是否继承父线程的完整对话历史
}3.2 输出
rust
#[derive(Debug, Serialize)]
pub(crate) struct SpawnAgentResult {
agent_id: String, // 新 Agent 的线程 ID
nickname: Option<String>, // 显示昵称
}3.3 执行流程
1. 解析 SpawnAgentArgs
2. 解析 agent_type(trim、过滤空字符串)
3. 解析 collab 输入(message + items 合并为 input_items)
4. 计算子线程深度(next_thread_spawn_depth)
5. 检查深度限制(exceeds_thread_spawn_depth_limit)
6. 构建 Agent 生成配置(build_agent_spawn_config)
7. 应用模型覆盖(apply_requested_spawn_agent_model_overrides)
8. 应用角色配置(apply_role_to_config)→ 查找自定义 Agent TOML
9. 调用 AgentControl::spawn_agent_with_metadata
10. 返回 { agent_id, nickname }3.4 fork_context 机制
fork_context 参数控制子 Agent 是否继承父线程的完整对话历史:
fork_context: false(默认):子 Agent 从空白开始,仅接收spawn_agent调用中提供的指令fork_context: true:子 Agent 继承父线程的完整对话历史,成为父 Agent 的"克隆"
rust
pub(crate) enum SpawnAgentForkMode {
FullHistory, // 继承完整历史
LastNTurns(usize), // 只继承最近 N 轮
}Fork 后,子线程会收到一条消息:
"You are the newly spawned agent. The prior conversation history was..."
注意事项:
fork_context=true可能导致大量 token 消耗(长对话历史被完整复制到子线程)- 社区建议增加
allow_fork_context = false配置项来硬性禁用此功能 - 默认情况下省略
fork_context即为false
四、AgentControl 控制平面
AgentControl 是多 Agent 操作的核心控制平面,每个 root 会话/线程只创建一个实例:
rust
#[derive(Clone, Default)]
pub(crate) struct AgentControl {
manager: Weak<ThreadManagerState>, // 线程管理器的弱引用
state: Arc<AgentRegistry>, // Agent 注册表
}4.1 核心方法
| 方法 | 功能 |
|---|---|
spawn_agent() | 生成新 Agent 线程并提交初始提示 |
spawn_agent_with_metadata() | 带元数据的 Agent 生成 |
spawn_agent_internal() | 内部实现,处理 fork/非 fork 分支 |
spawn_forked_thread() | Fork 模式:克隆父线程历史到新线程 |
send_input() | 向指定 Agent 线程发送输入 |
4.2 昵称系统
Codex 内置了一个预定义的 Agent 名称列表(agent_names.txt),用于给生成的 Agent 分配可读的显示昵称。也可以在自定义 Agent 中通过 nickname_candidates 指定专属候选昵称。
4.3 继承与隔离
子 Agent 从父线程继承的运行时状态:
| 继承项 | 说明 |
|---|---|
| Provider | API 提供商配置 |
| Approval policy | 审批策略 |
| Sandbox mode | 沙箱模式 |
| CWD | 工作目录 |
| Base instructions | 基础指令(AGENTS.md) |
| Runtime overrides | 会话中用户的动态覆盖(如 /approvals 变更、--yolo) |
子 Agent 可额外叠加的角色特定配置:
- 自定义 Agent TOML 中的
model、model_reasoning_effort、sandbox_mode - 角色特定的
developer_instructions - 角色特定的
mcp_servers
五、内置 Agent 类型
Codex 提供三种内置 Agent 类型:
| Agent 类型 | 用途 | 特点 |
|---|---|---|
default | 通用兜底 Agent | 当未指定 agent_type 时使用 |
worker | 执行型 Agent | 专注于实现和修复 |
explorer | 探索型 Agent | 只读,适合代码库探索和证据收集 |
覆盖规则: 如果自定义 Agent 的 name 与内置 Agent(如 explorer)相同,自定义 Agent 优先。
六、自定义 Agent 定义
6.1 文件位置
| 位置 | 作用域 | 说明 |
|---|---|---|
~/.codex/agents/*.toml | 个人级 | 跨项目可用 |
.codex/agents/*.toml | 项目级 | 随项目版本控制 |
每个 TOML 文件定义一个自定义 Agent。Codex 将这些文件作为配置层加载到生成的会话上,因此自定义 Agent 可以覆盖与正常 Codex 会话配置相同的设置。
6.2 Schema 定义
必填字段:
| 字段 | 类型 | 说明 |
|---|---|---|
name | string | Agent 名称,Codex 生成或引用时使用 |
description | string | 面向用户的指引——何时应使用此 Agent |
developer_instructions | string | 定义 Agent 行为的核心指令 |
可选字段(省略时从父会话继承):
| 字段 | 类型 | 说明 |
|---|---|---|
nickname_candidates | string[] | 显示昵称候选池 |
model | string | 模型选择 |
model_reasoning_effort | string | 推理努力程度 (high/medium/low) |
sandbox_mode | string | 沙箱模式 (read-only/workspace-write 等) |
mcp_servers | table | MCP 服务器配置 |
skills.config | array | 技能配置 |
6.3 完整示例
示例 1:PR 审查团队(三个 Agent 协作)
项目配置 .codex/config.toml:
toml
[agents]
max_threads = 6
max_depth = 1探索 Agent .codex/agents/pr-explorer.toml:
toml
name = "pr_explorer"
description = "Read-only codebase explorer for gathering evidence before changes are proposed."
model = "gpt-5.3-codex-spark"
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 the parent agent asks for them.
Prefer fast search and targeted file reads over broad scans.
"""审查 Agent .codex/agents/reviewer.toml:
toml
name = "reviewer"
description = "PR reviewer focused on correctness, security, and missing tests."
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "read-only"
developer_instructions = """
Review code like an owner.
Prioritize correctness, security, behavior regressions, and missing test coverage.
Lead with concrete findings, include reproduction steps when possible, and avoid style-only comments unless they hide a real bug.
"""
nickname_candidates = ["Atlas", "Delta", "Echo"]文档研究 Agent .codex/agents/docs-researcher.toml:
toml
name = "docs_researcher"
description = "Documentation specialist that uses the docs MCP server to verify APIs and framework behavior."
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Use the docs MCP server to confirm APIs, options, and version-specific behavior.
Return concise answers with links or exact references when available.
Do not make code changes.
"""
[mcp_servers.openaiDeveloperDocs]
url = "https://developers.openai.com/mcp"使用方式:
text
Review this branch against main. Have pr_explorer map the affected code paths,
reviewer find real risks, and docs_researcher verify the framework APIs that
the patch relies on.示例 2:前端集成调试团队
代码映射 Agent .codex/agents/code-mapper.toml:
toml
name = "code_mapper"
description = "Read-only codebase explorer for locating the relevant frontend and backend code paths."
model = "gpt-5.4-mini"
model_reasoning_effort = "medium"
sandbox_mode = "read-only"
developer_instructions = """
Map the code that owns the failing UI flow.
Identify entry points, state transitions, and likely files before the worker starts editing.
"""浏览器调试 Agent .codex/agents/browser-debugger.toml:
toml
name = "browser_debugger"
description = "UI debugger that uses browser tooling to reproduce issues and capture evidence."
model = "gpt-5.4"
model_reasoning_effort = "high"
sandbox_mode = "workspace-write"
developer_instructions = """
Reproduce the issue in the browser, capture exact steps, and report what the UI actually does.
Use browser tooling for screenshots, console output, and network evidence.
Do not edit application code.
"""
[mcp_servers.chrome_devtools]
url = "http://localhost:3000/mcp"
startup_timeout_sec = 20UI 修复 Agent .codex/agents/ui-fixer.toml:
toml
name = "ui_fixer"
description = "Implementation-focused agent for small, targeted fixes after the issue is understood."
model = "gpt-5.3-codex-spark"
model_reasoning_effort = "medium"
developer_instructions = """
Own the fix once the issue is reproduced.
Make the smallest defensible change, keep unrelated files untouched, and validate only the behavior you changed.
"""
[[skills.config]]
path = "/Users/me/.agents/skills/docs-editor/SKILL.md"
enabled = false6.4 自定义 Agent 设计原则
"最好的自定义 Agent 是窄小且固执己见的。给每个 Agent 一个清晰的任务,匹配该任务的工具表面,以及防止它漂移到相邻工作的指令。"
关键点:
- 单一职责:每个 Agent 只做一件事
- 工具匹配:通过
sandbox_mode限制工具范围(如read-only) - 防漂移指令:明确告诉 Agent 不该做什么(如"Do not make code changes")
- 模型匹配:探索用便宜快速的模型,深度推理用强力模型
七、全局配置
7.1 config.toml 中的 Agent 配置
toml
[agents]
max_threads = 6 # 最大并发线程数(默认 6)
max_depth = 1 # 嵌套深度(默认 1,允许直接子 Agent 但阻止更深嵌套)
job_max_runtime_seconds = 1800 # CSV 批处理每个 Worker 的超时时间关于 max_depth:
- 默认值
1意味着:根会话(深度 0)可以生成子 Agent(深度 1),但子 Agent 不能再生成孙 Agent - 提高此值有风险:宽泛的委派指令可能变成反复 fan-out,导致 token 消耗、延迟和资源消耗暴增
max_threads仍然限制并发线程数,但无法消除深层递归带来的成本和可预测性风险- 在
max_depth限制处,协作工具(spawn_agent等)会被禁用
7.2 工具重建机制
Codex 独特之处:工具列表每次采样请求时动态重建(built_tools() 在 codex.rs 中每次调用),而非一次性静态初始化。这意味着到达深度限制时,spawn_agent 等工具会从 Agent 的工具集中消失。
八、SubAgent 管理
8.1 CLI 命令
| 命令 | 功能 |
|---|---|
/agent | 切换活跃 Agent 线程,检查或继续某个 Agent 的工作 |
/fork | Fork 当前对话为新线程(探索替代方案) |
8.2 模型可用的管理工具
| 工具 | 功能 |
|---|---|
send_input | 向已有 Agent 追加输入 |
resume_agent | 恢复已有 Agent |
wait_agent | 前台阻塞等待子 Agent 完成 |
close_agent | 关闭 Agent 线程 |
8.3 审批与沙箱控制
- SubAgent 继承父线程的沙箱策略
- 在交互式 CLI 会话中,审批请求可以从非活跃 Agent 线程弹出(即使你正在查看主线程)
- 审批弹层显示来源线程标签,按
o可打开该线程再决定 - 非交互模式中,需要新审批的操作会直接失败,Codex 将错误上报给父工作流
- 父线程的运行时覆盖(如
/approvals变更、--yolo)会重新应用到子 Agent,即使自定义 Agent 文件设置了不同默认值
九、CSV 批处理(实验性)
spawn_agents_on_csv 是一个 Map-Reduce 风格的批量子 Agent 工作流:
9.1 工作流程
CSV 输入 → 每行生成一个 Worker SubAgent → 并行执行 → 结果汇总到输出 CSV + SQLite9.2 参数
| 参数 | 类型 | 说明 |
|---|---|---|
csv_path | string | 源 CSV 文件路径 |
instruction | string | Worker 提示模板,使用 {column_name} 占位符 |
id_column | string | 稳定标识符列名 |
output_schema | object | 每个 Worker 应返回的 JSON 对象结构 |
output_csv_path | string | 输出 CSV 路径 |
max_concurrency | number | 最大并发数 |
max_runtime_seconds | number | 每个 Worker 超时时间 |
9.3 使用示例
text
Create /tmp/components.csv with columns path,owner and one row per frontend component.
Then call spawn_agents_on_csv with:
- csv_path: /tmp/components.csv
- id_column: path
- instruction: "Review {path} owned by {owner}. Return JSON with keys path, risk, summary, and follow_up via report_agent_job_result."
- output_csv_path: /tmp/components-review.csv
- output_schema: an object with required string fields path, risk, summary, and follow_up9.4 关键规则
- 每个 Worker 必须恰好调用一次
report_agent_job_result - 如果 Worker 退出时未报告结果,Codex 在导出 CSV 中标记该行为错误
- 导出的 CSV 包含原始行数据 + 元数据(
job_id、item_id、status、last_error、result_json) - 通过
codex exec运行时,stderr显示单行进度条(带 ETA)
9.5 适用场景
- 审查每个文件/包/服务
- 检查一批事件、PR 或迁移目标
- 为大量相似输入生成结构化摘要
十、触发与提示工程
10.1 显式触发原则
Codex 不会自动生成 SubAgent。必须在提示中明确要求:
text
# 好的提示
"Spawn two agents to review security and test coverage in parallel."
"Delegate this work to parallel subagents."
"Use one agent per point."
# 无效的提示(不会触发 SubAgent)
"Review this code thoroughly." ← 不会自动使用 SubAgent10.2 良好的 SubAgent 提示结构
一个好的 SubAgent 提示应说明:
- 如何拆分工作
- 是否等待所有 Agent 完成后再继续
- 返回什么样的摘要或输出
text
Review this branch with parallel subagents.
Spawn one subagent for security risks, one for test gaps, and one for maintainability.
Wait for all three, then summarize the findings by category with file references.10.3 指定自定义 Agent
text
Spawn pr-reviewer to check this PR.
Have pr_explorer map the affected code paths, reviewer find real risks.10.4 控制 fork_context
text
Spawn subagent with fork_context=true to inherit our discussion context.
Spawn subagent with fork_context=false for a fresh perspective.十一、模型与推理选择
11.1 推荐模型
| 模型 | 适用场景 |
|---|---|
gpt-5.4 | 大多数 Agent 的起点。编码、推理、工具使用、复杂工作流 |
gpt-5.4-mini | 速度优先的轻量任务:探索、只读扫描、大文件审查、文档处理 |
gpt-5.3-codex-spark | ChatGPT Pro 专属,近乎即时的纯文本迭代 |
11.2 推理努力程度
| 级别 | 适用场景 |
|---|---|
high | 追踪复杂逻辑、检查假设、处理边界情况(如审查 Agent、安全分析 Agent) |
medium | 大多数 Agent 的平衡默认值 |
low | 任务简单直接、速度最重要 |
11.3 自动选择
如果不固定 model 或 model_reasoning_effort,Codex 会自动选择平衡智能、速度和价格的配置:
- 快速扫描任务可能选择
gpt-5.4-mini - 复杂推理任务可能选择高努力的
gpt-5.4配置
十二、AGENTS.md 指令系统
12.1 层级加载
Codex 在启动时构建指令链(每次运行一次),按以下顺序加载:
1. 全局:~/.codex/AGENTS.override.md → ~/.codex/AGENTS.md
2. 项目(从项目根到当前目录逐层走):
每层检查:AGENTS.override.md → AGENTS.md → 回退文件名列表
3. 合并:从根向下拼接,靠近当前目录的文件优先级更高限制:合并后总大小不超过 project_doc_max_bytes(默认 32KiB)。
12.2 与 SubAgent 的关系
- SubAgent 继承父线程的 base instructions(包括 AGENTS.md 内容)
- 自定义 Agent 的
developer_instructions会叠加到基础指令之上 - AGENTS.md 定义的是项目级行为规范,而自定义 Agent TOML 定义的是角色特定行为
12.3 示例
markdown
# AGENTS.md
## Repository expectations
- Run `npm run lint` before opening a pull request.
- Document public utilities in `docs/` when you change behavior.markdown
# services/payments/AGENTS.override.md
## Payments service rules
- Use `make test-payments` instead of `npm test`.
- Never rotate API keys without notifying the security channel.十三、Skills 技能系统
13.1 与自定义 Agent 的关系
Skills 和自定义 Agent 是互补的:
- Skills:定义可复用的工作流程(如发布步骤、审查流程、文档更新)
- 自定义 Agent:定义特化的角色,可以选择预加载特定 Skills
13.2 Skill 目录
| 作用域 | 位置 |
|---|---|
| 项目级 | .agents/skills/ |
| 用户级 | $HOME/.agents/skills/ 或 ~/.codex/skills/ |
13.3 在自定义 Agent 中配置 Skills
toml
# .codex/agents/ui-fixer.toml
name = "ui_fixer"
description = "..."
developer_instructions = "..."
[[skills.config]]
path = "/path/to/skill/SKILL.md"
enabled = true # 或 false 来禁用13.4 渐进式披露
Codex 对 Skills 采用渐进式披露策略:
- 启动时只加载 Skills 元数据(
name、description) - 仅当 Agent 决定使用某个 Skill 时才加载完整的
SKILL.md指令
十四、外部编排:Agents SDK + MCP
除了内置 SubAgent 系统,Codex 还支持通过 OpenAI Agents SDK 进行更复杂的多 Agent 编排。
14.1 架构
┌──────────────────────────────────────────┐
│ OpenAI Agents SDK (Python) │
│ │
│ ┌──────────┐ ┌───────────────┐ │
│ │ Agent A │ │ Agent B │ │
│ │ (Designer)│ │(Frontend Dev) │ │
│ └─────┬─────┘ └──────┬───────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌────────────────────────────────────┐ │
│ │ Codex CLI (MCP Server) │ │
│ │ codex() | codex_apply_patch() │ │
│ └────────────────────────────────────┘ │
└──────────────────────────────────────────┘14.2 初始化 Codex MCP 服务器
python
from agents.mcp import MCPServerStdio
async with MCPServerStdio(
name="Codex CLI",
params={
"command": "npx",
"args": ["-y", "codex", "mcp"]
},
client_session_timeout_seconds=360000,
) as codex_mcp_server:
# Agent 定义...Codex MCP 服务器暴露两个工具:
codex()— 执行编码任务codex_apply_patch()— 应用代码补丁
14.3 多 Agent 团队定义
python
from agents import Agent, ModelSettings, Runner, Reasoning
# 设计师 Agent
designer_agent = Agent(
name="Designer",
instructions="You are the Designer. Create UI/UX specs...",
model="gpt-5",
mcp_servers=[codex_mcp_server],
)
# 前端开发 Agent
frontend_developer_agent = Agent(
name="Frontend Developer",
instructions="You are the Frontend Developer. Implement the UI...",
model="gpt-5",
mcp_servers=[codex_mcp_server],
)
# 测试 Agent
tester_agent = Agent(
name="Tester",
instructions="You are the Tester. Validate outputs...",
model="gpt-5",
mcp_servers=[codex_mcp_server],
)
# 项目经理 Agent(协调者)
project_manager_agent = Agent(
name="Project Manager",
instructions="""
You are the Project Manager.
1) Create REQUIREMENTS.md, TEST.md, AGENT_TASKS.md
2) Hand off to Designer with transfer_to_designer_agent
3) After design, hand off to Frontend Developer
4) After implementation, hand off to Tester
5) Do not advance until artifacts exist
""",
model="gpt-5",
model_settings=ModelSettings(
reasoning=Reasoning(effort="medium"),
),
handoffs=[designer_agent, frontend_developer_agent, tester_agent],
mcp_servers=[codex_mcp_server],
)
# 执行
result = await Runner.run(project_manager_agent, task_list, max_turns=30)14.4 与内置 SubAgent 的差异
| 维度 | 内置 SubAgent | Agents SDK 编排 |
|---|---|---|
| 实现语言 | Rust(CLI 原生) | Python(外部) |
| 编排方式 | 模型自主决定何时生成 | 预定义 handoff 链 |
| 通信机制 | CLI 线程间通信 | MCP 协议 |
| 确定性 | 模型驱动,较不确定 | 门控 handoff,更确定 |
| 可追踪性 | CLI 线程检查 | Agents SDK Traces(完整的提示/工具调用/handoff 记录) |
| 适用场景 | 灵活的临时并行任务 | 复杂的、需要严格流程控制的工作流 |
十五、核心概念与权衡
15.1 上下文污染与上下文腐烂
- 上下文污染 (Context Pollution):有用信息被嘈杂的中间输出埋没
- 上下文腐烂 (Context Rot):对话中不相关细节越来越多,性能逐渐退化
SubAgent 通过将嘈杂工作移出主线程来缓解这两个问题:
- 主 Agent 保持聚焦于需求、决策和最终输出
- SubAgent 并行处理探索、测试、日志分析
- SubAgent 返回摘要而非原始中间输出
15.2 并行读 vs 并行写
- 推荐并行:只读任务(探索、测试、分类、摘要)
- 谨慎并行:写操作(Agent 同时编辑代码可能产生冲突,增加协调开销)
15.3 成本考量
- 每个 SubAgent 都有自己的模型和工具调用,SubAgent 工作流比单 Agent 运行消耗更多 token
- 使用
gpt-5.4-mini做轻量级并行扫描 - 使用
gpt-5.4做需要深度推理的主 Agent 和协调 Agent fork_context=true可能导致 token 消耗大幅增加
十六、与 Claude Code SubAgent 的对比
| 维度 | Codex CLI | Claude Code |
|---|---|---|
| 实现语言 | Rust | TypeScript (Node.js) |
| 触发方式 | 显式触发(用户明确要求) | 模型自主决定(可自动生成) |
| 定义格式 | TOML | Markdown + YAML frontmatter |
| 内置类型数 | 3 种 (default/worker/explorer) | 6 种 (General/Explore/Plan/Verification/Guide/Statusline) |
| 嵌套限制 | 可配置 max_depth(默认 1) | 硬限制 depth=1(默认不可递归) |
| 并发限制 | max_threads(默认 6) | 最多 10 个并行子 Agent |
| 上下文继承 | fork_context 参数控制 | Fork Agent 机制(字节精确缓存利用) |
| 缓存优化 | 无特殊 prompt cache 优化 | Fork Agent 实现 90% 缓存折扣 |
| 批处理 | spawn_agents_on_csv(CSV Map-Reduce) | 无原生批处理 |
| 外部编排 | Agents SDK + MCP Server | Agent Teams(实验性) |
| 工具暴露 | 5 个工具给模型(spawn/send/resume/wait/close) | 1 个 Agent/Task 工具 |
| 沙箱控制 | 每个 Agent 可独立设置 sandbox_mode | 通过 permissionMode 控制 |
| 模型选择 | gpt-5.4/gpt-5.4-mini/gpt-5.3-codex-spark | Haiku/Sonnet/Opus/inherit |
| 指令系统 | AGENTS.md(层级加载) | CLAUDE.md + 系统提示 |
十七、最佳实践总结
17.1 何时使用 SubAgent
| 适合使用 | 不适合使用 |
|---|---|
| 高度并行的只读任务 | 需要频繁来回交互的任务 |
| 代码库探索和证据收集 | 多阶段共享大量上下文的任务 |
| 多维度独立审查 | 快速且局部的变更 |
| 大规模文档/文件批量处理 | 单一简单的编码任务 |
17.2 自定义 Agent 设计
- 保持窄小和固执:一个 Agent 一个任务
- 匹配工具表面:探索 Agent 用
read-only,实现 Agent 用workspace-write - 防漂移指令:明确说不该做什么
- 匹配模型和推理:探索用 mini + medium,审查用 full + high
- 版本控制:项目级 Agent 放
.codex/agents/随代码提交
17.3 提示工程
- 明确要求并行:"Spawn one agent per point"
- 指定等待策略:"Wait for all three, then summarize"
- 指定输出格式:"Summarize findings by category with file references"
- 按名指定 Agent:"Have pr_explorer map the paths, reviewer find risks"
参考资料
- Codex 官方文档 - Subagents
- Codex 官方文档 - Subagent Concepts
- Codex 官方文档 - Custom Instructions (AGENTS.md)
- Codex 官方文档 - Agent Skills
- Codex 官方文档 - Agents SDK
- Codex 官方文档 - Customization
- Codex 源码 - spawn.rs
- Codex 源码 - control.rs
- OpenAI Cookbook - Multi-Agent Workflow
- Agent Jobs PR #10935
- arXiv 2604.03515 - Source-Code Taxonomy of Coding Agent Architectures