> 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.2-inbound-message-processing-pipeline.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 14.2 Inbound Message Processing Pipeline

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

***

When a message arrives at the Gateway from an external channel (Telegram, WhatsApp, etc.), it must go through a series of processing steps before reaching the AI Agent. This processing flow is the **Inbound Message Pipeline**, which is responsible for message format unification, sender identity identification, permission filtering, and routing decisions.

## 14.2.1 Message Reception and Normalization

### Chat Type Normalization

Different channels use different naming conventions for message types: Telegram distinguishes between "private" and "group", Discord uses "DM" and "GUILD\_TEXT", Slack uses "im" and "channel". `src/channels/chat-type.ts` unifies these different naming conventions into three standard types:

```typescript
// src/channels/chat-type.ts
export type NormalizedChatType = "direct" | "group" | "channel";

export function normalizeChatType(raw?: string): NormalizedChatType | undefined {
  const value = raw?.trim().toLowerCase();
  if (!value) return undefined;
  if (value === "direct" || value === "dm") return "direct";
  if (value === "group") return "group";
  if (value === "channel") return "channel";
  return undefined;
}
```

| Raw Type        | Normalized Type | Description                                       |
| --------------- | --------------- | ------------------------------------------------- |
| `direct` / `dm` | `"direct"`      | One-to-one private chat                           |
| `group`         | `"group"`       | Multi-person group                                |
| `channel`       | `"channel"`     | Channel (e.g., Discord channel, Telegram channel) |

This normalization allows the Gateway's subsequent logic to handle messages uniformly without needing to care about which specific platform the message came from.

## 14.2.2 Sender Identity Identification

In group scenarios, knowing just which group a message came from is not enough—we also need to know **who** sent the message. `src/channels/sender-identity.ts` provides validation logic for sender identity:

```typescript
// src/channels/sender-identity.ts
export function validateSenderIdentity(ctx: MsgContext): string[] {
  const issues: string[] = [];
  const chatType = normalizeChatType(ctx.ChatType);
  const isDirect = chatType === "direct";

  const senderId = ctx.SenderId?.trim() || "";
  const senderName = ctx.SenderName?.trim() || "";
  const senderUsername = ctx.SenderUsername?.trim() || "";
  const senderE164 = ctx.SenderE164?.trim() || "";

  // Group messages must have sender identity
  if (!isDirect) {
    if (!senderId && !senderName && !senderUsername && !senderE164) {
      issues.push("missing sender identity (SenderId/SenderName/SenderUsername/SenderE164)");
    }
  }

  // E.164 format validation (international phone number standard)
  if (senderE164) {
    if (!/^\+\d{3,}$/.test(senderE164)) {
      issues.push(`invalid SenderE164: ${senderE164}`);
    }
  }

  // Username should not contain @ or whitespace
  if (senderUsername) {
    if (senderUsername.includes("@")) {
      issues.push(`SenderUsername should not include "@": ${senderUsername}`);
    }
    if (/\s/.test(senderUsername)) {
      issues.push(`SenderUsername should not include whitespace: ${senderUsername}`);
    }
  }

  return issues;
}
```

> **Sidebar**: E.164 is the international phone number standard format established by the International Telecommunication Union (ITU), formatted as `+` followed by country code and phone number, for example `+8613812345678` (China) or `+14155551234` (USA). In OpenClaw, the WhatsApp and Signal channels use this format to identify users.

OpenClaw's message context (`MsgContext`) provides four sender identification fields:

| Field            | Description               | Example                                    |
| ---------------- | ------------------------- | ------------------------------------------ |
| `SenderId`       | Platform internal user ID | `123456789` (Telegram), `U0123ABC` (Slack) |
| `SenderName`     | User display name         | `Alice`, `Zhang San`                       |
| `SenderUsername` | Username (without @)      | `alice_dev`, `zhangsan`                    |
| `SenderE164`     | E.164 format phone number | `+8613812345678`                           |

For private messages, sender identity is not required (since there is only one conversation party); but for group messages, at least one identity field is needed, otherwise the Agent cannot distinguish between different group members.

## 14.2.3 Allowlist Matching

For security reasons, OpenClaw does not respond to messages from strangers by default. The `allowFrom` allowlist mechanism controls which users or groups can interact with the Agent.

`src/channels/allowlists/resolve-utils.ts` provides allowlist merging utilities:

```typescript
// src/channels/allowlists/resolve-utils.ts
export function mergeAllowlist(params: {
  existing?: Array<string | number>;
  additions: string[];
}): string[] {
  const seen = new Set<string>();
  const merged: string[] = [];
  const push = (value: string) => {
    const normalized = value.trim();
    if (!normalized) return;
    const key = normalized.toLowerCase();
    if (seen.has(key)) return;  // Deduplication
    seen.add(key);
    merged.push(normalized);
  };
  for (const entry of params.existing ?? []) push(String(entry));
  for (const entry of params.additions) push(entry);
  return merged;
}
```

