> 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/ch18-streaming-and-block-replies/18.5-reply-shaping-and-suppression.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 18.5 Reply Shaping and Suppression

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

***

Raw text produced by the model cannot be sent directly to users. In the final stage of the "streaming → chunking → sending" pipeline, OpenClaw must complete a series of **reply shaping** operations: filter silent tokens, remove duplicate messages, inline tool execution summaries into the conversation. These operations together ensure that users receive messages that are both clean and complete.

***

## 18.5.1 `NO_REPLY` Silent Token Filtering

### Problem Background

In certain scenarios, an AI agent "hears" a message but doesn't need to reply—for example, conversations between others in a group chat, heartbeat detection, or when user-set auto-reply conditions aren't met. The model is still invoked (to maintain context continuity), but the text it produces should be **completely discarded** and not sent to users.

OpenClaw implements this mechanism using a special **silent reply token**.

### Token Definition

The silent token is defined in `src/auto-reply/tokens.ts`, extremely concisely:

```typescript
// src/auto-reply/tokens.ts
export const HEARTBEAT_TOKEN = "HEARTBEAT_OK";
export const SILENT_REPLY_TOKEN = "NO_REPLY";
```

The system prompt guides the model: when no reply is needed, just output `NO_REPLY`. Similarly, `HEARTBEAT_OK` is used for heartbeat scenarios—periodic checks that the AI is still running normally.

### Detection Logic

The `isSilentReplyText` function determines whether a text contains the silent token:

```typescript
// src/auto-reply/tokens.ts
export function isSilentReplyText(
  text: string | undefined,
  token: string = SILENT_REPLY_TOKEN,
): boolean {
  if (!text) return false;

  const escaped = escapeRegExp(token);

  // Check prefix position: text starts with NO_REPLY (allow leading whitespace)
  const prefix = new RegExp(`^\\s*${escaped}(?=$|\\W)`);
  if (prefix.test(text)) return true;

  // Check suffix position: text ends with NO_REPLY
  const suffix = new RegExp(`\\b${escaped}\\b\\W*$`);
  return suffix.test(text);
}
```

This detection function has two key points:

1. **Dual-position detection**: Checks not only the beginning but also the end of text. This is because some models might add spaces, punctuation, or newlines before or after `NO_REPLY`.
2. **Word boundary awareness**: Uses `\b` (word boundary) and `\W` (non-word character) to avoid false matches—for example, `NO_REPLY_NEEDED` won't be treated as a silent token.

> **Sidebar: Word Boundary `\b` in Regular Expressions**
>
> In regular expressions, `\b` matches the position between a "word character" and a "non-word character" (without consuming characters). Word characters include letters, digits, and underscore `[a-zA-Z0-9_]`. For example, in the string `"NO_REPLY done"`, `\bNO_REPLY\b` can match `NO_REPLY` because its left side is the string start (equivalent to a boundary) and its right side is a space (non-word character). But `\bNO_REPLY\b` won't match `NO_REPLY` in `"NO_REPLY_NEEDED"` because the `_` to the right of `Y` is a word character, not forming a boundary.

### Application in Reply Directive Parsing

Silent token detection is integrated into the `parseReplyDirectives` function, the core entry point for reply processing:

```typescript
// src/auto-reply/reply/reply-directives.ts (simplified)
export function parseReplyDirectives(
  raw: string,
  options: { currentMessageId?: string; silentToken?: string } = {},
): ReplyDirectiveParseResult {
  const split = splitMediaFromOutput(raw);       // Separate media URLs
  let text = split.text ?? "";

  const replyParsed = parseInlineDirectives(text, {
    currentMessageId: options.currentMessageId,
    stripReplyTags: true,                         // Handle [[reply:xxx]] directives
  });
  if (replyParsed.hasReplyTag) {
    text = replyParsed.text;
  }

  // Silent detection
  const silentToken = options.silentToken ?? SILENT_REPLY_TOKEN;
  const isSilent = isSilentReplyText(text, silentToken);
  if (isSilent) {
    text = "";                                    // Clear text, prevent sending
  }

  return {
    text,
    mediaUrls: split.mediaUrls,
    replyToId: replyParsed.replyToId,
    replyToCurrent: replyParsed.replyToCurrent,
    replyToTag: replyParsed.hasReplyTag,
    isSilent,
  };
}
```

