> 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.5-source-deep-dive-seven-inbound-gates.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 14.5 Source Deep Dive: The Seven Gates of the Inbound Pipeline

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~270,000 tokens, Output \~14,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

What actually happens between a message arriving from a channel and the agent starting to run?

The official docs (`docs/concepts/messages.md`) give a four-line summary:

```
Inbound message
  -> routing/bindings -> session key
  -> queue (if a run is active)
  -> agent run (streaming + tools)
  -> outbound replies (channel limits + chunking)
```

In the code each step is much finer. The diagram below is the full chain reconstructed from reading `src/auto-reply/` (34,520 lines) plus `src/routing/`:

```mermaid
flowchart TD
    A[Channel event<br/>Telegram/Discord/WhatsApp...] --> B[Inbound debounce<br/>merge rapid bursts from one sender]
    B --> C[Channel preflight<br/>allowlist / groupPolicy / mention check]
    C -->|group, unmentioned, not a command| X1[drop or store in history buffer]
    C --> D[resolveAgentRoute<br/>seven-level binding match → agentId + sessionKey]
    D --> E[dispatchInboundMessage]
    E --> F[inbound dedupe<br/>channel redelivery]
    F --> G[fast-abort detect /stop]
    G --> H[sendPolicy check<br/>deny = silent block]
    H --> I[getReplyFromConfig]
    I --> J[media/link understanding → command authorization]
    J --> K[session state init<br/>/new /reset detection]
    K --> L[directive parsing<br/>/model /think /queue ...]
    L -->|command returns directly| X2[command reply, no agent]
    L --> M[runPreparedReply<br/>prompt assembly + queue decision]
    M --> N{active run on this session?}
    N -->|no| O[runEmbeddedPiAgent]
    N -->|steer and streaming| P[queueEmbeddedPiMessage<br/>inject into current run]
    N -->|followup/collect| Q[enqueueFollowupRun]
```

This section walks the gates in order.

## 14.5.1 Gate One: Inbound Debounce

Chat users habitually split one thought across three or four messages. Triggering an agent run for each wastes tokens and produces three or four disjointed replies.

OpenClaw merges them **at the channel monitor layer** — before the auto-reply pipeline even starts. The core is the generic debouncer at `src/auto-reply/inbound-debounce.ts:51-128`:

```ts
// src/auto-reply/inbound-debounce.ts:97-125
const enqueue = async (item: T) => {
    const key = params.buildKey(item);
    const debounceMs = resolveDebounceMs(item);
    const canDebounce = debounceMs > 0 && (params.shouldDebounce?.(item) ?? true);

    if (!canDebounce || !key) {
      if (key && buffers.has(key)) {
        await flushKey(key);   // non-debounceable messages flush any existing buffer first, preserving order
      }
      await params.onFlush([item]);
      return;
    }
    const existing = buffers.get(key);
    if (existing) {
      existing.items.push(item);
      existing.debounceMs = debounceMs;
      scheduleFlush(key, existing);  // sliding window: each arrival resets the timer
      return;
    }
```

Three design details:

**1. A sliding window, not a fixed one.** `scheduleFlush` calls `clearTimeout` and re-arms every time (`:87-95`). As long as the user keeps typing, the window keeps extending — until they actually stop.

**2. The debounce key is precise down to "channel + account + conversation + sender."** For Discord it's `discord:${accountId}:${channelId}:${authorId}` (`src/discord/monitor/message-handler.ts:59-73`). **Messages from different people never merge** — two people talking at once in a group must not be stitched into one utterance.

**3. Two message classes bypass debouncing entirely.** `src/channels/inbound-debounce-policy.ts:10-28` is blunt: `hasMedia` returns false immediately, and a `hasControlCommand(text)` hit returns false too.

* **Messages with media** don't merge — the correspondence between image and text would scramble;
* **Control commands** don't merge — `/status` stitched into someone else's prose loses its command semantics.

How do merged messages become one? Discord concatenates the text and constructs a "synthetic message" (`message-handler.ts:113-130`), **using the last message's ID and metadata as the reply-threading anchor** — the reply should hang under the newest message, not the first.

Debounce duration resolution order: caller override > channel-level `messages.inbound.byChannel` > global `debounceMs` > 0. **Off by default**, enabled via configuration.

## 14.5.2 Gate Two: Group Mention Gating

A bot in a group can't answer everything it sees. Each channel monitor calls shared logic during preflight (`src/channels/mention-gating.ts:30-59`):

