跳到主要内容

子 Agent 委派

delegate_task 工具可生成具有独立上下文、受限工具集和独立终端会话的子 AIAgent 实例。每个子 Agent 都以全新的对话开始并独立工作——只有其最终摘要会进入父 Agent 的上下文。

单任务

delegate_task(
goal="Debug why tests fail",
context="Error: assertion in test_foo.py line 42",
toolsets=["terminal", "file"]
)

并行批处理

默认最多 3 个并发子 Agent(可配置,无硬上限):

delegate_task(tasks=[
{"goal": "Research topic A", "toolsets": ["web"]},
{"goal": "Research topic B", "toolsets": ["web"]},
{"goal": "Fix the build", "toolsets": ["terminal", "file"]}
])

子 Agent 上下文的工作方式

关键:子 Agent 一无所知

子 Agent 以全新的对话开始。它们对父 Agent 的对话历史、之前的工具调用或委派前讨论的任何内容一无所知。子 Agent 的唯一上下文来自父 Agent 调用 delegate_task 时填写的 goalcontext 字段。

这意味着父 Agent 必须在调用中传入子 Agent 所需的一切信息

# 错误示例 - 子 Agent 不知道"the error"是什么
delegate_task(goal="Fix the error")

# 正确示例 - 子 Agent 拥有所需的全部上下文
delegate_task(
goal="Fix the TypeError in api/handlers.py",
context="""The file api/handlers.py has a TypeError on line 47:
'NoneType' object has no attribute 'get'.
The function process_request() receives a dict from parse_body(),
but parse_body() returns None when Content-Type is missing.
The project is at /home/user/myproject and uses Python 3.11."""
)

子 Agent 接收由 goal 和 context 构建的专注系统提示,指示其完成任务并提供结构化摘要,包括所做的事情、发现的内容、修改的文件以及遇到的问题。

实际示例

并行研究

同时研究多个主题并收集摘要:

delegate_task(tasks=[
{
"goal": "Research the current state of WebAssembly in 2025",
"context": "Focus on: browser support, non-browser runtimes, language support",
"toolsets": ["web"]
},
{
"goal": "Research the current state of RISC-V adoption in 2025",
"context": "Focus on: server chips, embedded systems, software ecosystem",
"toolsets": ["web"]
},
{
"goal": "Research quantum computing progress in 2025",
"context": "Focus on: error correction breakthroughs, practical applications, key players",
"toolsets": ["web"]
}
])

代码审查 + 修复

将审查和修复工作流委派给全新的上下文:

delegate_task(
goal="Review the authentication module for security issues and fix any found",
context="""Project at /home/user/webapp.
Auth module files: src/auth/login.py, src/auth/jwt.py, src/auth/middleware.py.
The project uses Flask, PyJWT, and bcrypt.
Focus on: SQL injection, JWT validation, password handling, session management.
Fix any issues found and run the test suite (pytest tests/auth/).""",
toolsets=["terminal", "file"]
)

多文件重构

委派会大量占用父 Agent 上下文的大型重构任务:

delegate_task(
goal="Refactor all Python files in src/ to replace print() with proper logging",
context="""Project at /home/user/myproject.
Use the 'logging' module with logger = logging.getLogger(__name__).
Replace print() calls with appropriate log levels:
- print(f"Error: ...") -> logger.error(...)
- print(f"Warning: ...") -> logger.warning(...)
- print(f"Debug: ...") -> logger.debug(...)
- Other prints -> logger.info(...)
Don't change print() in test files or CLI output.
Run pytest after to verify nothing broke.""",
toolsets=["terminal", "file"]
)

批处理模式详情

当提供 tasks 数组时,子 Agent 使用线程池并行运行:

  • 最大并发数: 默认 3 个任务(可通过 delegation.max_concurrent_childrenDELEGATION_MAX_CONCURRENT_CHILDREN 环境变量配置;最小值为 1,无硬上限)。超过限制的批次会返回工具错误,而不是静默截断。
  • 线程池: 使用 ThreadPoolExecutor,以配置的并发限制作为最大工作线程数
  • 进度显示: 在 CLI 模式下,树形视图实时显示每个子 Agent 的工具调用,并显示每个任务的完成行。在网关模式下,进度会批量收集并传递给父 Agent 的进度回调
  • 结果排序: 结果按任务索引排序,与输入顺序保持一致(与完成顺序无关)
  • 中断传播: 中断父 Agent(例如发送新消息)会中断所有活跃的子 Agent

