> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch14-channel-routing-and-message-dispatch/14.4-multi-agent-routing.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 14.4 Multi-Agent Routing

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~300,000 tokens, Output \~24,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In single-agent mode, all messages are handled by the same Agent. However, in real-world scenarios, users may want different channels, accounts, or even different chat partners to be served by different Agents—for example, a "work" Agent handling Slack messages, a "life" Agent handling Telegram messages, and a "coding" Agent specifically handling requests from a particular Discord channel. OpenClaw's **Multi-Agent Routing** mechanism is designed for this purpose.

## 14.4.1 Multi-Agent Configuration: `agents.list[]` and Bindings

The core configuration of multi-agent systems consists of two parts: **agent list** (`agents.list`) and **binding rules** (`bindings`).

### Agent List

The agent list defines which Agents exist in the system and their respective properties. Each Agent can have independent model configuration, skill filters, identity information, and sandbox policies:

```typescript
// src/config/types.agents.ts
export type AgentConfig = {
  id: string;            // Agent unique identifier
  default?: boolean;     // Whether this is the default agent
  name?: string;         // Display name
  workspace?: string;    // Workspace directory
  agentDir?: string;     // Agent state directory
  model?: AgentModelConfig;  // Model configuration (primary + fallback list)
  skills?: string[];     // Skill allowlist (omit = all skills)
  identity?: IdentityConfig; // Identity configuration (name/avatar/theme color)
  groupChat?: GroupChatConfig; // Group chat configuration
  subagents?: {          // Subagent configuration
    allowAgents?: string[];  // List of allowed agent IDs to spawn
    model?: AgentModelConfig; // Default model for subagents
  };
  sandbox?: { ... };     // Sandbox isolation policy
  tools?: AgentToolsConfig;  // Tool permission configuration
};

export type AgentsConfig = {
  defaults?: AgentDefaultsConfig;  // Global default configuration
  list?: AgentConfig[];            // Agent list
};
```

A typical multi-agent configuration example:

```yaml
# openclaw.yaml
agents:
  list:
    - id: home
      default: true
      name: "Home Assistant"
      model: "anthropic/claude-sonnet-4-20250514"
      identity:
        name: "Little Claw"
        emoji: "🏠"
    - id: work
      name: "Work Assistant"
      model:
        primary: "openai/gpt-4o"
        fallbacks: ["anthropic/claude-sonnet-4-20250514"]
      workspace: "~/work-projects"
      identity:
        name: "Work Claw"
        emoji: "💼"
    - id: code
      name: "Coding Assistant"
      model: "anthropic/claude-sonnet-4-20250514"
      skills: ["code-review", "git", "terminal"]
      workspace: "~/dev"
```

### Default Agent Resolution

When the system needs to determine the "default agent", the `resolveDefaultAgentId` function selects according to the following priority:

```typescript
// src/agents/agent-scope.ts
export function resolveDefaultAgentId(cfg: OpenClawConfig): string {
  const agents = listAgents(cfg);
  if (agents.length === 0) {
    return DEFAULT_AGENT_ID;  // "main"
  }
  // Find agents marked with default=true
  const defaults = agents.filter((agent) => agent?.default);
  if (defaults.length > 1) {
    console.warn("Multiple agents marked default=true; using the first entry.");
  }
  const chosen = (defaults[0] ?? agents[0])?.id?.trim();
  return normalizeAgentId(chosen || DEFAULT_AGENT_ID);
}
```

The resolution logic is as follows:

1. If `agents.list` is empty, return the constant `DEFAULT_AGENT_ID` (value is `"main"`)
2. If one or more agents are marked with `default: true`, take the first one
3. If no agents are marked `default`, take the first one in the list
4. Multiple `default: true` triggers a warning but doesn't cause an error

> **Sidebar**: The `normalizeAgentId` function performs trim + lowercase operations on strings, ensuring that `"Home"`, `" home"`, and `"HOME"` are all treated as the same agent ID. This normalization is a common practice in distributed systems to avoid identifier ambiguity.

### Binding Type Definition

Bindings are rules that route messages to specific agents:

