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

# 18.2 Block Streaming

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

***

Model-generated text is a continuous token stream, but message channels (such as Telegram, Signal) need **discrete messages**. Splitting the continuous text stream into appropriately-sized message blocks—this is the core problem that **Block Streaming** solves.

OpenClaw's `EmbeddedBlockChunker` implements a sophisticated text chunking algorithm that doesn't simply split by fixed character count, but instead seeks **semantically reasonable break points** and can safely handle Markdown code fences.

## 18.2.1 EmbeddedBlockChunker Algorithm (`src/agents/pi-embedded-block-chunker.ts`)

### BlockReplyChunking Configuration

```typescript
// src/agents/pi-embedded-block-chunker.ts
export type BlockReplyChunking = {
  minChars: number;       // Minimum block size
  maxChars: number;       // Maximum block size
  breakPreference?: "paragraph" | "newline" | "sentence";
  flushOnParagraph?: boolean; // Flush immediately on paragraph boundary
};
```

`minChars` and `maxChars` form a **watermark range**: text below `minChars` continues to accumulate, above `maxChars` is forced to break, and between them seeks suitable break points.

### Core Class Structure

```typescript
export class EmbeddedBlockChunker {
  #buffer = "";                    // Text buffer
  readonly #chunking: BlockReplyChunking; // Configuration
  
  append(text: string) {           // Append text
    this.#buffer += text;
  }
  
  reset() {                        // Reset buffer
    this.#buffer = "";
  }
  
  hasBuffered(): boolean {         // Whether there is unsent content
    return this.#buffer.length > 0;
  }
  
  drain(params: {                  // Drain buffer
    force: boolean;                // Whether to force (ignore minChars)
    emit: (chunk: string) => void; // Emit callback
  }) { ... }
}
```

### drain Method Execution Flow

```typescript
drain(params: { force: boolean; emit: (chunk: string) => void }) {
  const minChars = Math.max(1, Math.floor(this.#chunking.minChars));
  const maxChars = Math.max(minChars, Math.floor(this.#chunking.maxChars));
  
  // Paragraph mode: flush immediately on \n\n
  if (this.#chunking.flushOnParagraph && !force) {
    this.#drainParagraphs(emit, maxChars);
    return;
  }
  
  // Below low watermark and not forced → continue accumulating
  if (this.#buffer.length < minChars && !force) return;
  
  // Forced and within limit → send as whole
  if (force && this.#buffer.length <= maxChars) {
    if (this.#buffer.trim().length > 0) emit(this.#buffer);
    this.#buffer = "";
    return;
  }
  
  // Loop chunking
  while (this.#buffer.length >= minChars || 
         (force && this.#buffer.length > 0)) {
    const breakResult = force && this.#buffer.length <= maxChars
      ? this.#pickSoftBreakIndex(this.#buffer, 1)
      : this.#pickBreakIndex(this.#buffer, force ? 1 : undefined);
    
    if (breakResult.index <= 0) {
      if (force) { emit(this.#buffer); this.#buffer = ""; }
      return;
    }
    
    this.#emitBreakResult(breakResult, emit);
    
    if (this.#buffer.length < minChars && !force) return;
  }
}
```

## 18.2.2 Low Watermark / High Watermark Chunking Strategy

The chunking strategy is based on the classic **watermark** pattern:

```
                maxChars (high watermark)
                ─────────────────────────
                ↑ Must break (force seeking break point)
                │
                │ Preference range (seek best break point in this range)
                │
                ─────────────────────────
                ↑ minChars (low watermark)
                │ Continue accumulating (no chunking)
                ─────────────────────────
```

* **Below minChars**: Don't chunk, continue accumulating text
* **Between minChars and maxChars**: Seek **best break point**—try paragraph, newline, sentence, whitespace in order of preference
* **Above maxChars**: Force break at maxChars, even if inside code block (use fence reopening mechanism)

The advantage of this design is: short messages won't be split prematurely (avoiding fragmentation), and long messages won't accumulate indefinitely (avoiding timeout or channel limits).

> **Sidebar—Watermark Pattern**
>
> The watermark pattern originates from flow control. The low watermark represents the threshold to "start action," and the high watermark represents the threshold to "must act." In network programming, TCP send buffer's low/high watermarks control when to notify the application that it can write data. OpenClaw borrows this concept to control text block sizes.

## 18.2.3 Break Point Preference: Paragraph → Newline → Sentence → Whitespace → Hard Break

The `#pickBreakIndex` method tries different types of break points in order of priority:

```typescript
#pickBreakIndex(buffer: string, minCharsOverride?: number): BreakResult {
  const window = buffer.slice(0, Math.min(maxChars, buffer.length));
  const fenceSpans = parseFenceSpans(buffer);
  const preference = this.#chunking.breakPreference ?? "paragraph";
  
  // Priority 1: Paragraph break point (\n\n)
  if (preference === "paragraph") {
    let paragraphIdx = window.lastIndexOf("\n\n");
    while (paragraphIdx >= minChars) {
      if (isSafeFenceBreak(fenceSpans, paragraphIdx)) {
        return { index: paragraphIdx };
      }
      paragraphIdx = window.lastIndexOf("\n\n", paragraphIdx - 1);
    }
  }
  
  // Priority 2: Newline break point (\n)
  if (preference === "paragraph" || preference === "newline") {
    let newlineIdx = window.lastIndexOf("\n");
    while (newlineIdx >= minChars) {
      if (isSafeFenceBreak(fenceSpans, newlineIdx)) {
        return { index: newlineIdx };
      }
      newlineIdx = window.lastIndexOf("\n", newlineIdx - 1);
    }
  }
  
  // Priority 3: Sentence break point (.!? followed by whitespace or end of line)
  if (preference !== "newline") {
    const matches = window.matchAll(/[.!?](?=\s|$)/g);
    // Select the last valid sentence break point
    let sentenceIdx = -1;
    for (const match of matches) {
      const candidate = (match.index ?? -1) + 1;
      if (candidate >= minChars && isSafeFenceBreak(fenceSpans, candidate)) {
        sentenceIdx = candidate;
      }
    }
    if (sentenceIdx >= minChars) return { index: sentenceIdx };
  }
  
  // Priority 4: Whitespace break point
  for (let i = window.length - 1; i >= minChars; i--) {
    if (/\s/.test(window[i]) && isSafeFenceBreak(fenceSpans, i)) {
      return { index: i };
    }
  }
  
  // Priority 5: Hard break (force split at maxChars)
  if (buffer.length >= maxChars) {
    if (isSafeFenceBreak(fenceSpans, maxChars)) {
      return { index: maxChars };
    }
    // Inside fence → use fence split
    const fence = findFenceSpanAt(fenceSpans, maxChars);
    if (fence) {
      return {
        index: maxChars,
        fenceSplit: {
          closeFenceLine: `${fence.indent}${fence.marker}`,
          reopenFenceLine: fence.openLine,
        },
      };
    }
    return { index: maxChars };
  }
  
  return { index: -1 }; // Cannot break
}
```

Key point: **Every break point candidate must pass the `isSafeFenceBreak` check**—ensuring the break point is not inside a Markdown code fence. This is because breaking in the middle of a code block causes Markdown rendering issues.

### Paragraph Eager Flush Mode

When `flushOnParagraph` is `true`, each paragraph boundary (`\n\n`) triggers an immediate send without waiting for the buffer to fill:

```typescript
#drainParagraphs(emit: (chunk: string) => void, maxChars: number) {
  while (this.#buffer.length > 0) {
    const fenceSpans = parseFenceSpans(this.#buffer);
    const paragraphBreak = findNextParagraphBreak(this.#buffer, fenceSpans);
    
    if (!paragraphBreak || paragraphBreak.index > maxChars) {
      // No paragraph boundary or too far → fall back to normal break logic
      if (this.#buffer.length >= maxChars) {
        const breakResult = this.#pickBreakIndex(this.#buffer, 1);
        if (breakResult.index > 0) {
          this.#emitBreakResult(breakResult, emit);
          continue;
        }
      }
      return;
    }
    
    const chunk = this.#buffer.slice(0, paragraphBreak.index);
    if (chunk.trim().length > 0) emit(chunk);
    this.#buffer = stripLeadingNewlines(
      this.#buffer.slice(paragraphBreak.index + paragraphBreak.length)
    );
  }
}
```

## 18.2.4 Fenced Block Safe Splitting: Close + Reopen

This is the most elegant part of the block streaming algorithm. When text exceeds maxChars but the break point is exactly inside a code fence, we can't simply cut in the middle—this would break the Markdown format. The solution is to **close the current fence, then reopen it in the next block**:

```typescript
#emitBreakResult(breakResult: BreakResult, emit) {
  let rawChunk = this.#buffer.slice(0, breakResult.index);
  let nextBuffer = this.#buffer.slice(breakResult.index);
  
  const fenceSplit = breakResult.fenceSplit;
  if (fenceSplit) {
    // Add closing fence at end of current block
    const closeFence = rawChunk.endsWith("\n")
      ? `${fenceSplit.closeFenceLine}\n`
      : `\n${fenceSplit.closeFenceLine}\n`;
    rawChunk = `${rawChunk}${closeFence}`;
    
    // Add reopening fence at start of next block
    const reopenFence = fenceSplit.reopenFenceLine.endsWith("\n")
      ? fenceSplit.reopenFenceLine
      : `${fenceSplit.reopenFenceLine}\n`;
    nextBuffer = `${reopenFence}${nextBuffer}`;
  }
  
  emit(rawChunk);
  this.#buffer = fenceSplit ? nextBuffer : stripLeadingNewlines(...);
}
```

Example. Suppose the original text is:

````
This is some explanatory text.

```python
def hello():
    print("Hello")
    # This is a very long function...
    # ...many lines of code...
    return True
```
````

If maxChars happens to be right after `print("Hello")`, the chunker produces:

**Block 1**:

````
This is some explanatory text.

```python
def hello():
    print("Hello")
```
````

**Block 2**:

````
```python
    # This is a very long function...
    # ...many lines of code...
    return True
```
````

The fence split information comes from `parseFenceSpans` and `findFenceSpanAt`, which parse all fenced code blocks in Markdown and record their positions, indentation, and markers:

````typescript
type FenceSplit = {
  closeFenceLine: string;  // Closing line (e.g., "```")
  reopenFenceLine: string; // Reopening line (e.g., "```python")
};
````

***

## Section Summary

1. **EmbeddedBlockChunker** splits continuous text streams into discrete blocks suitable for sending via message channels.
2. **Watermark strategy** (minChars/maxChars) avoids problems of messages being too fragmented or too large.
3. **Break point priority** (paragraph > newline > sentence > whitespace > hard break) ensures text breaks at semantically reasonable positions.
4. **Fence safety check** (`isSafeFenceBreak`) prevents breaking inside code blocks, avoiding Markdown rendering issues.
5. **Fence close + reopen** mechanism is the essence of the block streaming algorithm—when forced to split code blocks, automatically closing and reopening fences maintains Markdown validity.
