Skip to content

Sub-agents 子智能体

Codex 支持 subagent(子智能体) 工作流,让你可以把边界清晰的工作交给子线程,主线程专注于核心问题。

官方 best practices:

Use Codex’s subagent workflows to offload bounded work from the main thread. Keep the main agent focused on the core problem, and use subagents for tasks like exploration, tests, or triage.

Codex 的 session 会积累上下文、决策和中间状态。如果所有事情都在一个线程里做:

  • 上下文越来越臃肿
  • 后面任务容易跑偏
  • 探索性工作会“污染”主线

用 Sub-agent 的好处:

  • 主线程保持干净,聚焦核心判断
  • 子线程消化局部信息,完成后只把结论带回
  • 多个 sub-agent 可以并行

官方推荐用 sub-agent 做的任务:

子任务类型 例子
代码探索 “找到所有处理支付的函数”
测试补充 “给 src/auth/ 补单元测试”
日志分析 “分析最近 1 小时的错误日志”
方案对比 “对比 Redis vs Memcached 做会话存储”
风险排查 “这次重构可能影响哪些下游服务”

这些任务边界清晰、目标明确,适合交给子线程。

运行并行 agent 时,用斜杠命令切换:

/agent

在不同 agent 线程间切换,查看各自进度。

多个 live thread 同时改同一批文件会冲突,必须用 git worktree 隔离(见第 20 章)。每个 sub-agent 在独立的 worktree 工作,互不干扰。

概念 作用
Skill 封装稳定的做事方法(怎么做一个任务)
Sub-agent 分配做事的线程(在哪个上下文里做)

可以组合:用 Skill 定义方法,用 Sub-agent 在独立线程执行。

官方建议:

Keep one thread per coherent unit of work. If the work is still part of the same problem, staying in the same thread is often better because it preserves the reasoning trail. Fork only when the work truly branches.

原则:一个 session 对应一个相对完整的任务。

  • 任务还在同一问题里 → 留在同一线程(保留推理过程)
  • 任务分叉 → fork 新线程或用 subagent