```typescript
// src/config/types.agents.ts
export type AgentBinding = {
  agentId: string;      // Target agent ID
  match: {
    channel: string;    // Channel identifier (telegram/slack/discord, etc.)
    accountId?: string; // Account ID (multiple accounts can be configured on the same channel)
    peer?: {            // Peer (chat partner)
      kind: "dm" | "group" | "channel";
      id: string;
    };
    guildId?: string;   // Discord server ID
    teamId?: string;    // Slack workspace ID
  };
};
```

Binding configuration example:

```yaml
# openclaw.yaml
bindings:
  - agentId: work
    match:
      channel: slack
      teamId: "T01234567"
  - agentId: code
    match:
      channel: discord
      guildId: "123456789"
  - agentId: home
    match:
      channel: telegram
      accountId: personal
```

These three bindings mean: messages from Slack workspace `T01234567` are handled by the `work` agent, messages from Discord server `123456789` are handled by the `code` agent, and messages from Telegram `personal` account are handled by the `home` agent.

## 14.4.2 Routing Rules Based on Channel/Account/Peer

Route resolution is the most critical decision point in a multi-agent system. The `resolveAgentRoute` function implements a **multi-level matching** strategy that progressively falls back from the most precise matching conditions to the broadest ones.

### Route Input and Output

The input to route resolution contains complete source information of the message:

```typescript
// src/routing/resolve-route.ts
export type ResolveAgentRouteInput = {
  cfg: OpenClawConfig;
  channel: string;          // Channel identifier
  accountId?: string | null; // Account ID
  peer?: RoutePeer | null;  // Chat peer
  parentPeer?: RoutePeer | null; // Parent peer (for thread inheritance)
  guildId?: string | null;  // Discord server ID
  teamId?: string | null;   // Slack workspace ID
};
```

The route output contains the resolved agent ID and session key:

```typescript
export type ResolvedAgentRoute = {
  agentId: string;          // Agent ID to route to
  channel: string;          // Normalized channel
  accountId: string;        // Normalized account ID
  sessionKey: string;       // Session key (for persistence and concurrency control)
  mainSessionKey: string;   // Main session key (convenience alias)
  matchedBy:                // Matching method (for debugging and logging)
    | "binding.peer"
    | "binding.peer.parent"
    | "binding.guild"
    | "binding.team"
    | "binding.account"
    | "binding.channel"
    | "default";
};
```

### Six-Level Matching Priority

The core of `resolveAgentRoute` is a matching chain with decreasing priority. Here is the complete matching process:

```typescript
// src/routing/resolve-route.ts (simplified)
export function resolveAgentRoute(input: ResolveAgentRouteInput): ResolvedAgentRoute {
  const channel = normalizeToken(input.channel);
  const accountId = normalizeAccountId(input.accountId);
  const peer = input.peer ? { kind: input.peer.kind, id: normalizeId(input.peer.id) } : null;

  // Step 1: Pre-filter — keep only bindings matching channel + accountId
  const bindings = listBindings(input.cfg).filter((binding) => {
    if (!matchesChannel(binding.match, channel)) return false;
    return matchesAccountId(binding.match?.accountId, accountId);
  });

  // Step 2: Match by priority in order
  // Priority 1: Exact peer matching
  if (peer) {
    const peerMatch = bindings.find((b) => matchesPeer(b.match, peer));
    if (peerMatch) return choose(peerMatch.agentId, "binding.peer");
  }

  // Priority 2: Parent peer inheritance (thread scenario)
  if (parentPeer && parentPeer.id) {
    const parentPeerMatch = bindings.find((b) => matchesPeer(b.match, parentPeer));
    if (parentPeerMatch) return choose(parentPeerMatch.agentId, "binding.peer.parent");
  }

  // Priority 3: Discord server (Guild) matching
  if (guildId) {
    const guildMatch = bindings.find((b) => matchesGuild(b.match, guildId));
    if (guildMatch) return choose(guildMatch.agentId, "binding.guild");
  }

  // Priority 4: Slack workspace (Team) matching
  if (teamId) {
    const teamMatch = bindings.find((b) => matchesTeam(b.match, teamId));
    if (teamMatch) return choose(teamMatch.agentId, "binding.team");
  }

  // Priority 5: Account-level matching (exclude wildcards, peers, Guild, Team)
  const accountMatch = bindings.find((b) =>
    b.match?.accountId?.trim() !== "*" &&
    !b.match?.peer && !b.match?.guildId && !b.match?.teamId
  );
  if (accountMatch) return choose(accountMatch.agentId, "binding.account");

  // Priority 6: Channel-level matching (accountId is wildcard "*")
  const anyAccountMatch = bindings.find((b) =>
    b.match?.accountId?.trim() === "*" &&
    !b.match?.peer && !b.match?.guildId && !b.match?.teamId
  );
  if (anyAccountMatch) return choose(anyAccountMatch.agentId, "binding.channel");

  // Fallback: use default agent
  return choose(resolveDefaultAgentId(input.cfg), "default");
}
```

