子代理派生
源码版本v2026.7.20
职责
delegate_tool 让主 agent 把一个子任务派生给隔离的子代理:子代理有自己的对话、自己的终端、自己的工具集,跑完只把最终结果交回父代理。这实现了「零上下文成本」的流水线——父代理上下文不被子任务的过程细节污染。子代理在 ThreadPoolExecutor worker 里运行,危险命令默认 auto-deny(可配置 auto-approve)。
关键文件
def delegate_task:2426— 派生入口class DelegateEvent:625— 派生事件枚举auto-deny / auto-approve 回调:61-103—_subagent_auto_deny(安全默认)/_subagent_auto_approve(opt-in YOLO)_get_subagent_approval_callback:102-160— 按delegation.subagent_auto_approve配置选回调DaemonThreadPoolExecutor:1978-1990— 子代理用的常驻线程池with DaemonThreadPoolExecutor:2651-2660— 派生执行上下文tools/daemon_pool.py—DaemonThreadPoolExecutor实现多后端终端:5-15— 子代理的终端在 6 个沙箱后端之一执行(见沙箱)
数据流
- 主循环 provider 返回
tool_call: delegate。 delegate_task:2426被调用,拿到子任务描述与可选 toolsets。- 在
DaemonThreadPoolExecutor:2651里起一个 worker:- worker initializer 安装审批回调(
tools/delegate_tool.py:102),默认 auto-deny 危险命令 - 子代理构造自己的对话上下文,调
run_conversation:588跑循环 - 子代理的工具调用走
registry:765(可被父代理限制 toolsets)
- worker initializer 安装审批回调(
- 子代理完成后只把最终文本交回,delegate_task 经
tool_result:798封装回填给父代理。 - 父代理上下文只增长一条 tool 结果,不被过程污染。
小结
子代理派生 = 上下文隔离 + 危险命令管控。父代理只看结果,不看过程,这让长流水线不被过程噪声撑爆。安全默认 auto-deny,批量/cron 场景可 opt-in auto-approve。终端执行落在沙箱后端。