```ts
// src/channels/mention-gating.ts:30-48
export function resolveMentionGating(params: MentionGateParams): MentionGateResult {
  const implicit = params.implicitMention === true;
  const bypass = params.shouldBypassMention === true;
  const effectiveWasMentioned = params.wasMentioned || implicit || bypass;
  const shouldSkip = params.requireMention && params.canDetectMention && !effectiveWasMentioned;
  return { effectiveWasMentioned, shouldSkip };
}
```

Three input paths feed the decision:

**1. Platform-native mentions** (`wasMentioned`) — Telegram entities, Discord's mention array.

**2. Text pattern matching.** `src/auto-reply/reply/mentions.ts:8-21` **auto-derives a regex** from the agent's `identity.name` / `emoji` (`\b@?Agent\s+Name\b`), and also supports configured `mentionPatterns`.

Before matching it **strips zero-width characters** (`mentions.ts:84-86`) — preventing bypass or interference via invisible characters. That's a real evasion technique: insert U+200B into the middle of the name and it looks identical but stops matching.

**3. Command bypass.**

```ts
// mention-gating.ts:102-108 semantics
even without an @, a control command from a sender with command authority is allowed through
```

This is an operational necessity — an admin typing `/status` in a group shouldn't be required to @ the bot first.

### Where blocked messages go

**Not discarded — into a history buffer** (pending-only).

The next time the bot is genuinely triggered, those unanswered messages are wrapped into the prompt as `[Chat messages since your last reply - for context]`.

**So the agent has continuous group context rather than one isolated @.** The value shows up immediately in real group chats: people discuss something for ten minutes, then @ you asking "what do you think?" — without context you simply can't answer.

Activation mode can be toggled with `/activation mention|always` (`src/auto-reply/group-activation.ts:16-34`), stored on the session entry. On first activation `runPreparedReply` injects a group behavior primer (`get-reply-run.ts:251-265`) telling the model it's in a group and when to stay quiet (reply with the SILENT token).

## 14.5.3 Gate Three: Routing — Which Agent, Which Session

The job of `src/routing/`, entered through `resolveAgentRoute` (`src/routing/resolve-route.ts:614-804`).

### Seven-level binding match

In multi-agent setups, `bindings` maps channels/accounts/groups to specific agents. Matching cascades by priority (`resolve-route.ts:723-781`):

```
binding.peer          exact conversation peer (a specific group or DM)
binding.peer.parent   thread inherits its parent channel's binding
binding.guild+roles   Discord server + roles
binding.guild         Discord server
binding.team          Slack workspace
binding.account       channel account
binding.channel       whole channel (accountPattern "*")
default               nothing matched → default agent
```

**The implementation avoids naive iteration** — this is the hot path every message walks. Three optimizations:

1. Bindings are **pre-compiled into several indexes** by channel + account (`byPeer` / `byGuild` / `byTeam`…, `:214-221`);
2. Backed by a **WeakMap cache keyed on the config object** (`:201-212`) — an unchanged config object reuses the compiled result;
3. The final routing result gets another **4,000-entry LRU cache**.

Using the config object itself as the WeakMap key is elegant: **a hot reload producing a new object invalidates the cache automatically**, with no manual invalidation logic.

### The philosophy of session key construction

The session key is the system's **unit of concurrency, unit of storage, and unit of routing**, formatted `agent:<agentId>:<rest>`:

```ts
// src/routing/session-key.ts:139-173 (excerpt)
const peerKind = params.peerKind ?? "direct";
if (peerKind === "direct") {
    const dmScope = params.dmScope ?? "main";
    // ...
    if (dmScope === "per-account-channel-peer" && peerId) {
      return `agent:${agentId}:${channel}:${accountId}:direct:${peerId}`;
    }
    if (dmScope === "per-channel-peer" && peerId) {
      return `agent:${agentId}:${channel}:direct:${peerId}`;
    }
    if (dmScope === "per-peer" && peerId) {
      return `agent:${agentId}:direct:${peerId}`;
    }
    return buildAgentMainSessionKey({ agentId, mainKey });  // default: collapse into the main session
}
// groups and channels are always isolated
return `agent:${agentId}:${channel}:${peerKind}:${peerId}`;
```

**The default policy has real personality: every DM collapses into one `agent:main:main` session.**

Whether you DM it from Telegram or WhatsApp, you're talking to the same memory.

That fits the "personal assistant" product framing exactly — **one person, many entrances**. You don't want to re-explain something in WhatsApp that you already said in Telegram.

Group chats inherently involve multiple parties and must be isolated by `channel:kind:groupId`.

`dmScope` offers four granularities from "merge everything" to "isolate by channel account + peer." `identityLinks` can additionally map one person's identities across channels to a canonical name (`session-key.ts:176-220`), achieving "switch apps, keep the memory."