The following table summarizes the six-level matching priority:

| Priority | matchedBy             | Matching Condition                     | Typical Scenario                               |
| -------- | --------------------- | -------------------------------------- | ---------------------------------------------- |
| 1        | `binding.peer`        | channel + accountId + peer (kind + id) | Dedicated agent for specific user/group        |
| 2        | `binding.peer.parent` | channel + accountId + parentPeer       | Thread inherits parent message's agent binding |
| 3        | `binding.guild`       | channel + accountId + guildId          | Discord server-level binding                   |
| 4        | `binding.team`        | channel + accountId + teamId           | Slack workspace-level binding                  |
| 5        | `binding.account`     | channel + accountId (exact)            | Binding by channel account                     |
| 6        | `binding.channel`     | channel + accountId=`*`                | Default agent for entire channel               |
| Fallback | `default`             | No match                               | Use system default agent                       |

### Pre-filtering Mechanism

The first step of the matching chain is not to directly iterate through all bindings, but to perform **pre-filtering**: keep only bindings where both channel and account ID match. This means a binding only enters subsequent fine-grained matching if its `channel` field matches the message's source channel.

Account ID matching has three cases:

1. Binding doesn't specify `accountId` (or is empty)—only matches the default account (`DEFAULT_ACCOUNT_ID`)
2. Binding specifies `accountId: "*"`—matches any account
3. Binding specifies specific `accountId`—exact match

### Thread Inheritance

Priority 2's "parent peer inheritance" is a noteworthy design. In Slack and Discord, users can create threads under messages. If the thread itself doesn't directly match a binding rule, the system checks whether the thread's parent message (parentPeer) matches some binding. This ensures that "threads created under a certain channel" inherit that channel's agent assignment.

### Agent ID Validation

The `choose` helper function calls `pickFirstExistingAgentId`, which validates whether the agent ID referenced in the binding actually exists in `agents.list`:

```typescript
// src/routing/resolve-route.ts
function pickFirstExistingAgentId(cfg: OpenClawConfig, agentId: string): string {
  const normalized = normalizeAgentId(agentId);
  const agents = listAgents(cfg);
  if (agents.length === 0) return sanitizeAgentId(agentId);

  // Find matching agent in agents.list
  const match = agents.find((agent) => normalizeAgentId(agent.id) === normalized);
  if (match?.id?.trim()) return sanitizeAgentId(match.id.trim());

  // If not found, fall back to default agent
  return sanitizeAgentId(resolveDefaultAgentId(cfg));
}
```

If a binding references a non-existent agent ID, the system doesn't error but silently falls back to the default agent. This is a **defensive design**—configuration errors should not prevent messages from being processed.

## 14.4.3 Subagent Registry

In addition to static multi-agent routing, OpenClaw also supports a **dynamic subagent** mechanism: a running Agent can spawn subagents at runtime to execute background tasks, and automatically report results back to the parent agent after completion.

> **Sidebar**: The subagent pattern is similar to the `fork()` + `wait()` pattern in operating systems—a parent process creates child processes to execute specific tasks, and child processes return results to the parent process after completion. In OpenClaw, the parent Agent spawns child Agents through the `sessions_send` tool, and child Agents report results back to the parent Agent's context through an "announce flow" after completion.

### SubagentRunRecord Data Model