In the return value of `parseReplyDirectives`, the `isSilent` flag and cleared `text` work together—upper-layer code naturally skips sending the message when it sees empty text and no media URLs.

The entire silent token handling flow can be summarized as:

```
Model output: "NO_REPLY"
    │
    ▼
parseReplyDirectives()
    ├── splitMediaFromOutput() → text="NO_REPLY", media=[]
    ├── parseInlineDirectives() → no special directives
    └── isSilentReplyText("NO_REPLY") → true
         │
         ▼
    text = ""           // Clear
    isSilent = true     // Mark
    │
    ▼
Upper layer: if (!text && !media) → don't send
```

***

## 18.5.2 Messaging Tool Deduplication

### Problem Background

OpenClaw's AI agent can actively send messages to users or other channels via **messaging tools**—for example, using the `message` tool to send a notification to a Discord channel. The problem is: after the model uses `message(action="send", to="user", content="Hello!")` tool, it often repeats the same content in its final text reply ("Hello!"). Without deduplication, users receive **two identical messages**: one from the tool call, one from the final reply.

### Messaging Tool Identification

First, we need to know which tools are "messaging tools." This is determined by the `isMessagingTool` function:

```typescript
// src/agents/pi-embedded-messaging.ts
const CORE_MESSAGING_TOOLS = new Set(["sessions_send", "message"]);

export function isMessagingTool(toolName: string): boolean {
  if (CORE_MESSAGING_TOOLS.has(toolName)) {
    return true;
  }
  // Channel plugins can also register as messaging tools
  const providerId = normalizeChannelId(toolName);
  return Boolean(providerId && getChannelPlugin(providerId)?.actions);
}
```

There are two core messaging tools:

* `sessions_send`: Send message within session
* `message`: Generic message sending (supports specifying provider, channel, to)

Additionally, any channel plugin that registers `actions` (such as Discord, Slack) is also considered a messaging tool—their tool name itself is the channel ID (such as `discord`, `slack`).

### Send Action Determination

Not all messaging tool calls are "sends"—the `message` tool also supports `read`, `list`, and other actions. Only send actions need deduplication:

```typescript
// src/agents/pi-embedded-messaging.ts (simplified)
export function isMessagingToolSendAction(
  toolName: string,
  args: Record<string, unknown>,
): boolean {
  const action = typeof args.action === "string" ? args.action.trim() : "";

  if (toolName === "sessions_send") return true;  // Always send
  if (toolName === "message") {
    return action === "send" || action === "thread-reply";
  }

  // Channel plugins delegate to the plugin itself
  const plugin = getChannelPlugin(normalizeChannelId(toolName));
  return Boolean(plugin?.actions?.extractToolSend?.({ args })?.to);
}
```

### Tracking and Commit Mechanism

Messaging tool deduplication uses a **"stage first, commit later"** two-phase design. The core consideration is: if the tool call fails, the message wasn't actually sent, so we shouldn't suppress the same text in the final reply.

In `handleToolExecutionStart`, text is staged to `pendingMessagingTexts`:

```typescript
// src/agents/pi-embedded-subscribe.handlers.tools.ts (simplified)
export async function handleToolExecutionStart(ctx, evt) {
  // ...
  if (isMessagingTool(toolName)) {
    const isMessagingSend = isMessagingToolSendAction(toolName, argsRecord);
    if (isMessagingSend) {
      // Extract send target
      const sendTarget = extractMessagingToolSend(toolName, argsRecord);
      if (sendTarget) {
        ctx.state.pendingMessagingTargets.set(toolCallId, sendTarget);
      }
      // Stage message text
      const text = argsRecord.content ?? argsRecord.message;
      if (text && typeof text === "string") {
        ctx.state.pendingMessagingTexts.set(toolCallId, text);
      }
    }
  }
}
```

In `handleToolExecutionEnd`, decide whether to commit or discard based on execution result:

```typescript
// src/agents/pi-embedded-subscribe.handlers.tools.ts (simplified)
export function handleToolExecutionEnd(ctx, evt) {
  const isToolError = Boolean(evt.isError) || isToolResultError(result);

  // Retrieve from staging area
  const pendingText = ctx.state.pendingMessagingTexts.get(toolCallId);
  if (pendingText) {
    ctx.state.pendingMessagingTexts.delete(toolCallId);
    if (!isToolError) {
      // Success: commit to sent list
      ctx.state.messagingToolSentTexts.push(pendingText);
      ctx.state.messagingToolSentTextsNormalized.push(
        normalizeTextForComparison(pendingText)
      );
      ctx.trimMessagingToolSent();
    }
    // Failure: discard directly, don't suppress subsequent reply
  }
}
```

### Text Normalization and Fuzzy Matching

Deduplication comparison is not simple string equality—the model might slightly modify wording in the reply (add emoji, change case, etc.). OpenClaw uses **normalized comparison**:

```typescript
// src/agents/pi-embedded-helpers/messaging-dedupe.ts
const MIN_DUPLICATE_TEXT_LENGTH = 10;

export function normalizeTextForComparison(text: string): string {
  return text
    .trim()
    .toLowerCase()
    .replace(/\p{Emoji_Presentation}|\p{Extended_Pictographic}/gu, "")  // Remove emoji
    .replace(/\s+/g, " ")                                                // Merge whitespace
    .trim();
}

export function isMessagingToolDuplicateNormalized(
  normalized: string,
  normalizedSentTexts: string[],
): boolean {
  if (normalizedSentTexts.length === 0) return false;
  if (!normalized || normalized.length < MIN_DUPLICATE_TEXT_LENGTH) return false;

  return normalizedSentTexts.some((sent) => {
    if (!sent || sent.length < MIN_DUPLICATE_TEXT_LENGTH) return false;
    // Bidirectional substring containment check
    return normalized.includes(sent) || sent.includes(normalized);
  });
}
```

Normalization steps:

| Step             | Input Example           | Output Example  |
| ---------------- | ----------------------- | --------------- |
| Original text    | `" Hello 👋 WORLD 🌍 "` | —               |
| `trim()`         | `"Hello 👋 WORLD 🌍"`   | —               |
| `toLowerCase()`  | `"hello 👋 world 🌍"`   | —               |
| Remove emoji     | `"hello world "`        | —               |
| Merge whitespace | —                       | `"hello world"` |

The matching algorithm uses **bidirectional substring containment** rather than strict equality: if the reply text contains the already-sent tool message text (or vice versa), it's considered a duplicate. This captures the common pattern of the model "quoting" tool message content in its reply.

But note the **10-character minimum length threshold**: very short text (like "ok", "done") doesn't participate in deduplication because it's too generic and prone to false suppression.

### Checkpoints in Block Output

Deduplication checks occur at two critical locations:

1. **`emitBlockChunk`**—when block stream outputs (the BlockChunker output callback introduced in section 10.2):

```typescript
// src/agents/pi-embedded-subscribe.ts (simplified)
const emitBlockChunk = (text: string) => {
  if (state.suppressBlockChunks) return;
  const chunk = stripBlockTags(text, state.blockState).trimEnd();
  if (!chunk) return;

  // Deduplication check
  const normalizedChunk = normalizeTextForComparison(chunk);
  if (isMessagingToolDuplicateNormalized(normalizedChunk, messagingToolSentTextsNormalized)) {
    log.debug(`Skipping block reply - already sent via messaging tool`);
    return;     // Silently discard
  }

  // ...normal output...
  void params.onBlockReply({ text: cleanedText, ... });
};
```

2. **`handleMessageEnd`**—final reply send at message end:

```typescript
// src/agents/pi-embedded-subscribe.handlers.messages.ts (simplified)
// In message_end handling
const normalizedText = normalizeTextForComparison(text);
if (isMessagingToolDuplicateNormalized(normalizedText, ctx.state.messagingToolSentTextsNormalized)) {
  ctx.log.debug(`Skipping message_end block reply - already sent via messaging tool`);
  // Skip sending
} else {
  void onBlockReply({ text: cleanedText, ... });
}
```

