Skip to content

子代理系统

子代理 (Subagent) 系统实现了事件驱动的任务分发与结果回收。

注册表 (subagent-registry.ts)

数据结构:SubagentRunRecord

typescript
{
  runId, childSessionKey, requesterSessionKey,
  requesterOrigin (DeliveryContext),
  task, cleanup ("delete" | "keep"), label,
  createdAt, startedAt, endedAt,
  outcome ({status: "ok"|"error"|"timeout", error?}),
  archiveAtMs, cleanupCompletedAt, cleanupHandled
}

机制

  • 内存 Map + 磁盘持久化 (saveSubagentRegistryToDisk)
  • 生命周期监听: onAgentEvent() 监听 lifecycle 事件 (start/end/error)
  • 跨进程等待: callGateway("agent.wait", {runId, timeoutMs}) 通过 Gateway RPC
  • 启动恢复: restoreSubagentRunsOnce() 重启后从磁盘恢复,resume 未完成的任务
  • 清理: archiveAfterMinutes 配置(默认 60 分钟),sweeper 每 60s 运行

结果通报 (subagent-announce.ts)

流程

  1. 子代理完成 → lifecycle event → beginSubagentCleanup()
  2. runSubagentAnnounceFlow() → 读取子代理最后回复 readLatestAssistantReply()
  3. 格式化结果(包含 duration, token usage, cost)
  4. 通过 Gateway RPC 发送到 requester session
  5. finalizeSubagentCleanup() → 根据 cleanup 策略删除或标记完成

通报队列

subagent-announce-queue.ts 确保通报消息按序发送。

Spawn 机制

子代理 spawn 在 openclaw-tools.ts 中的 sessions_spawn 工具触发:

  • 分配独立 session key (含 subagent: 前缀)
  • 可配置独立 model、thinking level
  • 通过 registerSubagentRun() 注册到注册表
  • 通过 Gateway agent method 实际启动

🦞 雪安的小龙虾 · 每日自动抓取 · 内容有误概不负责