The subagent registry is an in-memory `Map<string, SubagentRunRecord>` that tracks all running subagents:

```typescript
// src/agents/subagent-registry.ts
export type SubagentRunRecord = {
  runId: string;               // Run unique identifier
  childSessionKey: string;     // Child agent's session key
  requesterSessionKey: string; // Parent agent's session key
  requesterOrigin?: DeliveryContext;  // Parent agent's delivery context
  requesterDisplayKey: string; // Parent agent display name (for logging)
  task: string;                // Task description
  cleanup: "delete" | "keep"; // Whether to delete child session after completion
  label?: string;              // Optional label
  createdAt: number;           // Creation timestamp
  startedAt?: number;          // Execution start timestamp
  endedAt?: number;            // End timestamp
  outcome?: SubagentRunOutcome; // Execution result
  archiveAtMs?: number;        // Archive expiration time
  cleanupHandled?: boolean;    // Whether cleanup has been handled
  cleanupCompletedAt?: number; // Cleanup completion time
};
```

### Registration and Lifecycle

When a parent Agent calls a tool to spawn a subagent, the `registerSubagentRun` function is called:

```typescript
// src/agents/subagent-registry.ts (simplified)
export function registerSubagentRun(params: {
  runId: string;
  childSessionKey: string;
  requesterSessionKey: string;
  requesterOrigin?: DeliveryContext;
  requesterDisplayKey: string;
  task: string;
  cleanup: "delete" | "keep";
  label?: string;
  runTimeoutSeconds?: number;
}) {
  const now = Date.now();
  const cfg = loadConfig();

  // Calculate archive expiration time (default: can be cleaned after 60 minutes)
  const archiveAfterMs = resolveArchiveAfterMs(cfg);
  const archiveAtMs = archiveAfterMs ? now + archiveAfterMs : undefined;

  // Calculate wait timeout
  const waitTimeoutMs = resolveSubagentWaitTimeoutMs(cfg, params.runTimeoutSeconds);

  // Register to in-memory Map
  subagentRuns.set(params.runId, {
    runId: params.runId,
    childSessionKey: params.childSessionKey,
    // ...other fields
    createdAt: now,
    startedAt: now,
    archiveAtMs,
    cleanupHandled: false,
  });

  // Start event listener
  ensureListener();
  // Persist to disk
  persistSubagentRuns();
  // Start archive cleanup timer
  if (archiveAfterMs) startSweeper();

  // Wait for subagent completion via Gateway RPC
  void waitForSubagentCompletion(params.runId, waitTimeoutMs);
}
```

This function does four critical things:

1. **Register record**—create an entry in the in-memory Map
2. **Start listener**—subscribe to Agent lifecycle events so we can immediately sense when a subagent ends
3. **Persist**—write the registry to disk, supporting recovery after process restart
4. **Async wait**—wait for subagent execution completion via Gateway's `agent.wait` RPC method

### Event Listening and Completion Detection

The registry detects subagent completion through two paths:

**Path 1: In-process lifecycle events**

```typescript
// src/agents/subagent-registry.ts
function ensureListener() {
  if (listenerStarted) return;
  listenerStarted = true;
  listenerStop = onAgentEvent((evt) => {
    if (evt.stream !== "lifecycle") return;
    const entry = subagentRuns.get(evt.runId);
    if (!entry) return;

    if (evt.data?.phase === "start") {
      entry.startedAt = evt.data.startedAt;
      persistSubagentRuns();
      return;
    }
    if (evt.data?.phase === "end" || evt.data?.phase === "error") {
      entry.endedAt = evt.data?.endedAt ?? Date.now();
      entry.outcome = evt.data?.phase === "error"
        ? { status: "error", error: evt.data?.error }
        : { status: "ok" };
      persistSubagentRuns();

      // Trigger announce flow
      beginSubagentCleanup(evt.runId);
      void runSubagentAnnounceFlow({ /* ... */ });
    }
  });
}
```

**Path 2: Cross-process RPC wait**