单任务委派直接运行,无线程池开销。

模型覆盖

可通过 config.yaml 为子 Agent 配置不同的模型——适合将简单任务委派给更便宜/更快的模型:

# In ~/.hermes/config.yaml
delegation:
model: "google/gemini-flash-2.0" # Cheaper model for subagents
provider: "openrouter" # Optional: route subagents to a different provider

如果省略,子 Agent 使用与父 Agent 相同的模型。

工具集选择技巧

toolsets 参数控制子 Agent 可访问的工具。根据任务选择:

工具集模式使用场景
["terminal", "file"]代码工作、调试、文件编辑、构建
["web"]研究、事实核查、文档查阅
["terminal", "file", "web"]全栈任务(默认)
["file"]只读分析、无需执行的代码审查
["terminal"]系统管理、进程管理

无论你指定什么,某些工具集对子 Agent 都会被阻止:

  • delegation — 叶子子 Agent(默认)被阻止。role="orchestrator" 的子 Agent 保留此工具,受 max_spawn_depth 限制——参见下方深度限制与嵌套编排
  • clarify — 子 Agent 无法与用户交互
  • memory — 不能写入共享持久记忆
  • code_execution — 子 Agent 应逐步推理
  • send_message — 禁止跨平台副作用(例如发送 Telegram 消息)

最大迭代次数

每个子 Agent 都有一个迭代限制(默认:50),控制其可进行的工具调用轮次:

delegate_task(
goal="Quick file check",
context="Check if /etc/nginx/nginx.conf exists and print its first 10 lines",
max_iterations=10 # Simple task, don't need many turns
)

子 Agent 超时

如果子 Agent 静默超过 delegation.child_timeout_seconds 秒,将被判定为卡死并终止。默认值为 600(10 分钟)——从早期版本的 300 秒提升,因为高推理模型在执行非平凡研究任务时会在思考过程中被终止。按需调整:

delegation:
child_timeout_seconds: 600 # default

对快速本地模型可降低此值;对慢速推理模型处理困难问题时可提高此值。每次子 Agent 进行 API 调用或工具调用时,计时器会重置——只有真正空闲的工作进程才会触发终止。

零调用超时的诊断转储

如果子 Agent 在零次 API 调用后超时(通常是:提供商不可达、认证失败或工具模式拒绝),delegate_task 会将结构化诊断信息写入 ~/.hermes/logs/subagent-timeout-<session>-<timestamp>.log,包含子 Agent 的配置快照、凭证解析跟踪以及任何早期错误消息。比之前的静默超时行为更容易定位根因。

