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

# 19.3 Outbound Message Adaptation

> **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`)

***

AI agent-generated replies are in standard Markdown format—but different channels have vastly different levels of Markdown support. Telegram supports bold, italic, code blocks, and links; WhatsApp only supports limited formatting marks; Discord supports rich Markdown but has a 2000 character limit. The task of the outbound message adaptation layer is to convert unified Markdown replies into formats that each channel can correctly render.

***

## 19.3.1 Markdown Formatting and Channel Specificity

### Intermediate Representation (IR) Architecture

OpenClaw doesn't write separate Markdown parsers for each channel; instead, it adopts an **Intermediate Representation (IR)** architecture. This is a classic pattern from compiler design:

```
Markdown source text
    │
    ▼ Parse (markdown-it)
MarkdownIR (intermediate representation)
    │
    ├── Render to Telegram format
    ├── Render to Discord format
    ├── Render to WhatsApp format
    └── Render to plain text format
```

> **Sidebar: Intermediate Representation**
>
> In compiler design, intermediate representation is a bridge data structure between source and target languages. Classic compilers (such as LLVM) first compile source code to IR, then generate machine code for different target platforms from IR. This way you need N frontends + M backends, not N×M translators. OpenClaw's Markdown IR follows the same principle: one parser + K channel renderers, not K separate parse + render pipelines.

The `MarkdownIR` data structure is defined in `src/markdown/ir.ts`:

```typescript
// src/markdown/ir.ts
export type MarkdownStyle = "bold" | "italic" | "strikethrough" | "code" | "code_block" | "spoiler";

export type MarkdownStyleSpan = {
  start: number;        // Start position in plain text
  end: number;          // End position in plain text
  style: MarkdownStyle; // Style type
};

export type MarkdownLinkSpan = {
  start: number;
  end: number;
  href: string;         // Link target URL
};

export type MarkdownIR = {
  text: string;                    // Plain text content (no formatting marks)
  styles: MarkdownStyleSpan[];     // List of style spans
  links: MarkdownLinkSpan[];       // List of link spans
};
```

The core idea of IR is to separate **content** from **formatting**: the `text` field stores plain text, while `styles` and `links` arrays record which text ranges have what styles in span form. This "annotation-based" representation is better suited for cross-platform rendering than nested AST—each renderer only needs to know how to convert style spans to the target format's marks.

### Parser: markdown-it

IR construction uses the `markdown-it` library—a high-performance Markdown parser:

```typescript
// src/markdown/ir.ts (simplified)
function createMarkdownIt(options: MarkdownParseOptions): MarkdownIt {
  const md = new MarkdownIt({
    html: false,              // Disable HTML tags (security consideration)
    linkify: options.linkify ?? true,  // Auto-detect URLs
    breaks: false,            // Don't convert newlines to <br>
    typographer: false,       // Don't apply typography beautification
  });
  md.enable("strikethrough");

  // Table support enabled on demand
  if (options.tableMode && options.tableMode !== "off") {
    md.enable("table");
  } else {
    md.disable("table");
  }

  return md;
}
```

### Renderer: Style Mark Mapping

The core of the renderer is `renderMarkdownWithMarkers` (located in `src/markdown/render.ts`), which converts IR to text with channel-specific marks:

```typescript
// src/markdown/render.ts (simplified)
export type RenderStyleMarker = {
  open: string;      // Opening mark
  close: string;     // Closing mark
};

export type RenderStyleMap = Partial<Record<MarkdownStyle, RenderStyleMarker>>;