```typescript
// src/agents/subagent-registry.ts (simplified)
async function waitForSubagentCompletion(runId: string, waitTimeoutMs: number) {
  const wait = await callGateway<{ status?: string; startedAt?: number; endedAt?: number }>({
    method: "agent.wait",
    params: { runId, timeoutMs: waitTimeoutMs },
    timeoutMs: waitTimeoutMs + 10_000,
  });
  if (wait?.status === "ok" || wait?.status === "error") {
    // Update record and trigger announce
    const entry = subagentRuns.get(runId);
    if (entry) {
      entry.endedAt = wait.endedAt ?? Date.now();
      entry.outcome = wait.status === "error"
        ? { status: "error", error: wait.error }
        : { status: "ok" };
      persistSubagentRuns();
      void runSubagentAnnounceFlow({ /* ... */ });
    }
  }
}
```

The reason for the dual-path design is: subagents may run in embedded mode in the same process (path 1 covers this) or in independent processes (path 2 covers this). Only one of the two paths will trigger the announce—the `beginSubagentCleanup` function ensures idempotency through the `cleanupHandled` flag.

### Announce Flow

When a subagent completes, the `runSubagentAnnounceFlow` function is responsible for injecting the result into the parent agent's context:

```typescript
// src/agents/subagent-announce.ts (simplified)
export async function runSubagentAnnounceFlow(params: {
  childSessionKey: string;
  requesterSessionKey: string;
  requesterOrigin?: DeliveryContext;
  task: string;
  cleanup: "delete" | "keep";
  outcome?: SubagentRunOutcome;
  // ...other fields
}): Promise<boolean> {
  // 1. Read the child agent's last reply
  const reply = await readLatestAssistantReply({
    sessionKey: params.childSessionKey,
  });

  // 2. Build statistics
  const statsLine = await buildSubagentStatsLine({
    sessionKey: params.childSessionKey,
    startedAt: params.startedAt,
    endedAt: params.endedAt,
  });

  // 3. Build trigger message
  const triggerMessage = [
    `A background task "${taskLabel}" just ${statusLabel}.`,
    "", "Findings:", reply || "(no output)", "",
    statsLine, "",
    "Summarize this naturally for the user.",
  ].join("\n");

  // 4. Try to queue injection (if parent agent is busy)
  const queued = await maybeQueueSubagentAnnounce({
    requesterSessionKey: params.requesterSessionKey,
    triggerMessage,
    requesterOrigin,
  });
  if (queued !== "none") return true;

  // 5. Send directly to parent agent
  await callGateway({
    method: "agent",
    params: {
      sessionKey: params.requesterSessionKey,
      message: triggerMessage,
      deliver: true,
      // ...channel information
    },
  });

  // 6. Clean up child session (if cleanup="delete")
  if (params.cleanup === "delete") {
    await callGateway({
      method: "sessions.delete",
      params: { key: params.childSessionKey, deleteTranscript: true },
    });
  }
}
```

Key steps in the announce flow:

1. **Read child agent reply**—read the last assistant message from the child session's transcript
2. **Build statistics**—including runtime, token consumption, estimated cost, etc.
3. **Build trigger message**—wrap the child agent's output and statistics into a message sent to the parent agent
4. **Smart injection**—if the parent agent is busy (has an active Agent loop), use a queue mechanism; otherwise send directly
5. **Cleanup**—optionally delete the child agent's session and transcript based on the `cleanup` policy

### Subagent System Prompt

Each subagent receives a dedicated system prompt when created, clearly stating its role and limitations:

```typescript
// src/agents/subagent-announce.ts
export function buildSubagentSystemPrompt(params) {
  return [
    "# Subagent Context",
    "",
    "You are a **subagent** spawned by the main agent for a specific task.",
    "",
    "## Your Role",
    `- You were created to handle: ${params.task}`,
    "- Complete this task. That's your entire purpose.",
    "- You are NOT the main agent. Don't try to be.",
    "",
    "## Rules",
    "1. **Stay focused** - Do your assigned task, nothing else",
    "2. **Complete the task** - Your final message will be automatically reported",
    "3. **Don't initiate** - No heartbeats, no proactive actions",
    "4. **Be ephemeral** - You may be terminated after task completion",
    "",
    "## What You DON'T Do",
    "- NO user conversations (that's main agent's job)",
    "- NO external messages unless explicitly tasked",
    "- NO cron jobs or persistent state",
    // ...
  ].join("\n");
}
```