Threads add a suffix: `{base}:thread:{threadId}` (`:234-253`). `resolveThreadParentSessionKey` (`src/sessions/session-key-utils.ts:112-132`) can resolve back to the parent session for binding inheritance and context.

> **A trade-off worth flagging**: collapsing all DMs into the main session is a product stance — continuity of context over isolation. The cost is that **if any one channel's allowlist is breached, the attacker can inject content into the main session**; the trust boundary is wider than in per-peer mode. This is consistent with §44.4's single-operator trust model (both assume a trusted operator), but deserves attention when deploying into a multi-person environment.

## 14.5.4 Gate Four: Four Small Gates in the Dispatch Layer

Once a channel monitor has assembled a `MsgContext` it calls `dispatchInboundMessage`; the real orchestration lives in `dispatch-from-config.ts:107-610`. Four gates stand before the agent:

### 1. Inbound redelivery dedupe (`:168-171`)

Channels frequently re-push the same message after a reconnect. `shouldSkipDuplicateInbound` deduplicates with a **20-minute TTL, 5,000-entry cap** cache.

One key detail in key construction (`src/auto-reply/reply/inbound-dedupe.ts:27-33`): **the session dimension is deliberately degraded to `agent:<agentId>`**.

The comment is explicit:

> Even if a routing bug causes the same physical message to appear under both the main key and a direct key, it must never run twice.

That's **defensive redundancy** — not trusting its own upstream routing, and using a coarser granularity as a backstop at the dedupe layer.

### 2. fast-abort (`:278-314`)

Abort directives like `/stop` take a fast path: **call `abortEmbeddedPiRun` immediately to kill the active run and acknowledge, with no queueing at all**.

The reasoning is simple: **a queued "stop" is meaningless.** Executing "stop" after everything ahead of it finishes accomplishes nothing.

### 3. sendPolicy (`:318-338`)

Session- or channel-level send policy. On `deny` it **silently swallows the entire reply flow** — used for "listen only, don't speak" observer sessions.

### 4. Message hooks (`:188-209`)

The `message_received` plugin hook and internal hooks fire **fire-and-forget** and **do not block the main chain**.

That's the right choice: hooks are extension points and shouldn't let one slow plugin drag down all message processing. The cost is that hooks can't veto a message — vetoing requires a different mechanism.

### Also decided here: cross-channel return routing

This layer also determines whether, if a message's `OriginatingChannel` differs from the channel currently processing it (typical with shared sessions), the reply should bypass this channel's dispatcher and go back through `routeReply` to the originating channel (`:218-233`, detailed in §18.6).

## 14.5.5 Gate Five: Command Detection and Authorization

### Detection: permissive in, strict out

`src/auto-reply/command-detection.ts` only does coarse filtering:

```ts
// src/auto-reply/command-detection.ts:74-88
export function hasInlineCommandTokens(text?: string): boolean {
  // ...
  return /(?:^|\s)[/!][a-z]/i.test(body);  // false positives are intentional
}
```

The comment states the intent outright: **"intentionally errs on the side of false positives."**

Why is permissiveness safe here? Because `CommandAuthorized` only determines **whether command semantics get executed**; it doesn't affect ordinary chat replies. A false positive that later fails exact matching is simply treated as an ordinary message — harmless.

`hasControlCommand` (`:10-46`) does exact matching: normalize, then compare against the registry's `textAliases`. **Commands taking arguments additionally require whitespace after the alias** — so `/statusfoo` doesn't falsely match `/status`.

### Authorization: two systems stacked

`resolveCommandAuthorization` (`src/auto-reply/command-auth.ts:258`, in a 389-line file) is the knottiest stretch of the inbound chain, because it supports two generations of configuration simultaneously:

| System     | Rule                                                                                                        |
| ---------- | ----------------------------------------------------------------------------------------------------------- |
| **New**    | `commands.allowFrom` (optionally per-channel). If configured, it **takes over completely** (`:367-378`)     |
| **Legacy** | Channel `allowFrom` + `commands.ownerAllowFrom` derive an owner list, then check whether the sender matches |

Sender identity candidates are ordered deliberately (`:232-238`): **WhatsApp prefers the E164 phone number, other channels prefer the platform ID**.

Additionally, internal channels (webchat / console) whose clients carry the `operator.admin` scope are **treated as owner directly** (`:350-353`) — they already passed Gateway authentication, so by §44.4's trust model they are trusted operators.

The resulting `senderIsOwner` / `isAuthorizedSender` travel all the way into the agent run — **they even determine the default tier for bash elevation** (§22.5.2).

> **Risk note** (already in §45.2): this function interleaves two `allowFrom` systems, three sources of owner, and per-channel candidate-ordering special cases. It is a **high-risk breeding ground for permission bugs**. Audits should look at "multiple rule systems converging" functions first.

