作者:由数入道
五、高级协同模式
1. Ping-Pong 交互模式
当需要代理间多轮对话时,sessions_send 自动支持 ping-pong 循环:
最多 5 轮交互(可配置)任一方回复 REPLY_SKIP 即可终止循环适用于需要澄清或迭代的场景
2. 使用 Lobster 实现确定性工作流
对于需要严格步骤控制和审批的场景,可以结合 Lobster 工具:
定义多步骤管道内置审批检查点可恢复的工作流状态适合替代复杂的代理间协调
- # Lobster
- Lobster is a workflow shell that lets OpenClaw run multi-step tool sequences as a single, deterministic operation with explicit approval checkpoints.
- ## Hook
- Your assistant can build the tools that manage itself. Ask for a workflow,and 30 minutes later you have a CLI plus pipelines that run as one call. Lobster is the missing piece: deterministic pipelines, explicit approvals, and resumable state.
- ## Why
- Today, complex workflows require many back-and-forth tool calls. Each call costs tokens,and the LLM has to orchestrate every step. Lobster moves that orchestration into a typed runtime:-**Onecall instead of many**: OpenClaw runs one Lobster tool call and gets a structured result.
- -**Approvalsbuilt in**: Side effects (send email, post comment) halt the workflow until explicitly approved.
- -**Resumable**: Halted workflows return a token; approve and resume without re-running everything.
复制代码 3. 广播组用于专业团队
如果需要多个代理同时评审同一任务:- {broadcast:{strategy:"parallel","+15555550123":["developer","tester","security-auditor"]}}
复制代码 所有代理会并行处理相同消息,各自提供专业视角。
六、最佳实践建议
1. 隔离性保障
✅ 为每个代理配置独立的工作空间✅ 使用沙箱限制敏感代理的工具访问✅ 配置 sessionToolsVisibility: "spawned" 限制会话可见性
2. 协同效率
✅ 总指挥和项目经理使用更强大的模型(如 Opus)✅ 执行型代理可使用较快的模型(如 Sonnet)✅ 设置合理的 runTimeoutSeconds 避免长时间挂起
3. 错误处理
✅ 检查子代理的 status 字段(success/error/timeout)✅ 使用 sessions_history 查看失败任务的详细日志✅ 配置自动归档清理完成的子代理会话
Notes
关键配置要点:
必须显式启用跨代理通信:tools.agentToAgent.enabled: true 是前提条件,否则代理间消息会被拒绝
会话键格式:子代理使用 agent:<agentId>:subagent:<uuid> 格式,确保完全隔离
认证信息隔离:每个代理的认证配置存储在各自的 ~/.openclaw/agents/<agentId>/agent/auth-profiles.json
工具策略是安全关键:通过 agents.list[].tools.allow/deny 精确控制每个代理的能力边界
宣告机制是异步的:子代理完成后的回报是尽力而为(best-effort),网关重启可能导致宣告丢失
OpenClaw 的这种架构设计使得代理既能保持完全独立(各自的工作空间、会话、权限),又能通过结构化的工具调用实现无缝协同,非常适合您描述的层级化任务委派场景。
Citations
File: /concepts/multi-agent.md- An **agent** is a fully scoped brain with its own:
- - **Workspace** (files, AGENTS.md/SOUL.md/USER.md, local notes, persona rules).
- - **State directory** (`agentDir`) for auth profiles, model registry, and per-agent config.
- - **Session store** (chat history + routing state) under `~/.openclaw/agents/<agentId>/sessions`.
- Auth profiles are **per-agent**. Each agent reads from its own:
复制代码 ~/.openclaw/agents//agent/auth-profiles.json- Main agent credentials are **not** shared automatically. Never reuse `agentDir`
- across agents (it causes auth/session collisions). If you want to share creds,
- copy `auth-profiles.json` into the other agent's `agentDir`.
- Skills are per-agent via each workspace’s `skills/` folder, with shared skills
- available from `~/.openclaw/skills`. See [Skills: per-agent vs shared](/tools/skills#per-agent-vs-shared-skills).
复制代码 File: concepts/multi-agent.md- `~/.openclaw/openclaw.json` (JSON5):
- ```js
- {
- agents: {
- list: [
- {
- id: "home",
- default: true,
- name: "Home",
- workspace: "~/.openclaw/workspace-home",
- agentDir: "~/.openclaw/agents/home/agent",
- },
- {
- id: "work",
- name: "Work",
- workspace: "~/.openclaw/workspace-work",
- agentDir: "~/.openclaw/agents/work/agent",
- },
- ],
- },
- // Deterministic routing: first match wins (most-specific first).
- bindings: [
- { agentId: "home", match: { channel: "whatsapp", accountId: "personal" } },
- { agentId: "work", match: { channel: "whatsapp", accountId: "biz" } },
- // Optional per-peer override (example: send a specific group to work agent).
- {
- agentId: "work",
- match: {
- channel: "whatsapp",
- accountId: "personal",
- peer: { kind: "group", id: "1203630...@g.us" },
- },
- },
- ],
- // Off by default: agent-to-agent messaging must be explicitly enabled + allowlisted.
- tools: {
- agentToAgent: {
- enabled: false,
- allow: ["home", "work"],
- },
- },
- channels: {
- whatsapp: {
- accounts: {
- personal: {
- // Optional override. Default: ~/.openclaw/credentials/whatsapp/personal
- // authDir: "~/.openclaw/credentials/whatsapp/personal",
- },
- biz: {
- // Optional override. Default: ~/.openclaw/credentials/whatsapp/biz
- // authDir: "~/.openclaw/credentials/whatsapp/biz",
- },
- },
- },
- },
- }
复制代码 File: concepts/multi-agent.md- Starting with v2026.1.6, each agent can have its own sandbox and tool restrictions:
- ```js
- {
- agents: {
- list: [
- {
- id: "personal",
- workspace: "~/.openclaw/workspace-personal",
- sandbox: {
- mode: "off", // No sandbox for personal agent
- },
- // No tool restrictions - all tools available
- },
- {
- id: "family",
- workspace: "~/.openclaw/workspace-family",
- sandbox: {
- mode: "all", // Always sandboxed
- scope: "agent", // One container per agent
- docker: {
- // Optional one-time setup after container creation
- setupCommand: "apt-get update && apt-get install -y git curl",
- },
- },
- tools: {
- allow: ["read"], // Only read tool
- deny: ["exec", "write", "edit", "apply_patch"], // Deny others
- },
- },
- ],
- },
- }
- Note: `setupCommand` lives under `sandbox.docker` and runs once on container creation.
- Per-agent `sandbox.docker.*` overrides are ignored when the resolved scope is `"shared"`.
- **Benefits:**
- - **Security isolation**: Restrict tools for untrusted agents
- - **Resource control**: Sandbox specific agents while keeping others on host
- - **Flexible policies**: Different permissions per agent
- Note: `tools.elevated` is **global** and sender-based; it is not configurable per agent.
- If you need per-agent boundaries, use `agents.list[].tools` to deny `exec`.
- For group targeting, use `agents.list[].groupChat.mentionPatterns` so @mentions map cleanly to the intended agent.
- See [Multi-Agent Sandbox & Tools](/tools/multi-agent-sandbox-tools) for detailed examples.
复制代码 File: concepts/session-tool.md- Fetch transcript for one session.
- Parameters:
- - `sessionKey` (required; accepts session key or `sessionId` from `sessions_list`)
- - `limit?: number` max messages (server clamps)
- - `includeTools?: boolean` (default false)
- Behavior:
- - `includeTools=false` filters `role: "toolResult"` messages.
- - Returns messages array in the raw transcript format.
- - When given a `sessionId`, OpenClaw resolves it to the corresponding session key (missing ids error).
复制代码 File: concepts/session-tool.md- Send a message into another session.
- Parameters:
- - `sessionKey` (required; accepts session key or `sessionId` from `sessions_list`)
- - `message` (required)
- - `timeoutSeconds?: number` (default >0; 0 = fire-and-forget)
- Behavior:
- - `timeoutSeconds = 0`: enqueue and return `{ runId, status: "accepted" }`.
- - `timeoutSeconds > 0`: wait up to N seconds for completion, then return `{ runId, status: "ok", reply }`.
- - If wait times out: `{ runId, status: "timeout", error }`. Run continues; call `sessions_history` later.
- - If the run fails: `{ runId, status: "error", error }`.
- - Announce delivery runs after the primary run completes and is best-effort; `status: "ok"` does not guarantee the announce was delivered.
- - Waits via gateway `agent.wait` (server-side) so reconnects don't drop the wait.
- - Agent-to-agent message context is injected for the primary run.
- - After the primary run completes, OpenClaw runs a **reply-back loop**:
- - Round 2+ alternates between requester and target agents.
- - Reply exactly `REPLY_SKIP` to stop the ping‑pong.
- - Max turns is `session.agentToAgent.maxPingPongTurns` (0–5, default 5).
- - Once the loop ends, OpenClaw runs the **agent‑to‑agent announce step** (target agent only):
- - Reply exactly `ANNOUNCE_SKIP` to stay silent.
- - Any other reply is sent to the target channel.
- - Announce step includes the original request + round‑1 reply + latest ping‑pong reply.
复制代码 File: concepts/session-tool.md- Behavior:
- - Starts a new `agent:<agentId>:subagent:<uuid>` session with `deliver: false`.
- - Sub-agents default to the full tool set **minus session tools** (configurable via `tools.subagents.tools`).
- - Sub-agents are not allowed to call `sessions_spawn` (no sub-agent → sub-agent spawning).
- - Always non-blocking: returns `{ status: "accepted", runId, childSessionKey }` immediately.
- - After completion, OpenClaw runs a sub-agent **announce step** and posts the result to the requester chat channel.
- - Reply exactly `ANNOUNCE_SKIP` during the announce step to stay silent.
- - Announce replies are normalized to `Status`/`Result`/`Notes`; `Status` comes from runtime outcome (not model text).
- - Sub-agent sessions are auto-archived after `agents.defaults.subagents.archiveAfterMinutes` (default: 60).
- - Announce replies include a stats line (runtime, tokens, sessionKey/sessionId, transcript path, and optional cost).
复制代码 File: tools/subagents.md- # Sub-agents
- Sub-agents are background agent runs spawned from an existing agent run. They run in their own session (`agent:<agentId>:subagent:<uuid>`) and, when finished, **announce** their result back to the requester chat channel.
- ## Slash command
- Use `/subagents` to inspect or control sub-agent runs for the **current session**:
- - `/subagents list`
- - `/subagents stop <id|#|all>`
- - `/subagents log <id|#> [limit] [tools]`
- - `/subagents info <id|#>`
- - `/subagents send <id|#> <message>`
- `/subagents info` shows run metadata (status, timestamps, session id, transcript path, cleanup).
- Primary goals:
- - Parallelize “research / long task / slow tool” work without blocking the main run.
- - Keep sub-agents isolated by default (session separation + optional sandboxing).
- - Keep the tool surface hard to misuse: sub-agents do **not** get session tools by default.
- - Avoid nested fan-out: sub-agents cannot spawn sub-agents.
- Cost note: each sub-agent has its **own** context and token usage. For heavy or repetitive
- tasks, set a cheaper model for sub-agents and keep your main agent on a higher-quality model.
- You can configure this via `agents.defaults.subagents.model` or per-agent overrides.
复制代码 File: tools/subagents.md- ## Tool
- Use `sessions_spawn`:
- - Starts a sub-agent run (`deliver: false`, global lane: `subagent`)
- - Then runs an announce step and posts the announce reply to the requester chat channel
- - Default model: inherits the caller unless you set `agents.defaults.subagents.model` (or per-agent `agents.list[].subagents.model`); an explicit `sessions_spawn.model` still wins.
- - Default thinking: inherits the caller unless you set `agents.defaults.subagents.thinking` (or per-agent `agents.list[].subagents.thinking`); an explicit `sessions_spawn.thinking` still wins.
- Tool params:
- - `task` (required)
- - `label?` (optional)
- - `agentId?` (optional; spawn under another agent id if allowed)
- - `model?` (optional; overrides the sub-agent model; invalid values are skipped and the sub-agent runs on the default model with a warning in the tool result)
- - `thinking?` (optional; overrides thinking level for the sub-agent run)
- - `runTimeoutSeconds?` (default `0`; when set, the sub-agent run is aborted after N seconds)
- - `cleanup?` (`delete|keep`, default `keep`)
复制代码 File: tools/subagents.md- Allowlist:
- - `agents.list[].subagents.allowAgents`: list of agent ids that can be targeted via `agentId` (`["*"]` to allow any). Default: only the requester agent.
- Discovery:
- - Use `agents_list` to see which agent ids are currently allowed for `sessions_spawn`.
复制代码 File: tools/subagents.md- Auto-archive:
- - Sub-agent sessions are automatically archived after `agents.defaults.subagents.archiveAfterMinutes` (default: 60).
- - Archive uses `sessions.delete` and renames the transcript to `*.deleted.<timestamp>` (same folder).
- - `cleanup: "delete"` archives immediately after announce (still keeps the transcript via rename).
- - Auto-archive is best-effort; pending timers are lost if the gateway restarts.
- - `runTimeoutSeconds` does **not** auto-archive; it only stops the run. The session remains until auto-archive.
复制代码 File: tools/subagents.md- ## Announce
- Sub-agents report back via an announce step:
- - The announce step runs inside the sub-agent session (not the requester session).
- - If the sub-agent replies exactly `ANNOUNCE_SKIP`, nothing is posted.
- - Otherwise the announce reply is posted to the requester chat channel via a follow-up `agent` call (`deliver=true`).
- - Announce replies preserve thread/topic routing when available (Slack threads, Telegram topics, Matrix threads).
- - Announce messages are normalized to a stable template:
- - `Status:` derived from the run outcome (`success`, `error`, `timeout`, or `unknown`).
- - `Result:` the summary content from the announce step (or `(not available)` if missing).
- - `Notes:` error details and other useful context.
- - `Status` is not inferred from model output; it comes from runtime outcome signals.
复制代码 File: channels/broadcast-groups.md- ## Overview
- Broadcast Groups enable multiple agents to process and respond to the same message simultaneously. This allows you to create specialized agent teams that work together in a single WhatsApp group or DM — all using one phone number.
- Current scope: **WhatsApp only** (web channel).
- Broadcast groups are evaluated after channel allowlists and group activation rules. In WhatsApp groups, this means broadcasts happen when OpenClaw would normally reply (for example: on mention, depending on your group settings).
- ## Use Cases
- ### 1. Specialized Agent Teams
- Deploy multiple agents with atomic, focused responsibilities:
- Group: "Development Team"
- Agents:
- - CodeReviewer (reviews code snippets)
- - DocumentationBot (generates docs)
- - SecurityAuditor (checks for vulnerabilities)
- - TestGenerator (suggests test cases)
复制代码 File: channels/broadcast-groups.md- ### Basic Setup
- Add a top-level `broadcast` section (next to `bindings`). Keys are WhatsApp peer ids:
- - group chats: group JID (e.g. `120363403215116621@g.us`)
- - DMs: E.164 phone number (e.g. `+15551234567`)
- ```json
- {
- "broadcast": {
- "120363403215116621@g.us": ["alfred", "baerbel", "assistant3"]
- }
- }
- **Result:** When OpenClaw would reply in this chat, it will run all three agents.
复制代码 File: channels/broadcast-groups.md- ### Session Isolation
- Each agent in a broadcast group maintains completely separate:
- - **Session keys** (`agent:alfred:whatsapp:group:120363...` vs `agent:baerbel:whatsapp:group:120363...`)
- - **Conversation history** (agent doesn't see other agents' messages)
- - **Workspace** (separate sandboxes if configured)
- - **Tool access** (different allow/deny lists)
- - **Memory/context** (separate IDENTITY.md, SOUL.md, etc.)
- - **Group context buffer** (recent group messages used for context) is shared per peer, so all broadcast agents see the same context when triggered
- This allows each agent to have:
- - Different personalities
- - Different tool access (e.g., read-only vs. read-write)
- - Different models (e.g., opus vs. sonnet)
- - Different skills installed
- ### Example: Isolated Sessions
复制代码 File: agents/tools/sessions-send-tool.ts- const SessionsSendToolSchema = Type.Object({
- sessionKey: Type.Optional(Type.String()),
- label: Type.Optional(Type.String({ minLength:1, maxLength:SESSION_LABEL_MAX_LENGTH})),
- agentId: Type.Optional(Type.String({ minLength:1, maxLength:64})),
- message: Type.String(),
- timeoutSeconds: Type.Optional(Type.Number({ minimum:0})),});
复制代码 File: tools/lobster.md- # Lobster
- Lobster is a workflow shell that lets OpenClaw run multi-step tool sequences as a single, deterministic operation with explicit approval checkpoints.
- ## Hook
- Your assistant can build the tools that manage itself. Ask for a workflow, and 30 minutes later you have a CLI plus pipelines that run as one call. Lobster is the missing piece: deterministic pipelines, explicit approvals, and resumable state.
- ## Why
- Today, complex workflows require many back-and-forth tool calls. Each call costs tokens, and the LLM has to orchestrate every step. Lobster moves that orchestration into a typed runtime:
- - **One call instead of many**: OpenClaw runs one Lobster tool call and gets a structured result.
- - **Approvals built in**: Side effects (send email, post comment) halt the workflow until explicitly approved.
- - **Resumable**: Halted workflows return a token; approve and resume without re-running everything.
复制代码 原文地址:https://blog.csdn.net/cxr828/article/details/157825292 |