This system prompt design embodies the "principle of least privilege"—subagents are only authorized to complete their assigned task and cannot initiate heartbeats, proactively contact users, or create persistent state.

### Archival and Cleanup

The registry has a built-in **sweeper** that periodically checks the expiration status of completed subagents:

```typescript
// src/agents/subagent-registry.ts
async function sweepSubagentRuns() {
  const now = Date.now();
  for (const [runId, entry] of subagentRuns.entries()) {
    if (!entry.archiveAtMs || entry.archiveAtMs > now) continue;

    // Expired record: delete child session and remove from registry
    subagentRuns.delete(runId);
    await callGateway({
      method: "sessions.delete",
      params: { key: entry.childSessionKey, deleteTranscript: true },
    });
  }
  if (subagentRuns.size === 0) stopSweeper();
}
```

The sweeper runs every 60 seconds. The default archive expiration time is 60 minutes (configurable via `agents.defaults.subagents.archiveAfterMinutes`). When all subagent records have been cleaned up, the sweeper automatically stops to avoid unnecessary timer overhead.

### Process Restart Recovery

The registry supports persistence to disk and recovery after restart:

```typescript
// src/agents/subagent-registry.ts
function restoreSubagentRunsOnce() {
  if (restoreAttempted) return;
  restoreAttempted = true;

  const restored = loadSubagentRegistryFromDisk();
  for (const [runId, entry] of restored.entries()) {
    if (!subagentRuns.has(runId)) {
      subagentRuns.set(runId, entry);
    }
  }
  // After restoration, continue waiting or announcing
  for (const runId of subagentRuns.keys()) {
    resumeSubagentRun(runId);
  }
}
```

`resumeSubagentRun` checks each restored record: if the subagent has already ended but the announce is not yet complete, immediately trigger the announce; if the subagent is still running, restart the `agent.wait` wait.

### agents.list RPC Method

The Gateway provides an `agents.list` RPC method for clients to query all configured agents:

```typescript
// src/gateway/server-methods/agents.ts
"agents.list": ({ params, respond }) => {
  const cfg = loadConfig();
  const result = listAgentsForGateway(cfg);
  respond(true, result, undefined);
};
```

The `listAgentsForGateway` function collects the agent list and attaches identity information (name, avatar URL, theme color, etc.), returning a structure like:

```typescript
{
  defaultId: string;     // Default agent ID
  mainKey: string;       // Main session key
  scope: SessionScope;   // Session scope
  agents: Array<{
    id: string;
    name?: string;
    identity?: {
      name?: string;
      theme?: string;
      emoji?: string;
      avatar?: string;
      avatarUrl?: string;
    };
  }>;
}
```

Clients (such as the Web console and native applications) obtain the agent list through this RPC method, allowing them to display agent selectors and corresponding identity information in the UI.

***

## Section Summary

1. **Multi-agent configuration** consists of two parts: `agents.list` (agent definitions) and `bindings` (routing rules), with each agent able to have independent model, skill, identity, and sandbox configurations.
2. **Route resolution** uses six-level priority matching—from precise peer matching to channel-level matching, finally falling back to the default agent, ensuring every message finds a handler.
3. **Pre-filtering mechanism** first filters candidate bindings by channel + accountId, then performs fine-grained matching, avoiding irrelevant bindings interfering with routing results.
4. **Subagent registry** manages dynamically spawned subagents, using dual-path completion detection (in-process events + cross-process RPC) to ensure no completion notifications are missed.
5. **Announce flow** automatically injects subagent results into parent agent context, supporting both queued injection (when parent is busy) and direct sending modes.
6. **Persistence and recovery** mechanisms ensure process restarts don't lose subagent state, with archive sweeper automatically reclaiming expired records.

***

> ### 🔬 Going Deeper: 14.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**14.5 Source Deep Dive: Seven Gates on the Inbound Pipeline**](https://www.openclawbook.xyz/en/ch14-channel-routing-and-message-dispatch/14.5-source-deep-dive-seven-inbound-gates.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