监控运行中的子 Agent(/agents

TUI 提供了 /agents 覆盖层(别名 /tasks),将递归的 delegate_task 扇出转变为一流的审计界面:

  • 运行中和最近完成的子 Agent 的实时树形视图,按父 Agent 分组
  • 按分支的成本、令牌和文件触及汇总
  • 终止和暂停控件——在不中断兄弟 Agent 的情况下取消特定子 Agent
  • 事后审查:即使子 Agent 已返回给父 Agent,也可逐步查看每个子 Agent 的逐轮历史

经典 CLI 仅将 /agents 打印为文本摘要;TUI 才是覆盖层真正发挥作用的地方。参见 TUI — 斜杠命令

深度限制与嵌套编排

默认情况下,委派是扁平的:父 Agent(深度 0)生成子 Agent(深度 1),这些子 Agent 无法进一步委派。这可防止失控的递归委派。

对于多阶段工作流(研究 → 综合,或对子问题进行并行编排),父 Agent 可以生成能够委派自身工作者的编排器子 Agent:

delegate_task(
goal="Survey three code review approaches and recommend one",
role="orchestrator", # Allows this child to spawn its own workers
context="...",
)
  • role="leaf"(默认):子 Agent 无法进一步委派——与扁平委派行为相同。
  • role="orchestrator":子 Agent 保留 delegation 工具集。受 delegation.max_spawn_depth 限制(默认 1 = 扁平,因此在默认设置下 role="orchestrator" 无效)。将 max_spawn_depth 提升至 2 以允许编排器子 Agent 生成叶子孙 Agent;3 为三级(上限)。
  • delegation.orchestrator_enabled: false:全局开关,无论 role 参数如何,强制所有子 Agent 为 leaf

费用警告: 使用 max_spawn_depth: 3max_concurrent_children: 3,树最多可达 3×3×3 = 27 个并发叶子 Agent。每增加一层都会成倍增加花费——请谨慎提高 max_spawn_depth

生命周期与持久性

delegate_task 是同步的——不具有持久性

delegate_task 在父 Agent 的当前轮次运行。它会阻塞父 Agent,直到所有子 Agent 完成(或被取消)。它不是后台任务队列:

  • 如果父 Agent 被中断(用户发送新消息、/stop/new),所有活跃的子 Agent 将被取消并返回 status="interrupted"。其正在进行的工作将被丢弃。
  • 子 Agent 在父 Agent 轮次结束后不会继续运行。
  • 被取消的子 Agent 返回结构化结果(status="interrupted"exit_reason="interrupted"),但由于父 Agent 也被中断,该结果通常无法进入用户可见的回复。

对于必须在中断后继续或超出当前轮次的持久性长期工作,请使用:

  • cronjob(action=create)——安排单独的 Agent 运行;不受父 Agent 轮次中断影响。
  • terminal(background=True, notify_on_complete=True)——在 Agent 执行其他操作时继续运行的长期 shell 命令。

关键属性

  • 每个子 Agent 都有其独立的终端会话(与父 Agent 分开)
  • 嵌套委派是可选的——只有 role="orchestrator" 的子 Agent 才能进一步委派,且仅在 max_spawn_depth 从默认值 1(扁平)提升后才有效。可通过 orchestrator_enabled: false 全局禁用。
  • 叶子子 Agent 无法调用:delegate_taskclarifymemorysend_messageexecute_code。编排器子 Agent 保留 delegate_task,但仍不能使用其他四个。
  • 中断传播——中断父 Agent 会中断所有活跃的子 Agent(包括编排器下的孙 Agent)
  • 只有最终摘要进入父 Agent 的上下文,保持令牌使用效率
  • 子 Agent 继承父 Agent 的 API 密钥、提供商配置和凭证池(支持速率限制时的密钥轮换)

委派 vs execute_code

因素delegate_taskexecute_code
推理完整 LLM 推理循环仅 Python 代码执行
上下文全新独立的对话无对话,仅脚本
工具访问所有未阻止工具加推理通过 RPC 使用 7 个工具,无推理
并行性默认 3 个并发子 Agent(可配置)单一脚本
最适合需要判断的复杂任务机械式多步骤流水线
令牌成本较高(完整 LLM 循环)较低(仅返回 stdout)
用户交互无(子 Agent 无法澄清)

经验法则: 当子任务需要推理、判断或多步骤问题解决时,使用 delegate_task。当需要机械式数据处理或脚本化工作流时,使用 execute_code

配置

# In ~/.hermes/config.yaml
delegation:
max_iterations: 50 # Max turns per child (default: 50)
# max_concurrent_children: 3 # Parallel children per batch (default: 3)
# max_spawn_depth: 1 # Tree depth (1-3, default 1 = flat). Raise to 2 to allow orchestrator children to spawn leaves; 3 for three levels.
# orchestrator_enabled: true # Disable to force all children to leaf role.
model: "google/gemini-3-flash-preview" # Optional provider/model override
provider: "openrouter" # Optional built-in provider

# Or use a direct custom endpoint instead of provider:
delegation:
model: "qwen2.5-coder"
base_url: "http://localhost:1234/v1"
api_key: "local-key"
提示

Agent 会根据任务复杂度自动处理委派。你无需明确要求其进行委派——当有必要时它会自行决定。