Each channel's Dock layer defines its own allowlist resolution and formatting logic. For example, WhatsApp needs to normalize numbers to E.164 format, Telegram uses user IDs, Discord uses string form of user IDs.

The allowlist supports the special value `"*"`, which means allowing all users. This is useful for open group bots, but should be used with caution—because it means anyone can consume your LLM quota.

## 14.2.4 @Mention Gating

In groups, an AI assistant should not respond to every message, but only when explicitly @mentioned. `src/channels/mention-gating.ts` implements this gating logic:

```typescript
// src/channels/mention-gating.ts
export type MentionGateParams = {
  requireMention: boolean;       // Whether mention is required
  canDetectMention: boolean;     // Whether the channel can detect mentions
  wasMentioned: boolean;         // Whether actually mentioned
  implicitMention?: boolean;     // Implicit mention (e.g., reply to AI message)
  shouldBypassMention?: boolean; // Whether to bypass mention requirement
};

export function resolveMentionGating(params: MentionGateParams): MentionGateResult {
  const implicit = params.implicitMention === true;
  const bypass = params.shouldBypassMention === true;
  const effectiveWasMentioned = params.wasMentioned || implicit || bypass;
  // Skip message when mention is required, can be detected, and was not mentioned
  const shouldSkip = params.requireMention && params.canDetectMention && !effectiveWasMentioned;
  return { effectiveWasMentioned, shouldSkip };
}
```

The gating logic considers three ways of being "mentioned":

1. **Explicit mention** (`wasMentioned`): User @mentioned the bot in the message
2. **Implicit mention** (`implicitMention`): User replied to a bot message
3. **Bypass mention** (`shouldBypassMention`): Authorized user sent a control command (e.g., `/new`)

`resolveMentionGatingWithBypass()` further handles the scenario where commands bypass the mention requirement:

```typescript
// src/channels/mention-gating.ts
export function resolveMentionGatingWithBypass(
  params: MentionGateWithBypassParams,
): MentionGateWithBypassResult {
  // Bypass condition: in group + mention required + not mentioned + text commands allowed + has control command + authorized
  const shouldBypassMention =
    params.isGroup &&
    params.requireMention &&
    !params.wasMentioned &&
    !(params.hasAnyMention ?? false) &&
    params.allowTextCommands &&
    params.commandAuthorized &&
    params.hasControlCommand;
  return {
    ...resolveMentionGating({ ...params, shouldBypassMention }),
    shouldBypassMention,
  };
}
```

This means that in a group, even without @mentioning the bot, authorized users sending control commands like `/new` or `/reset` will still be processed.

## 14.2.5 Command Gating

`src/channels/command-gating.ts` controls who can execute commands. It works in conjunction with mention gating:

```typescript
// src/channels/command-gating.ts
export function resolveControlCommandGate(params: {
  useAccessGroups: boolean;        // Whether to use access groups
  authorizers: CommandAuthorizer[]; // List of authorizers
  allowTextCommands: boolean;      // Whether to allow text commands
  hasControlCommand: boolean;      // Whether message contains control command
}): { commandAuthorized: boolean; shouldBlock: boolean } {
  const commandAuthorized = resolveCommandAuthorizedFromAuthorizers({
    useAccessGroups: params.useAccessGroups,
    authorizers: params.authorizers,
  });
  // If message contains control command but sender is not authorized, block it
  const shouldBlock = params.allowTextCommands
    && params.hasControlCommand
    && !commandAuthorized;
  return { commandAuthorized, shouldBlock };
}
```

`CommandAuthorizer` is a simple interface:

```typescript
export type CommandAuthorizer = {
  configured: boolean;  // Whether this authorizer is configured
  allowed: boolean;     // Whether current user is allowed
};
```

Multiple authorizers form a chain—as long as one is configured and allows, authorization passes. When `useAccessGroups` is off, the authorization policy is determined by `modeWhenAccessGroupsOff`: `"allow"` means allow all, `"deny"` means deny all, `"configured"` means only check configured authorizers.

***

## Section Summary

The inbound message processing pipeline is the first line of defense for OpenClaw's security and flexibility:

1. **Type normalization**: Unifies message types from different channels into three types: `direct` / `group` / `channel`
2. **Identity identification**: Group messages must carry sender identity, supporting four identification fields (ID / name / username / E.164)
3. **Allowlist filtering**: Rejects messages from strangers by default, explicitly authorizes through `allowFrom` configuration
4. **Mention gating**: Only responds to @mentioned messages in groups, but authorized users' control commands can bypass this
5. **Command gating**: Control commands (e.g., `/new`, `/reset`) require additional authorization checks

This pipeline ensures that only legitimate messages reach the Agent, while providing differentiated processing strategies for different scenarios (private chat / group / channel).
