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

# 19.2 Inbound Message Normalization

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

***

Different messaging platforms have vastly different message formats: Telegram uses `chat.id` and `from.username`, WhatsApp uses JID (Jabber ID), Discord uses snowflake IDs, and Signal uses E.164 phone numbers. OpenClaw's inbound message pipeline must convert these heterogeneous formats into a unified internal `MsgContext` structure, so that downstream routing, session management, and AI agent processing logic don't need to care about the message source.

***

## 19.2.1 Message Format Unification: Text, Images, Audio, Video, Files

### Unified Message Context: MsgContext

All inbound messages from channels are ultimately converted to the `MsgContext` structure (defined in `src/auto-reply/templating.ts`), which is the "lingua franca" of OpenClaw's internal messages. The core fields of `MsgContext` include:

| Field Category    | Key Fields                                                                    | Description                                |
| ----------------- | ----------------------------------------------------------------------------- | ------------------------------------------ |
| Channel ID        | `Channel`, `AccountId`                                                        | Source channel and account                 |
| Conversation Type | `ChatType`                                                                    | `"direct"` / `"group"` / `"channel"`       |
| Sender            | `From`, `SenderId`, `SenderName`, `SenderUsername`, `SenderE164`              | Multi-dimensional sender identity          |
| Recipient         | `To`                                                                          | Target identifier (usually the bot itself) |
| Message Content   | `Body`, `BodyForAgent`                                                        | Raw text / cleaned text                    |
| Media             | `MediaPath`, `MediaUrl`, `MediaType`, `MediaPaths`, `MediaUrls`, `MediaTypes` | Attachment information                     |
| Reply Context     | `ReplyToId`, `ReplyToBody`, `ReplyToIsQuote`                                  | Referenced message                         |
| Group Info        | `GroupSubject`, `GroupSpace`, `GroupChannel`                                  | Group name, space, channel                 |
| Threading         | `ThreadLabel`, `MessageThreadId`                                              | Thread label and ID                        |
| Session Label     | `ConversationLabel`                                                           | Human-readable label for session routing   |

### Conversation Type Normalization

The first step of inbound message processing is conversation type normalization. Different platforms use different terminology for "private chat" and "group chat":

```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;
}
```

| Platform | Raw Type               | Normalized |
| -------- | ---------------------- | ---------- |
| Telegram | `private`              | `direct`   |
| Telegram | `group` / `supergroup` | `group`    |
| Telegram | `channel`              | `channel`  |
| Discord  | DM                     | `direct`   |
| Discord  | `GUILD_TEXT`           | `channel`  |
| WhatsApp | Private chat           | `direct`   |
| WhatsApp | `@g.us` JID            | `group`    |
| Slack    | DM                     | `direct`   |
| Slack    | `channel` / `group`    | `channel`  |

### Multi-Dimensional Sender Identity Representation

Sender identity is where cross-platform differences are most pronounced. OpenClaw uses multiple complementary fields to represent the same sender:

```typescript
// src/channels/sender-identity.ts (simplified)
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() || "";

  // In group chats, at least one sender identifier must be present
  if (!isDirect) {
    if (!senderId && !senderName && !senderUsername && !senderE164) {
      issues.push("missing sender identity");
    }
  }

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

  // Username should not contain @ symbol
  if (senderUsername && senderUsername.includes("@")) {
    issues.push(`SenderUsername should not include "@"`);
  }

  return issues;
}
```

> **Sidebar: E.164 Format**
>
> E.164 is the international telephone numbering format standard defined by the International Telecommunication Union (ITU), starting with `+` followed by country code and number, maximum 15 digits. For example, `+8613812345678` (Chinese mobile number). Both Signal and WhatsApp identify users using E.164 format.

Different channels provide different field combinations:

| Channel  | SenderId                  | SenderName    | SenderUsername    | SenderE164       |
| -------- | ------------------------- | ------------- | ----------------- | ---------------- |
| Telegram | `12345678`                | `"Zhang San"` | `"zhangsan"`      | —                |
| WhatsApp | `86138...@s.whatsapp.net` | `"Zhang San"` | —                 | `+8613812345678` |
| Discord  | `1234567890123456`        | `"Zhang San"` | `"zhangsan#1234"` | —                |
| Signal   | —                         | `"Zhang San"` | —                 | `+8613812345678` |
| Slack    | `U012AB3CD`               | `"Zhang San"` | `"zhangsan"`      | —                |

The logic for generating sender labels (used for conversation identification in system prompts):

```typescript
// src/channels/sender-label.ts (simplified)
export function resolveSenderLabel(params: SenderLabelParams): string | null {
  const display = name ?? username ?? tag ?? "";
  const idPart = e164 ?? id ?? "";

  if (display && idPart && display !== idPart) {
    return `${display} (${idPart})`;    // "Zhang San (+8613812345678)"
  }
  return display || idPart || null;
}
```

### Channel-Specific Target Normalization

Each channel has its own target ID format, which needs to be normalized to a unified internal format. Taking Telegram and WhatsApp as examples:

```typescript
// src/channels/plugins/normalize/telegram.ts
export function normalizeTelegramMessagingTarget(raw: string): string | undefined {
  let normalized = raw.trim();

  // Remove channel prefix
  if (normalized.startsWith("telegram:")) {
    normalized = normalized.slice("telegram:".length).trim();
  } else if (normalized.startsWith("tg:")) {
    normalized = normalized.slice("tg:".length).trim();
  }

  // Parse t.me links
  const tmeMatch = /^https?:\/\/t\.me\/([A-Za-z0-9_]+)$/i.exec(normalized);
  if (tmeMatch?.[1]) {
    normalized = `@${tmeMatch[1]}`;
  }

  return `telegram:${normalized}`.toLowerCase();
}
```

```typescript
// src/channels/plugins/normalize/whatsapp.ts
export function normalizeWhatsAppMessagingTarget(raw: string): string | undefined {
  return normalizeWhatsAppTarget(raw.trim()) ?? undefined;
}
```

Normalized target IDs uniformly use the `channel:identifier` format (such as `telegram:@username`, `whatsapp:+8613812345678@s.whatsapp.net`), allowing routing and session management to handle them uniformly.

***

## 19.2.2 Media Attachment Processing

### Attachment Parsing Pipeline

When inbound messages contain images, files, and other attachments, OpenClaw processes them through `parseMessageWithAttachments` (located in `src/gateway/chat-attachments.ts`):

```typescript
// src/gateway/chat-attachments.ts (simplified)
export type ChatAttachment = {
  type?: string;
  mimeType?: string;
  fileName?: string;
  content?: unknown;      // base64-encoded content
};

export type ChatImageContent = {
  type: "image";
  data: string;           // base64 data
  mimeType: string;       // e.g., "image/jpeg"
};

export async function parseMessageWithAttachments(
  message: string,
  attachments: ChatAttachment[] | undefined,
  opts?: { maxBytes?: number; log?: AttachmentLog },
): Promise<ParsedMessageWithImages> {
  const maxBytes = opts?.maxBytes ?? 5_000_000;    // 5 MB limit
  if (!attachments || attachments.length === 0) {
    return { message, images: [] };
  }

  const images: ChatImageContent[] = [];

  for (const [idx, att] of attachments.entries()) {
    const label = att.fileName || att.type || `attachment-${idx + 1}`;
    const b64 = extractBase64(att.content);    // Strip Data URL prefix
    validateBase64(b64, label, maxBytes);       // Validate format and size

    // MIME type sniffing
    const providedMime = normalizeMime(att.mimeType);
    const sniffedMime = normalizeMime(await sniffMimeFromBase64(b64));

    // Only accept images
    if (sniffedMime && !isImageMime(sniffedMime)) {
      log?.warn(`attachment ${label}: detected non-image (${sniffedMime}), dropping`);
      continue;
    }

    images.push({
      type: "image",
      data: b64,
      mimeType: sniffedMime ?? providedMime ?? att.mimeType,
    });
  }

  return { message, images };
}
```

