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

# 18.6 Source Deep Dive: The Outbound Serial Chain and Chunk Coalescing

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~260,000 tokens, Output \~9,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§18.1–18.5 covered streaming architecture, block streaming, coalescing pace, and reply shaping. This section looks at the outbound source: **how three payload types stay ordered, how text is balanced between "split" and "merge," and how cross-channel return routing works.**

## 18.6.1 ReplyDispatcher: Guardian of Outbound Order

A run produces three kinds of payload:

| Type  | Contents         |
| ----- | ---------------- |
| tool  | Tool summaries   |
| block | Streaming blocks |
| final | The final reply  |

They're produced asynchronously, but the user must see them in the correct order. `createReplyDispatcher` (`src/auto-reply/reply/reply-dispatcher.ts:107-211`) strings them onto a single Promise chain:

```ts
// src/auto-reply/reply/reply-dispatcher.ts:108-115
let sendChain: Promise<void> = Promise.resolve();
// Track in-flight deliveries so we can emit a reliable "idle" signal.
// Start with pending=1 as a "reservation" to prevent premature gateway restart.
let pending = 1;
```

Every send task is appended to the tail of `sendChain`, so **outbound messages within one session are strictly ordered**.

### The `pending = 1` "reservation"

A subtle design that's easy to overlook.

The problem: the Gateway wants to know whether outbound work has drained (for safe restarts). The naive approach is treating `pending === 0` as idle.

But there's a window: **before the first message is enqueued the count is already 0** — the Gateway falsely concludes it's idle, restarts, and the message about to go out is lost.

The fix is to **start at 1**, treating that 1 as a reservation. `markComplete` clears the reservation **inside a microtask** (`:183-201`), leaving a window for enqueues in the same tick.

`withReplyDispatcher` in `dispatch.ts:17-33` ensures that **every error path still calls `markComplete` + `waitForIdle`** — otherwise the typing indicator spins forever (§13.6.5's two-signal requirement).

### humanDelay: simulating typing rhythm

Block replies support `humanDelay` between them (**800–2500 ms randomized** by default, `reply-dispatcher.ts:24-41`).

Purely an experience decision — several messages appearing instantaneously reads as a bot flooding the channel; a small gap reads as someone typing.

## 18.6.2 Split and Merge: Two Components Pulling Opposite Ways

Outbound text handling has a pair of components pulling in **opposite directions**, which is the most interesting part of this section.

### `chunk.ts`: splitting

Channels have length limits (default 4000 characters, `src/auto-reply/chunk.ts:24`).

* `chunkByParagraph` **prefers paragraph boundaries** — never cut mid-sentence;
* `parseFenceSpans` (`chunk.ts:7`) ensures **code fences are never split down the middle** — half a code block sent on its own destroys Markdown rendering entirely.

### `block-reply-coalescer.ts`: merging

Streamed text blocks are often too fine-grained — a model may emit only a few characters at a time. Sending each as its own message bombards the user.

`createBlockReplyCoalescer` (`:11-149`) coalesces on three parameters:

| Parameter  | Behavior                                    |
| ---------- | ------------------------------------------- |
| `minChars` | Below this, accumulate                      |
| `idleMs`   | Accumulated but idle too long → force flush |
| `maxChars` | Reached the cap → send immediately          |

The three conditions cover every case: **fast streams cut at maxChars, slow streams are guaranteed by idleMs not to stall, and normal streams stay uncluttered thanks to minChars.**

### Two moments that must break the buffer

* **Media payloads bypass** — flush any existing buffer first, then send the media; otherwise text and images arrive out of order;
* **A change in `replyToId` or the voice flag** also breaks the buffer — content for different reply targets must not be concatenated.

### A repo-level red line

The root `CLAUDE.md` states it explicitly:

> **External channels like WhatsApp and Telegram send only the final reply; streaming and partial replies go only to internal UI.**

The matching default: `agents.defaults.blockStreamingDefault: off`, with non-Telegram channels requiring explicit opt-in.

The reasoning is that messages on external channels are **irrevocable historical records** — send half a sentence and it stays there forever. Internal UI can be redrawn freely.

## 18.6.3 routeReply: Back to Where the Message Was Born

A shared main session across multiple channels (the session-key collapse policy from §14.5.3) means one thing: **the "processing channel" and the "originating channel" may differ.**

For example: you DM the agent on Telegram, sharing the main session; a message arrives from WhatsApp into that same session — where does the reply go?

`routeReply` (`src/auto-reply/reply/route-reply.ts:72-176`) is a **second outbound path parallel to the dispatcher**: it calls the outbound delivery layer directly using `OriginatingChannel` / `OriginatingTo` / `threadId`, and can optionally mirror the reply into the session transcript (`mirror`).

**Every followup-queue reply takes this path** (because it bypasses the inbound dispatcher, §13.6.3).

### Failure fallback: drop rather than send to the wrong place

`followup-runner.ts:110-125` is careful:

```
Only when the originating channel happens to equal the session's current provider
does it fall back to onBlockReply.
A genuine cross-channel failure → drop the message instead.
```

The comment's position is unambiguous: **sending to the wrong chat window is far worse than not sending.**

Picture it: you ask the agent to handle a private email; a return-routing failure falls back and posts it to the company group chat.

> A transferable general principle: **when "delivered" and "delivered correctly" conflict, choose correctly.** A lot of retry and fallback logic goes wrong precisely by chasing delivery rate blindly.

***

## Section Summary

1. **ReplyDispatcher keeps same-session outbound strictly ordered on one Promise chain**; the `pending = 1` reservation prevents "judged idle before the first message is even enqueued," and `markComplete` clears it in a microtask to leave a same-tick window.
2. **Outbound text has two components pulling opposite ways**: `chunk.ts` splits on paragraph boundaries while protecting code fences; `block-reply-coalescer` merges fragments on minChars/idleMs/maxChars — **fast streams cut at maxChars, slow streams don't stall thanks to idleMs, normal streams stay uncluttered thanks to minChars**.
3. **Media payloads and `replyToId` changes must break the buffer**, or ordering scrambles and content gets mis-concatenated.
4. **Repo-level red line: external channels get only the final reply**, streaming stays in internal UI — external messages are irrevocable historical records.
5. **`routeReply` is a second outbound path parallel to the dispatcher**, returning replies to the originating channel; every followup reply uses it.
6. **On failure it drops rather than sending to the wrong place** — "sending to the wrong chat window is far worse than not sending." General principle: **when delivered and delivered-correctly conflict, choose correctly.**