These two checkpoints ensure that whether it's streaming chunks or complete message end, duplicate content never leaks to users.

***

## 18.5.3 Tool Summary Inlining

### Problem Background

When an AI agent executes tools (such as reading files, running commands, searching the web), users waiting in channels like Telegram or Discord might wait a long time. To provide better experience, OpenClaw sends **tool summaries**—brief one-line status information telling users "what the agent is doing"—while tools execute.

### Summary Triggering and Format

Tool summaries are triggered in `handleToolExecutionStart`:

```typescript
// src/agents/pi-embedded-subscribe.handlers.tools.ts (simplified)
if (ctx.params.onToolResult && shouldEmitToolEvents && !ctx.state.toolSummaryById.has(toolCallId)) {
  ctx.state.toolSummaryById.add(toolCallId);
  ctx.emitToolSummary(toolName, meta);
}
```

`emitToolSummary` formats tool name and metadata into one readable line via `formatToolAggregate`:

```typescript
// src/agents/pi-embedded-subscribe.ts (simplified)
const emitToolSummary = (toolName?: string, meta?: string) => {
  const agg = formatToolAggregate(toolName, meta ? [meta] : undefined, {
    markdown: useMarkdown,
  });
  void params.onToolResult({ text: cleanedText, ... });
};
```

### Formatting Logic of `formatToolAggregate`

`formatToolAggregate` (located in `src/auto-reply/tool-meta.ts`) is the formatting core of tool summaries. It maps tool names to emoji + labels and intelligently groups metadata (usually file paths):

```typescript
// src/auto-reply/tool-meta.ts (simplified)
export function formatToolAggregate(
  toolName?: string,
  metas?: string[],
  options?: ToolAggregateOptions,
): string {
  const filtered = (metas ?? []).filter(Boolean).map(shortenMeta);
  const display = resolveToolDisplay({ name: toolName });
  const prefix = `${display.emoji} ${display.label}`;    // e.g., "📖 Read"

  if (!filtered.length) return prefix;

  // Group paths by directory and collapse with braces
  const grouped: Record<string, string[]> = {};
  for (const m of filtered) {
    if (!isPathLike(m)) { rawSegments.push(m); continue; }
    const parts = m.split("/");
    const dir = parts.slice(0, -1).join("/");
    const base = parts.at(-1) ?? m;
    if (!grouped[dir]) grouped[dir] = [];
    grouped[dir].push(base);
  }

  // Multiple files in same directory collapsed with braces
  const segments = Object.entries(grouped).map(([dir, files]) => {
    const brace = files.length > 1 ? `{${files.join(", ")}}` : files[0];
    return dir === "." ? brace : `${dir}/${brace}`;
  });

  return `${prefix}: ${meta}`;
}
```

Example formatted summaries:

| Tool Call                         | Formatted Result                     |
| --------------------------------- | ------------------------------------ |
| `read(path="src/index.ts")`       | `📖 Read: src/index.ts`              |
| `exec(cmd="npm test", pty=true)`  | `⚡ Exec: pty · npm test`             |
| `read` multiple files in same dir | `📖 Read: src/{index.ts, config.ts}` |
| `message(action="send")`          | `💬 Message: send`                   |

Brace collapse is common path abbreviation syntax in shells—when multiple files are in the same directory, use `{file1, file2}` instead of listing individually, making summaries more compact.

### Path Shortening

File paths in metadata are processed by `shortenMeta` and `shortenHomePath`, replacing user home directory with `~`:

```typescript
// src/auto-reply/tool-meta.ts
export function shortenMeta(meta: string): string {
  const colonIdx = meta.indexOf(":");
  if (colonIdx === -1) return shortenHomeInString(meta);
  const base = meta.slice(0, colonIdx);
  const rest = meta.slice(colonIdx);
  return `${shortenHomeInString(base)}${rest}`;
}
```

This means `/Users/john/projects/app/src/index.ts` displays as `~/projects/app/src/index.ts`—preserving enough path information while not exposing system usernames or wasting message space.