This pipeline has several noteworthy design decisions:

1. **Size Limit**: Default 5 MB, preventing oversized files from causing memory overflow.
2. **MIME Type Sniffing**: Don't trust the client's claimed MIME type; instead detect from the actual base64 data header bytes. This prevents type spoofing attacks.
3. **MIME Mismatch Handling**: When sniffing results differ from claimed type, prioritize the sniffed result and log a warning.
4. **Images Only**: Currently only image-type attachments are directly passed to the AI model (since the model's multimodal capabilities primarily support images). Non-image attachments are dropped and logged.

> **Sidebar: MIME Type Sniffing**
>
> MIME (Multipurpose Internet Mail Extensions) type identifies file format, such as `image/jpeg`, `application/pdf`. The MIME type sent by clients may be inaccurate—either mislabeled or maliciously spoofed. MIME sniffing detects the actual type by reading the file's header bytes (magic numbers). For example, JPEG files start with `FF D8 FF`, PNG files with `89 50 4E 47`. OpenClaw uses the `detectMime` function to detect actual MIME type from the first 256 bytes of base64 data.

### Data URL Processing

base64 data may arrive in Data URL format (such as `data:image/jpeg;base64,/9j/4AAQ...`), requiring prefix stripping:

```typescript
// src/gateway/chat-attachments.ts
let b64 = content.trim();
const dataUrlMatch = /^data:[^;]+;base64,(.*)$/.exec(b64);
if (dataUrlMatch) {
  b64 = dataUrlMatch[1];
}
```

### base64 Validation

Parsed base64 data must pass format and size validation:

```typescript
// src/gateway/chat-attachments.ts
// Length must be multiple of 4, containing only valid characters
if (b64.length % 4 !== 0 || /[^A-Za-z0-9+/=]/.test(b64)) {
  throw new Error(`attachment ${label}: invalid base64 content`);
}

const sizeBytes = Buffer.from(b64, "base64").byteLength;
if (sizeBytes <= 0 || sizeBytes > maxBytes) {
  throw new Error(`attachment ${label}: exceeds size limit`);
}
```

> **Sidebar: base64 Encoding**
>
> base64 is a method of encoding binary data as ASCII character strings. It divides every 3 bytes (24 bits) into 4 groups of 6 bits, each group mapped to a printable character (A-Z, a-z, 0-9, +, /), with `=` padding at the end if needed. Therefore, base64 strings must have length divisible by 4, and encoded size is approximately 4/3 of the original data.

***

## 19.2.3 Message Sanitization

### Envelope Stripping

In multi-agent, multi-channel scenarios, messages are wrapped in "envelopes" when forwarded—channel and timestamp markers are prepended. When these messages finally reach the AI model, the envelope must be stripped to avoid interfering with model understanding:

```typescript
// src/gateway/chat-sanitize.ts
const ENVELOPE_PREFIX = /^\[([^\]]+)\]\s*/;
const ENVELOPE_CHANNELS = [
  "WebChat", "WhatsApp", "Telegram", "Signal", "Slack",
  "Discord", "Google Chat", "iMessage", "Teams", "Matrix",
  "Zalo", "Zalo Personal", "BlueBubbles",
];

export function stripEnvelope(text: string): string {
  const match = text.match(ENVELOPE_PREFIX);
  if (!match) return text;

  const header = match[1] ?? "";
  if (!looksLikeEnvelopeHeader(header)) return text;

  return text.slice(match[0].length);
}
```

Envelope detection has two criteria:

1. **Contains timestamp**: Such as `[Telegram 2025-02-18T08:30Z] Hello` → after stripping becomes `Hello`
2. **Starts with channel name**: Such as `[WhatsApp zhangsan] message content` → after stripping becomes `message content`

```typescript
// src/gateway/chat-sanitize.ts
function looksLikeEnvelopeHeader(header: string): boolean {
  // ISO timestamp format
  if (/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(header)) return true;
  // Simplified timestamp format
  if (/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(header)) return true;
  // Starts with known channel name
  return ENVELOPE_CHANNELS.some(label => header.startsWith(`${label} `));
}
```

### Message ID Hint Cleanup

Some messages may contain `[message_id: ...]` annotations used for reply references. These annotations are noise for both human readers and AI, and need to be removed:

```typescript
// src/gateway/chat-sanitize.ts
const MESSAGE_ID_LINE = /^\s*\[message_id:\s*[^\]]+\]\s*$/i;

function stripMessageIdHints(text: string): string {
  if (!text.includes("[message_id:")) return text;    // Fast path

  const lines = text.split(/\r?\n/);
  const filtered = lines.filter(line => !MESSAGE_ID_LINE.test(line));
  return filtered.length === lines.length ? text : filtered.join("\n");
}
```

### Batch Message Sanitization

Sanitization can be applied to entire message history arrays, and only processes messages with user role (`role === "user"`)—assistant and system messages don't need sanitization:

```typescript
// src/gateway/chat-sanitize.ts
export function stripEnvelopeFromMessage(message: unknown): unknown {
  const entry = message as Record<string, unknown>;
  const role = typeof entry.role === "string" ? entry.role.toLowerCase() : "";
  if (role !== "user") return message;    // Only sanitize user messages

  // Handle string content
  if (typeof entry.content === "string") {
    const stripped = stripMessageIdHints(stripEnvelope(entry.content));
    if (stripped !== entry.content) return { ...entry, content: stripped };
  }

  // Handle structured content arrays (Claude API content block format)
  if (Array.isArray(entry.content)) {
    const updated = stripEnvelopeFromContent(entry.content);
    if (updated.changed) return { ...entry, content: updated.content };
  }

  return message;
}
```

Note the handling of the `content` field here, which has two cases:

* **String format**: Directly sanitize the entire string
* **Array format**: Iterate through each content block, only sanitizing blocks with `type === "text"`

This is because the Claude API supports two message formats—simple strings and structured content block arrays. OpenClaw needs to be compatible with both.

### Complete Sanitization Pipeline

```
Inbound message (from Telegram/WhatsApp/Discord/...)
    │
    ▼
Channel adapter: Platform-specific format → MsgContext
    │
    ├── ChatType normalization ("private" → "direct")
    ├── SenderId/SenderName/... population
    ├── Body/BodyForAgent extraction
    └── MediaPath/MediaUrl/... setting
    │
    ▼
Attachment processing: parseMessageWithAttachments()
    │
    ├── base64 validation and size check
    ├── MIME sniffing verification
    └── Non-image attachments dropped
    │
    ▼
Message sanitization: stripEnvelopeFromMessages()
    │
    ├── Envelope prefix stripping
    └── message_id annotation removal
    │
    ▼
Unified MsgContext → Routing / Session Management / AI Agent
```

***

## Summary of This Section

1. **`MsgContext` unified message structure** is the "lingua franca" for all channels, containing channel identification, sender identity, message content, media attachments, reply context, and complete information.
2. **Sender identity uses multi-dimensional representation** (SenderId, SenderName, SenderUsername, SenderE164), adapting to different platforms' identification systems. E.164 format standardizes phone numbers.
3. **Attachment processing pipeline** performs base64 validation, MIME sniffing, and size limits, prioritizing sniffed MIME type over client-claimed type, currently supporting only image attachments for direct AI model processing.
4. **Message sanitization** strips envelope prefixes and message\_id annotations, applying only to user-role messages, avoiding interference with AI model understanding.
5. **Channel-specific target normalization** (such as `telegram:@username`, `whatsapp:+86...@s.whatsapp.net`) unifies heterogeneous ID formats to `channel:identifier` format, providing consistent addressing foundation for downstream routing.