export function renderMarkdownWithMarkers(ir: MarkdownIR, options: RenderOptions): string {
  // 1. Collect all boundary points from style spans
  // 2. Insert corresponding open/close marks at each boundary
  // 3. Handle nested and overlapping style spans
  // ...
}
```

Comparison of style marks across different channels:

| Style         | Markdown Original | Telegram       | WhatsApp       | Discord        | Plain Text |
| ------------- | ----------------- | -------------- | -------------- | -------------- | ---------- |
| Bold          | `**text**`        | `**text**`     | `*text*`       | `**text**`     | `text`     |
| Italic        | `*text*`          | `_text_`       | `_text_`       | `*text*`       | `text`     |
| Strikethrough | `~~text~~`        | `~~text~~`     | `~text~`       | `~~text~~`     | `text`     |
| Inline code   | `` `code` ``      | `` `code` ``   | `` `code` ``   | `` `code` ``   | `code`     |
| Code block    | ` ```code``` `    | ` ```code``` ` | ` ```code``` ` | ` ```code``` ` | `code`     |

### Table Processing

Markdown tables are one of the hardest elements to render cross-platform. OpenClaw supports three table rendering modes:

```typescript
// src/config/types.base.ts
export type MarkdownTableMode = "off" | "bullets" | "code";
```

| Mode      | Effect                                      | Applicable Channels                   |
| --------- | ------------------------------------------- | ------------------------------------- |
| `off`     | Don't process, keep original Markdown table | Telegram, Discord (native support)    |
| `bullets` | Convert to list format                      | WhatsApp, Signal (no table support)   |
| `code`    | Convert to monospace code block             | Scenarios requiring precise alignment |

Table conversion is handled by the `convertMarkdownTables` function:

```typescript
// src/markdown/tables.ts
export function convertMarkdownTables(markdown: string, mode: MarkdownTableMode): string {
  if (!markdown || mode === "off") return markdown;

  const { ir, hasTables } = markdownToIRWithMeta(markdown, {
    tableMode: mode,
    // ...
  });
  if (!hasTables) return markdown;    // Fast path: no tables, no processing

  return renderMarkdownWithMarkers(ir, {
    styleMarkers: MARKDOWN_STYLE_MARKERS,
    escapeText: (text) => text,
    // ...
  });
}
```

### Correct Handling of Nested Styles

The renderer must correctly handle nested and overlapping styles. For example, `**bold _bold-italic_ bold**` contains nested bold and italic. `renderMarkdownWithMarkers` uses **stack-based state management**:

```typescript
// src/markdown/render.ts (simplified)
// Unified stack, tracking closing marks and end positions
const stack: { close: string; end: number }[] = [];

for (const pos of boundaryPoints) {
  // Close all styles that end at current position (LIFO order)
  while (stack.length && stack[stack.length - 1]?.end === pos) {
    out += stack.pop().close;
  }

  // Open new styles at current position (sorted by end position descending, outer first)
  for (const item of openingItems) {
    out += item.open;
    stack.push({ close: item.close, end: item.end });
  }

  // Output text from current position to next boundary
  out += escapeText(text.slice(pos, nextPos));
}
```

This stack ensures closing marks are inserted in LIFO (Last In First Out) order—outer styles open first and close last, inner styles open last and close first. This matches HTML/XML nesting rules.

***

## 19.3.2 Reply Prefix

### Dynamic Prefix Injection

OpenClaw supports injecting a **response prefix** at the beginning of AI replies—a configurable template text, typically containing agent name, model used, and other information. This feature is implemented through `src/channels/reply-prefix.ts`:

```typescript
// src/channels/reply-prefix.ts (simplified)
export type ResponsePrefixContext = {
  identityName: string;          // Agent identity name
  provider?: string;             // Model provider (e.g., "anthropic")
  model?: string;                // Model short name (e.g., "opus-4")
  modelFull?: string;            // Full model name (e.g., "anthropic/claude-opus-4")
  thinkingLevel?: string;        // Thinking level (e.g., "off", "medium")
};

export function createReplyPrefixContext(params: {
  cfg: OpenClawConfig;
  agentId: string;
  channel?: string;
  accountId?: string;
}): ReplyPrefixContextBundle {
  const prefixContext: ResponsePrefixContext = {
    identityName: resolveIdentityName(cfg, agentId),
  };

  const onModelSelected = (ctx: ModelSelectionContext) => {
    // Directly modify object (not reassign), ensuring closures see updates
    prefixContext.provider = ctx.provider;
    prefixContext.model = extractShortModelName(ctx.model);
    prefixContext.modelFull = `${ctx.provider}/${ctx.model}`;
    prefixContext.thinkingLevel = ctx.thinkLevel ?? "off";
  };

  return {
    prefixContext,
    responsePrefix: resolveEffectiveMessagesConfig(cfg, agentId, {
      channel: params.channel,
      accountId: params.accountId,
    }).responsePrefix,
    responsePrefixContextProvider: () => prefixContext,
    onModelSelected,
  };
}
```

### Lazy Binding Pattern

Note the design of the `onModelSelected` callback—it populates `provider`, `model`, and other fields only after the model is selected. This is because:

1. The reply prefix template needs to be prepared **before dispatch starts**
2. But the model used is determined **after routing and failover** (see Chapter 16)
3. Therefore, a "create context object first, populate model info later" **lazy binding** pattern is adopted

```
dispatchReply starts
    │
    ▼
createReplyPrefixContext()          ← Create empty prefix context
    │ prefixContext = { identityName: "Aria" }
    ▼
Model selection & failover
    │
    ▼
onModelSelected(ctx)                ← Callback populates model info
    │ prefixContext.model = "opus-4"
    ▼
Render reply prefix template
    │ "Aria (opus-4): "
    ▼
