> 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/ch13-session-management/13.2-session-routing-source-analysis.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 13.2 Session Routing Source Code Analysis

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

***

When a message arrives at the Gateway from a channel, the system must answer two questions: **Which Agent should handle it?** and **Which session should it go into?** This is the core responsibility of session routing. This section will analyze the source code implementation of the routing system file by file.

## 13.2.1 Route Bindings

Route bindings are rules defined by users in the configuration file to map specific channels/accounts/peers to specific Agents. `src/routing/bindings.ts` provides the infrastructure for binding queries.

```typescript
// src/routing/bindings.ts
import type { OpenClawConfig } from "../config/config.js";
import type { AgentBinding } from "../config/types.agents.js";

export function listBindings(cfg: OpenClawConfig): AgentBinding[] {
  return Array.isArray(cfg.bindings) ? cfg.bindings : [];
}
```

A typical binding configuration looks like this:

```json5
// config.json5
{
  "bindings": [
    {
      "agentId": "work-assistant",
      "match": {
        "channel": "slack",
        "accountId": "company-workspace"
      }
    },
    {
      "agentId": "personal",
      "match": {
        "channel": "telegram",
        "peer": { "kind": "dm", "id": "12345" }
      }
    }
  ]
}
```

This means: messages from the Slack company workspace go to the `work-assistant` Agent, and direct messages from Telegram user 12345 go to the `personal` Agent.

The `listBoundAccountIds()` function extracts all bound account IDs under a specific channel:

```typescript
export function listBoundAccountIds(cfg: OpenClawConfig, channelId: string): string[] {
  const normalizedChannel = normalizeBindingChannelId(channelId);
  const ids = new Set<string>();
  for (const binding of listBindings(cfg)) {
    const channel = normalizeBindingChannelId(binding.match?.channel);
    if (channel !== normalizedChannel) continue;
    const accountId = binding.match?.accountId?.trim() ?? "";
    if (!accountId || accountId === "*") continue; // Wildcards don't count
    ids.add(normalizeAccountId(accountId));
  }
  return Array.from(ids).toSorted((a, b) => a.localeCompare(b));
}
```

The `buildChannelAccountBindings()` function builds a nested `Map<channel, Map<agentId, accountId[]>>` structure for efficient subsequent lookups:

```typescript
export function buildChannelAccountBindings(cfg: OpenClawConfig) {
  const map = new Map<string, Map<string, string[]>>();
  for (const binding of listBindings(cfg)) {
    const channelId = normalizeBindingChannelId(binding.match?.channel);
    if (!channelId) continue;
    const accountId = normalizeAccountId(binding.match?.accountId);
    const agentId = normalizeAgentId(binding.agentId);
    // Build channel → agent → accounts mapping
    const byAgent = map.get(channelId) ?? new Map();
    const list = byAgent.get(agentId) ?? [];
    if (!list.includes(accountId)) list.push(accountId);
    byAgent.set(agentId, list);
    map.set(channelId, byAgent);
  }
  return map;
}
```

## 13.2.2 Route Resolution

`src/routing/resolve-route.ts` is the core of the routing system — the `resolveAgentRoute()` function receives message source information and returns the Agent ID and session key that should be used.

### Input and Output Types

```typescript
export type ResolveAgentRouteInput = {
  cfg: OpenClawConfig;
  channel: string;              // Channel identifier (e.g., "telegram", "slack")
  accountId?: string | null;    // Account ID
  peer?: RoutePeer | null;      // Message source (DM/group/channel)
  parentPeer?: RoutePeer | null;// Parent message source for threads
  guildId?: string | null;      // Discord Guild ID
  teamId?: string | null;       // Slack Team ID
};

export type ResolvedAgentRoute = {
  agentId: string;              // Selected Agent
  channel: string;
  accountId: string;
  sessionKey: string;           // Generated session key
  mainSessionKey: string;       // Agent's main session key
  matchedBy: "binding.peer" | "binding.guild" | "binding.account"
    | "binding.channel" | "binding.peer.parent" | "binding.team" | "default";
};
```

The `matchedBy` field records the reason for the route match, which is very valuable for debugging.

### Matching Priority

`resolveAgentRoute()` attempts to match according to a **specific-to-broad** priority:

```typescript
export function resolveAgentRoute(input: ResolveAgentRouteInput): ResolvedAgentRoute {
  // 1. Filter bindings that match channel and account
  const bindings = listBindings(input.cfg).filter((binding) => {
    if (!matchesChannel(binding.match, channel)) return false;
    return matchesAccountId(binding.match?.accountId, accountId);
  });

  const choose = (agentId: string, matchedBy: ...) => {
    const resolvedAgentId = pickFirstExistingAgentId(input.cfg, agentId);
    const sessionKey = buildAgentSessionKey({ ... });
    const mainSessionKey = buildAgentMainSessionKey({ ... });
    return { agentId: resolvedAgentId, channel, accountId, sessionKey, mainSessionKey, matchedBy };
  };

  // Priority 1: Exact peer match (most specific)
  if (peer) {
    const peerMatch = bindings.find((b) => matchesPeer(b.match, peer));
    if (peerMatch) return choose(peerMatch.agentId, "binding.peer");
  }

  // Priority 2: Thread parent peer match (inherit parent message routing)
  if (parentPeer?.id) {
    const parentMatch = bindings.find((b) => matchesPeer(b.match, parentPeer));
    if (parentMatch) return choose(parentMatch.agentId, "binding.peer.parent");
  }

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

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

  // Priority 5: Account match (excluding bindings with more specific conditions)
  const accountMatch = bindings.find((b) =>
    b.match?.accountId?.trim() !== "*" && !b.match?.peer && !b.match?.guildId
  );
  if (accountMatch) return choose(accountMatch.agentId, "binding.account");

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

  // Priority 7: Default Agent
  return choose(resolveDefaultAgentId(input.cfg), "default");
}
```

> **Sidebar**: This **specific-to-broad matching priority** is very common in routing systems. Similar to nginx's `location` matching rules — exact match > prefix match > regex match > default. OpenClaw's routing follows the same principle: peer binding > guild binding > account binding > channel binding > default.

## 13.2.3 Session Key Generation

The final product of route resolution is the session key. The `buildAgentSessionKey()` function generates the appropriate session key based on the routing result:

```typescript
export function buildAgentSessionKey(params: {
  agentId: string;
  channel: string;
  accountId?: string | null;
  peer?: RoutePeer | null;
  dmScope?: "main" | "per-peer" | "per-channel-peer" | "per-account-channel-peer";
  identityLinks?: Record<string, string[]>;
}): string {
  const channel = normalizeToken(params.channel) || "unknown";
  const peer = params.peer;
  return buildAgentPeerSessionKey({
    agentId: params.agentId,
    mainKey: DEFAULT_MAIN_KEY,
    channel,
    accountId: params.accountId,
    peerKind: peer?.kind ?? "dm",
    peerId: peer ? normalizeId(peer.id) || "unknown" : null,
    dmScope: params.dmScope,
    identityLinks: params.identityLinks,
  });
}
```

### Thread Session Keys

For Slack threads, Discord posts, and similar scenarios, `resolveThreadSessionKeys()` appends `:thread:<threadId>` to the base session key:

```typescript
export function resolveThreadSessionKeys(params: {
  baseSessionKey: string;
  threadId?: string | null;
  useSuffix?: boolean;
}): { sessionKey: string; parentSessionKey?: string } {
  const threadId = (params.threadId ?? "").trim();
  if (!threadId) return { sessionKey: params.baseSessionKey };
  const sessionKey = params.useSuffix
    ? `${params.baseSessionKey}:thread:${threadId.toLowerCase()}`
    : params.baseSessionKey;
  return { sessionKey, parentSessionKey: params.parentSessionKey };
}
```

## 13.2.4 Key Mapping Rules

Let's summarize the session keys produced by different message types with concrete examples:

### Direct Messages (DM)

```
dmScope=main:
  Telegram user alice → agent:main:main
  Slack user bob     → agent:main:main  (shared!)

dmScope=per-peer:
  Telegram user alice → agent:main:dm:alice
  Slack user bob     → agent:main:dm:bob

dmScope=per-channel-peer:
  Telegram user alice → agent:main:telegram:dm:alice
  Slack user bob     → agent:main:slack:dm:bob
```

### Group Messages

Group messages are **not affected by dmScope** and always include the channel and group ID:

```
Telegram group 12345    → agent:main:telegram:group:12345
Slack channel C789      → agent:main:slack:channel:c789
Discord channel #general → agent:main:discord:channel:general
```

### Cron Sessions

Scheduled tasks use a special key format:

```
Daily report task       → agent:main:cron:daily-report
Single run             → agent:main:cron:daily-report:run:<uuid>
```

### Thread Sessions

Threads append thread identification to the base key:

```
Thread T456 in Slack channel C789:
  Base key:   agent:main:slack:channel:c789
  Thread key: agent:main:slack:channel:c789:thread:t456
```

***

## Summary of This Section

Session routing is a critical link in OpenClaw's message processing pipeline:

1. **Binding system**: Maps channels/accounts/peers to specific Agents through configuration files
2. **Priority matching**: 7-level matching priority from specific (peer) to broad (default)
3. **Flexible key generation**: Generates unique session keys based on `dmScope`, `identityLinks`, and message type
4. **Thread inheritance**: Thread messages inherit the parent message's route binding, ensuring all messages in the same thread route to the same Agent

The design of the routing system enables OpenClaw to simultaneously serve multiple Agents, multiple channels, and multiple message types in a single Gateway instance, with each message being accurately routed to the correct location.