### Tool Display Configuration

`resolveToolDisplay` (located in `src/agents/tool-display.ts`) looks up display information for each tool from a JSON config file `tool-display.json`:

```typescript
// src/agents/tool-display.ts (simplified)
export function resolveToolDisplay(params: {
  name?: string; args?: unknown; meta?: string;
}): ToolDisplay {
  const key = normalizeToolName(params.name).toLowerCase();
  const spec = TOOL_MAP[key];             // Look up from JSON config
  const emoji = spec?.emoji ?? "🧩";      // Default emoji
  const title = spec?.title ?? defaultTitle(name);
  const label = spec?.label ?? title;

  // Some tools have action-specific labels
  const actionSpec = resolveActionSpec(spec, action);
  const verb = normalizeVerb(actionSpec?.label ?? action);

  return { name, emoji, title, label, verb, detail };
}
```

This design completely decouples tool **functional identity** from **display presentation**—when adding new tools, just add a record in the JSON config without modifying code logic.

### Detailed Output Mode

Besides tool summaries, OpenClaw also supports **tool output inlining**—embedding complete tool execution output in the conversation. This is controlled by `verboseLevel` configuration:

```typescript
// src/agents/pi-embedded-subscribe.ts (simplified)
const shouldEmitToolResult = () =>
  params.verboseLevel === "on" || params.verboseLevel === "full";

const shouldEmitToolOutput = () =>
  params.verboseLevel === "full";
```

| Verbosity | Tool Summary | Tool Output |
| --------- | ------------ | ----------- |
| `off`     | ❌            | ❌           |
| `on`      | ✅            | ❌           |
| `full`    | ✅            | ✅           |

In `full` mode, tool output is sent via `emitToolOutput`:

```typescript
// src/agents/pi-embedded-subscribe.ts (simplified)
const emitToolOutput = (toolName?: string, meta?: string, output?: string) => {
  const agg = formatToolAggregate(toolName, meta ? [meta] : undefined, { markdown: useMarkdown });
  const message = `${agg}\n${formatToolOutputBlock(output)}`;
  void params.onToolResult({ text: cleanedText, ... });
};

const formatToolOutputBlock = (text: string) => {
  const trimmed = text.trim();
  if (!trimmed) return "(no output)";
  if (!useMarkdown) return trimmed;
  return `\`\`\`txt\n${trimmed}\n\`\`\``;      // Wrap in Markdown code block
};
```

This means in `full` mode, users see messages like:

````
📖 Read: src/config.ts
```txt
export const DEFAULT_PORT = 3000;
export const MAX_RETRIES = 3;
// ...
````

```

This is very useful for debugging and teaching scenarios—users can see in real-time what files the AI is reading, what commands it's executing, what results it's getting.

---

## Section Summary

1. **`NO_REPLY` silent token** is a concise "no reply" protocol: model outputs `NO_REPLY`, system detects and clears text, upper layer naturally skips sending. Detection uses dual-position (prefix + suffix) regex matching, compatible with various model output variations.
2. **Messaging tool deduplication** prevents users from receiving duplicate messages. Uses "stage first, commit later" two-phase design—only records sent text after tool execution succeeds. Normalized comparison (remove emoji, merge whitespace, bidirectional substring containment) provides robust fuzzy matching.
3. **Tool summary inlining** provides concise status information while users wait for tool execution via emoji + label + path collapse. Paths automatically shorten (home directory replaced with `~`), files in same directory automatically collapse with braces.
4. **Verbosity levels** (`off`/`on`/`full`) let users choose information density as needed—from complete silence to showing complete tool output.
5. These three mechanisms together form the **final filter for replies**: filter what shouldn't be said (silence), remove what's said repeatedly (deduplication), supplement what should be seen (tool summaries), ensuring clean and complete user experience.

---

> ### 🔬 Going Deeper: 18.6 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: **[18.6 Source Deep Dive: The Serial Outbound Chain and Chunk Aggregation](18.6-Source-Deep-Dive-Outbound-Chain-and-Chunking.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.**
```