Concatenate to reply text front
```

There's a subtle but important implementation detail here: `onModelSelected` updates the context by **directly modifying object properties** (not reassigning the reference). This ensures all closures holding that object reference see the updates—if using `prefixContext = { ...newData}` style reassignment, old closures would still reference the old object.

***

## 19.3.3 Conversation Label

### Purpose of Conversation Label

Conversation label is a human-readable string used to identify the "identity" of the current conversation. It appears in system prompts, helping the AI agent understand "who am I talking to".

```typescript
// src/channels/conversation-label.ts (simplified)
export function resolveConversationLabel(ctx: MsgContext): string | undefined {
  // 1. Explicit label takes priority
  const explicit = ctx.ConversationLabel?.trim();
  if (explicit) return explicit;

  // 2. Thread label comes next
  const threadLabel = ctx.ThreadLabel?.trim();
  if (threadLabel) return threadLabel;

  // 3. Direct message: use sender name
  const chatType = normalizeChatType(ctx.ChatType);
  if (chatType === "direct") {
    return ctx.SenderName?.trim() || ctx.From?.trim() || undefined;
  }

  // 4. Group chat: use group name + optional ID suffix
  const base = ctx.GroupChannel?.trim()
    || ctx.GroupSubject?.trim()
    || ctx.GroupSpace?.trim()
    || ctx.From?.trim()
    || "";
  if (!base) return undefined;

  // For pure numeric IDs or WhatsApp group JIDs, append id suffix
  const id = extractConversationId(ctx.From);
  if (id && shouldAppendId(id) && base !== id && !base.includes(id)) {
    return `${base} id:${id}`;
  }

  return base;
}
```

### Label Resolution Priority

Resolution follows decreasing order of explicitness:

| Priority | Source                                                     | Example                   |
| -------- | ---------------------------------------------------------- | ------------------------- |
| 1        | `ConversationLabel` (explicitly set)                       | `"Product Discussion"`    |
| 2        | `ThreadLabel` (thread label)                               | `"#general / bug-report"` |
| 3        | Direct message: `SenderName` or `From`                     | `"Zhang San"`             |
| 4        | Group chat: `GroupChannel` / `GroupSubject` / `GroupSpace` | `"Product Team"`          |

### Intelligent ID Suffix Appending

For group chat labels, the function intelligently determines whether to append an ID suffix:

```typescript
// src/channels/conversation-label.ts
function shouldAppendId(id: string): boolean {
  if (/^[0-9]+$/.test(id)) return true;       // Pure numeric ID (e.g., Telegram group)
  if (id.includes("@g.us")) return true;       // WhatsApp group JID
  return false;
}
```

But not all cases append. The following scenarios skip appending:

```typescript
// Already contains ID → no duplication
if (base.includes(id)) return base;

// Already has "id:" annotation → no duplication
if (base.toLowerCase().includes(" id:")) return base;

// Starts with # or @ (e.g., Discord channel name) → already unique identifier
if (base.startsWith("#") || base.startsWith("@")) return base;
```

These rules ensure labels have sufficient information (AI can distinguish different conversations) without being overly redundant.

### Label Usage in System Prompt

Conversation labels are ultimately injected into the system prompt, helping the AI agent understand conversation context. For example:

```
You are chatting with "Zhang San (+8613812345678)" via WhatsApp direct message.
```

Or in group chat scenarios:

```
You are in the "Product Team id:120363012345678901@g.us" WhatsApp group.
Current speaker is "Zhang San".
```

This enables the AI agent to distinguish different conversations and maintain correct context in concurrent multi-conversation scenarios.

***

## Summary of This Section

1. **Markdown IR architecture** adopts the compiler intermediate representation pattern, decoupling parsing and rendering—one parser + K channel renderers, avoiding N×M combinatorial explosion.
2. **Style mark mapping** allows each channel to render the same IR with its own format marks (e.g., WhatsApp uses `*` for bold instead of `**`).
3. **Table conversion** supports three modes (off/bullets/code), adapting to different channels' table support levels.
4. **Reply prefix** uses lazy binding pattern—create context object first, populate model info via callback after model selection, ensuring closure reference consistency.
5. **Conversation label** resolves by four-level priority (explicit > thread > direct sender > group name), intelligently appending ID suffix for uniqueness.
6. The outbound message adaptation layer is the "last mile" format conversion—ensuring AI-generated standard Markdown renders correctly and beautifully on every channel.

***

> ### 🔬 Going Deeper: 19.4 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: [**19.4 Source Deep Dive: The ChannelPlugin Contract and Dual Registries**](https://www.openclawbook.xyz/en/ch19-channel-adapter-abstraction/19.4-source-deep-dive-channelplugin-contract-and-dual-registries.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.**
