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

# 18.3 Coalescing and Humanized Pacing

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

***

Block streaming solves the problem of "splitting continuous text into appropriately-sized blocks," but there's still a user experience issue—if the Agent rapidly generates multiple short blocks, users receive a barrage of message notifications. **Coalescing** merges multiple blocks produced in a short time into a single message; **Humanized Delay** simulates human typing rhythm, making the Agent's replies less "robotic."

## 18.3.1 Continuous Block Coalescing Strategy: Idle Gap, Min/Max Characters

### Block Emission Control

In `subscribeEmbeddedPiSession`, `emitBlockChunk` is the unified exit for block emission. It performs multiple filters before emitting:

```typescript
// src/agents/pi-embedded-subscribe.ts (simplified)
const emitBlockChunk = (text: string) => {
  if (state.suppressBlockChunks) return;     // Suppressed (final text exists)
  
  // 1. Strip <think>/<final> tags
  const chunk = stripBlockTags(text, state.blockState).trimEnd();
  if (!chunk) return;
  
  // 2. Deduplication: same as last emission → skip
  if (chunk === state.lastBlockReplyText) return;
  
  // 3. Messaging tool deduplication: already sent via messaging tool → skip
  const normalizedChunk = normalizeTextForComparison(chunk);
  if (isMessagingToolDuplicateNormalized(
    normalizedChunk, messagingToolSentTextsNormalized
  )) return;
  
  // 4. Assistant text deduplication: same as recent assistantText → skip
  if (shouldSkipAssistantText(chunk)) return;
  
  // 5. Record and emit
  state.lastBlockReplyText = chunk;
  assistantTexts.push(chunk);
  
  if (!params.onBlockReply) return;
  
  // 6. Parse reply directives (media URLs, audio markers, reply tags)
  const splitResult = replyDirectiveAccumulator.consume(chunk);
  if (!splitResult) return;
  
  void params.onBlockReply({
    text: splitResult.text,
    mediaUrls: splitResult.mediaUrls,
    audioAsVoice: splitResult.audioAsVoice,
    replyToId: splitResult.replyToId,
    replyToCurrent: splitResult.replyToCurrent,
  });
};
```

### Block Boundary Modes

Block boundaries are controlled by the `blockReplyBreak` parameter:

| Mode            | Behavior                             | Use Case                                  |
| --------------- | ------------------------------------ | ----------------------------------------- |
| `"text_end"`    | Flush block on each `text_end` event | Real-time streaming (Telegram draft mode) |
| `"message_end"` | Flush only on `message_end`          | Complete messages (email, SMS)            |

In `text_end` mode, the block chunker is forced to drain each time a text end event is received:

```typescript
// src/agents/pi-embedded-subscribe.handlers.messages.ts
if (evtType === "text_end" && state.blockReplyBreak === "text_end") {
  if (ctx.blockChunker?.hasBuffered()) {
    ctx.blockChunker.drain({ force: true, emit: ctx.emitBlockChunk });
    ctx.blockChunker.reset();
  } else if (ctx.state.blockBuffer.length > 0) {
    ctx.emitBlockChunk(ctx.state.blockBuffer);
    ctx.state.blockBuffer = "";
  }
}
```

### Forced Flush Before Tool Execution

When a tool starts executing, any buffered text blocks must be flushed first—ensuring users see all of the Agent's textual explanation before seeing tool operations:

```typescript
// src/agents/pi-embedded-subscribe.handlers.tools.ts
export async function handleToolExecutionStart(ctx, evt) {
  // Flush pending text blocks
  ctx.flushBlockReplyBuffer();
  if (ctx.params.onBlockReplyFlush) {
    void ctx.params.onBlockReplyFlush();
  }
  // ...subsequent tool handling
}
```

### Message Boundary Reset

When each new assistant message starts, all block state is reset:

```typescript
// Triggered by message_start event
const resetAssistantMessageState = (nextAssistantTextBaseline: number) => {
  state.deltaBuffer = "";
  state.blockBuffer = "";
  blockChunker?.reset();
  state.blockState.thinking = false;
  state.blockState.final = false;
  state.lastBlockReplyText = undefined;
  state.suppressBlockChunks = false;
  state.assistantMessageIndex += 1;
  state.assistantTextBaseline = nextAssistantTextBaseline;
};
```

## 18.3.2 Humanized Delay: `natural` / `custom` Mode

In section 9.3 we mentioned `resolveHumanDelayConfig`, which returns the humanized delay configuration. At the message sending layer, this delay is applied to the emission interval of block replies.

### Configuration

```yaml
agents:
  defaults:
    humanDelay:
      mode: "typing"     # Show "typing" status
      minMs: 500          # Minimum delay
      maxMs: 3000         # Maximum delay
```

### How It Works

Humanized delay is not implemented inside `subscribeEmbeddedPiSession`—it's applied at the **message sending layer** (such as Telegram bot adapter, Signal adapter). When the `onBlockReply` callback is triggered, the adapter:

1. Sends a "typing" status indicator
2. Waits for a random delay time (between `minMs` and `maxMs`)
3. Sends the actual message content

This design decouples the internal mechanism of streaming (`subscribeEmbeddedPiSession`) from its external presentation (channel adapter)—internally it always processes as fast as possible, with delays added by the outer layer as needed.

### Buffer Reset During Compaction

When auto compaction is triggered, all buffered blocks and state must be cleared:

```typescript
const resetForCompactionRetry = () => {
  assistantTexts.length = 0;    // Clear assistant texts
  toolMetas.length = 0;         // Clear tool metadata
  toolMetaById.clear();
  state.lastToolError = undefined;
  messagingToolSentTexts.length = 0;  // Clear deduplication records
  resetAssistantMessageState(0);       // Reset block state
};
```

This ensures that the retry after compaction starts from a completely clean state—users won't see partial text from before compaction immediately followed by new text after compaction.

***

## Section Summary

1. **Block emission** (`emitBlockChunk`) performs five-layer filtering before emitting: suppression check, tag stripping, text deduplication, messaging tool deduplication, assistant text deduplication.
2. **Two boundary modes** (`text_end` / `message_end`) adapt to different channel needs—real-time channels prefer frequent flushing, batch channels prefer complete messages.
3. **Flush before tool execution** ensures users receive all explanatory text before seeing tool operations.
4. **Humanized delay** is implemented at the message sending layer (channel adapter), decoupled from internal streaming.
5. **Compaction reset** ensures that after auto compaction, streaming restarts from a clean state.