## 14.5.6 Gate Six: Prompt Assembly

`getReplyFromConfig` (`src/auto-reply/reply/get-reply.ts:57-403`) is the pipeline's hub, completing in order:

```
model resolution (including heartbeat and channel-level model overrides)
  → workspace preparation
  → media/link understanding (converting images and audio to injectable text)
  → command authorization
  → initSessionState (detect /new, /reset; load the session store)
  → resolveReplyDirectives (parse inline /model /think /verbose /queue)
       ↑ a directive may short-circuit and return a reply on its own
  → handleInlineActions (command execution)
  → stageSandboxMedia
  → runPreparedReply
```

`runPreparedReply` (`get-reply-run.ts:181-556`) turns "what the user typed" into "what the model sees." You can see OpenClaw's **layered view of prompts** here:

| Layer                                 | Contents                                                                                                                                                                                                                                          |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **System side** (`extraSystemPrompt`) | Inbound metadata, group context, first-turn group intro (`:270-275`)                                                                                                                                                                              |
| **User side**                         | Thread context notes (`[Thread history - for context]`), **system event blocks** (`drainFormattedSystemEvents` flushes queued cron/exec completion events into the body, `:350-358`), media notes, untrusted context, and finally the actual body |

### Two versions of the body

An easily-missed but important design: **the body exists in two versions.**

| Version            | Used for                 | Contents                                         |
| ------------------ | ------------------------ | ------------------------------------------------ |
| `prefixedBodyBase` | Immediate execution path | think shortcuts stripped, session hints attached |
| `queuedBody`       | Queued path              | **kept as-is**                                   |

The comments explain why (`:346-358`, `:433-437`): **so that a deferred followup sees the same context it had at enqueue time.**

If queued messages also used the processed version, by the time they actually run (possibly minutes later) the session hints attached back then would be stale.

### An ordering constraint left by a bug fix

If the first word of the body is `low` / `medium` / `high`, it's lifted out as a one-shot thinking-level hint (`:338-345`).

The comment notes specifically: **this step must happen before system events are prepended.**

Otherwise the `System:` prefix takes over `parts[0]` and silently swallows the user's level hint — the user typed `high analyze this for me`, the thinking level didn't apply, and there's no way to tell why.

## 14.5.7 Gate Seven: Model Selection and Fallback Notification

Each run's model passes through several overrides:

```
default model
  → channel/group override (resolveChannelModelOverride)
  → session-level persistent /model override
  → inline /model directive (lifted from the body by src/auto-reply/model.ts:4-51)
  → heartbeat override
```

At runtime `runWithModelFallback` wraps it (§16.5).

`src/auto-reply/fallback-state.ts` maintains a **notification state machine**: it announces only on **the turn where degradation happens** and **the turn where it recovers** (`:61-80`), with state persisted on the session entry.

**No more spamming "you're on the backup model" every single turn.** Another instance of "a few dozen extra lines so the user is slightly less annoyed" (§44.5).

***

## Section Summary

1. **Inbound debounce** merges bursts with a sliding window, keyed precisely to "channel + account + conversation + sender" to prevent crosstalk; **media messages and control commands bypass it entirely**; synthetic messages anchor replies to the **last** message's ID.
2. **Mention gating** decides on three paths (platform-native / regex auto-derived from identity / command bypass), **stripping zero-width characters** before matching; **blocked messages go into a history buffer** and are injected as group context on the next trigger.
3. **Routing uses a seven-level binding cascade**, with three cache tiers on the hot path (pre-compiled indexes + **a WeakMap keyed on the config object** + a 4,000-entry LRU); using the config object as the key makes hot reload invalidate the cache automatically.
4. **The session key collapses all DMs into the main session by default** — "one person, many entrances"; groups stay isolated; `identityLinks` delivers "switch apps, keep the memory." The cost is a wider trust boundary.
5. **Four dispatch gates**: dedupe (**deliberately degraded session dimension — not trusting its own routing**), fast-abort (**a queued "stop" is meaningless**), sendPolicy, and fire-and-forget hooks.
6. **Command detection is permissive in, strict out** (false positives are intentional and harmless); **the authorization function interleaves two generations of systems** and is a high-risk area for permission bugs; internal channels with `operator.admin` are treated as owner directly.
7. **Prompts are layered into system side and user side**; **the body has both an immediate and a queued version** so deferred execution sees the context it had at enqueue time; thinking-level extraction must precede system-event prepending (a fixed bug).
8. **Model degradation notification is a state machine** announcing only on degradation and recovery, not every turn.
