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

# 18.1 Streaming Architecture

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

***

Large language models generate text through a **token-by-token** process—each inference produces a single token, then the next token is generated based on the tokens already produced. If we wait for the entire response to complete before showing it to the user, they might need to wait tens of seconds or even minutes. **Streaming** solves this problem: as the model generates each token (or small batch of tokens), it is immediately pushed to the client, allowing users to "watch the AI typing."

OpenClaw's streaming system is not merely forwarding model output to users—it must handle filtering of thinking tags, safe splitting of code blocks, message deduplication, and adaptation to multiple channels. This section will introduce the overall architecture of OpenClaw's streaming system, starting from the big picture.

## 18.1.1 Pi Agent Core Event Stream → OpenClaw Event Bridging

The underlying AI agent framework used by OpenClaw (Pi Agent Core / Pi Coding Agent) exposes streaming data through an **event subscription pattern**. The `AgentSession` provides a `subscribe` method that allows external code to listen to various events during Agent execution.

OpenClaw bridges these low-level events to its own high-level abstractions through the `subscribeEmbeddedPiSession` function:

```typescript
// src/agents/pi-embedded-subscribe.ts (simplified)
export function subscribeEmbeddedPiSession(
  params: SubscribeEmbeddedPiSessionParams
) {
  // 1. Initialize state
  const state: EmbeddedPiSubscribeState = {
    assistantTexts: [],     // Final collected assistant text fragments
    toolMetas: [],          // Tool call metadata
    deltaBuffer: "",        // Delta accumulation buffer
    blockBuffer: "",        // Block streaming buffer
    blockState: { thinking: false, final: false, ... },
    compactionInFlight: false,
    messagingToolSentTexts: [],
    // ...more state
  };
  
  // 2. Create block chunker (optional)
  const blockChunker = params.blockReplyChunking 
    ? new EmbeddedBlockChunker(params.blockReplyChunking) 
    : null;
  
  // 3. Build context object
  const ctx: EmbeddedPiSubscribeContext = {
    params, state, blockChunker,
    emitBlockChunk, flushBlockReplyBuffer,
    stripBlockTags, emitReasoningStream,
    // ...more methods
  };
  
  // 4. Register event handlers
  const unsubscribe = params.session.subscribe(
    createEmbeddedPiSessionEventHandler(ctx)
  );
  
  // 5. Return control handle
  return {
    assistantTexts,     // Readable text fragment array
    toolMetas,          // Tool metadata
    unsubscribe,        // Unsubscribe
    isCompacting: () => state.compactionInFlight,
    waitForCompactionRetry: () => { ... },
    didSendViaMessagingTool: () => messagingToolSentTexts.length > 0,
  };
}
```

The core architecture is as follows:

```
Pi Agent Core                    OpenClaw Event Bridging
┌──────────────┐                ┌──────────────────────┐
│ AgentSession │   subscribe    │ subscribeEmbedded     │
│              │ ──────────►   │ PiSession             │
│  .subscribe()│                │                      │
└──────────────┘                │  ┌─ lifecycle handler │
                                 │  ├─ message handler   │
                                 │  ├─ tool handler      │
                                 │  └─ compaction handler│
                                 └──────────┬───────────┘
                                            │
                               ┌────────────┼────────────┐
                               ▼            ▼            ▼
                          onBlockReply  onToolResult  onPartialReply
                          (user-visible) (verbose mode) (real-time preview)
```

### Subscription Parameters

`SubscribeEmbeddedPiSessionParams` defines all options that subscribers can configure:

```typescript
// src/agents/pi-embedded-subscribe.types.ts
export type SubscribeEmbeddedPiSessionParams = {
  session: AgentSession;         // Underlying Agent session
  runId: string;                 // Run identifier
  verboseLevel?: VerboseLevel;   // Output verbosity level
  reasoningMode?: ReasoningLevel;// Reasoning mode (off/on/stream)
  toolResultFormat?: ToolResultFormat; // Tool result format
  
  // Callback functions
  onBlockReply?: (payload: {     // Block reply callback
    text?: string;
    mediaUrls?: string[];
    audioAsVoice?: boolean;
    replyToId?: string;
  }) => void | Promise<void>;
  
  onToolResult?: (payload) => void;  // Tool result callback
  onPartialReply?: (payload) => void;// Partial reply callback (real-time update)
  onReasoningStream?: (payload) => void; // Reasoning stream callback
  onAssistantMessageStart?: () => void;  // Message start signal
  onBlockReplyFlush?: () => void;  // Block flush signal
  onAgentEvent?: (evt) => void;    // Generic event callback
  
  // Configuration
  blockReplyBreak?: "text_end" | "message_end"; // Block boundary
  blockReplyChunking?: BlockReplyChunking; // Chunking parameters
  enforceFinalTag?: boolean;       // Enforce <final> tag
};
```

## 18.1.2 Stream Event Types: `lifecycle` / `assistant` / `tool`

OpenClaw divides low-level events into three **streams**:

### lifecycle Stream: Lifecycle Events

```typescript
// src/agents/pi-embedded-subscribe.handlers.lifecycle.ts
export function handleAgentStart(ctx) {
  emitAgentEvent({
    runId: ctx.params.runId,
    stream: "lifecycle",
    data: { phase: "start", startedAt: Date.now() },
  });
}

export function handleAgentEnd(ctx) {
  emitAgentEvent({
    runId: ctx.params.runId,
    stream: "lifecycle",
    data: { phase: "end", endedAt: Date.now() },
  });
  // When Agent ends, force flush remaining buffer
  if (ctx.blockChunker?.hasBuffered()) {
    ctx.blockChunker.drain({ force: true, emit: ctx.emitBlockChunk });
    ctx.blockChunker.reset();
  }
}
```

The lifecycle stream contains four types of events:

| Event                   | Meaning                   | Trigger Time                              |
| ----------------------- | ------------------------- | ----------------------------------------- |
| `agent_start`           | Agent starts execution    | After receiving user message              |
| `agent_end`             | Agent execution completes | After all tool calls and replies complete |
| `auto_compaction_start` | Auto compaction starts    | Triggered by context overflow             |
| `auto_compaction_end`   | Auto compaction ends      | Compaction completes (may retry)          |

### assistant Stream: Assistant Text Events

The assistant stream is what users care about most—it contains the text generated by the model:

```typescript
// Triggered by handleMessageUpdate
emitAgentEvent({
  runId: ctx.params.runId,
  stream: "assistant",
  data: {
    text: cleanedText,   // Complete accumulated text
    delta: deltaText,    // New text fragment in this update
    mediaUrls: hasMedia ? mediaUrls : undefined,
  },
});
```

> **Sidebar—Delta vs Full Text**
>
> Streaming has two data modes: **Delta mode** only sends the incremental part each time ("Hello" → " world" → "!"), and the client must concatenate them; **Full mode** sends the complete accumulated text each time ("Hello" → "Hello world" → "Hello world!"). OpenClaw provides both `delta` and `text` fields, allowing different consumers to choose as needed.

### tool Stream: Tool Execution Events

```typescript
// Tool start
emitAgentEvent({
  stream: "tool",
  data: { phase: "start", name: toolName, toolCallId, args },
});

// Tool in progress (partial result)
emitAgentEvent({
  stream: "tool",
  data: { phase: "update", name: toolName, toolCallId, partialResult },
});

// Tool complete
emitAgentEvent({
  stream: "tool",
  data: { phase: "result", name: toolName, toolCallId, isError, result },
});
```

### compaction Stream: Compaction Events

```typescript
// Compaction start
emitAgentEvent({ stream: "compaction", data: { phase: "start" } });

// Compaction end
emitAgentEvent({ 
  stream: "compaction", 
  data: { phase: "end", willRetry: Boolean(evt.willRetry) },
});
```

## 18.1.3 Raw Stream Processing (`src/agents/pi-embedded-subscribe.raw-stream.ts`)

OpenClaw provides a **debug-level** raw stream logger that can write all low-level events as-is to a JSONL file:

```typescript
// src/agents/pi-embedded-subscribe.raw-stream.ts
const RAW_STREAM_ENABLED = isTruthyEnvValue(
  process.env.OPENCLAW_RAW_STREAM
);
const RAW_STREAM_PATH = process.env.OPENCLAW_RAW_STREAM_PATH?.trim() 
  || path.join(resolveStateDir(), "logs", "raw-stream.jsonl");

export function appendRawStream(payload: Record<string, unknown>) {
  if (!RAW_STREAM_ENABLED) return;
  
  if (!rawStreamReady) {
    rawStreamReady = true;
    try {
      fs.mkdirSync(path.dirname(RAW_STREAM_PATH), { recursive: true });
    } catch { /* ignore */ }
  }
  
  try {
    void fs.promises.appendFile(
      RAW_STREAM_PATH, 
      `${JSON.stringify(payload)}\n`
    );
  } catch { /* ignore */ }
}
```

After enabling with the environment variable `OPENCLAW_RAW_STREAM=1`, each text event is recorded:

```json
{"ts":1708243791000,"event":"assistant_text_stream","runId":"run_abc","evtType":"text_delta","delta":"Hello"}
{"ts":1708243791050,"event":"assistant_text_stream","runId":"run_abc","evtType":"text_delta","delta":" world"}
{"ts":1708243791100,"event":"assistant_message_end","runId":"run_abc","rawText":"Hello world","rawThinking":"..."}
```

> **Sidebar—JSONL (JSON Lines) Format**
>
> JSONL is a line-delimited JSON format—one complete JSON object per line. Unlike standard JSON arrays, JSONL files can be appended incrementally without rewriting the entire file, making it ideal for logging scenarios. Most data analysis tools (such as `jq`) natively support JSONL.

### Event Handler Routing

Low-level events are routed to corresponding handlers through `createEmbeddedPiSessionEventHandler`:

```typescript
// src/agents/pi-embedded-subscribe.handlers.ts
export function createEmbeddedPiSessionEventHandler(ctx) {
  return (evt: EmbeddedPiSubscribeEvent) => {
    switch (evt.type) {
      case "message_start":    handleMessageStart(ctx, evt);    return;
      case "message_update":   handleMessageUpdate(ctx, evt);   return;
      case "message_end":      handleMessageEnd(ctx, evt);      return;
      case "tool_execution_start":
        handleToolExecutionStart(ctx, evt).catch(/* ignore */);
        return;
      case "tool_execution_update": handleToolExecutionUpdate(ctx, evt); return;
      case "tool_execution_end":    handleToolExecutionEnd(ctx, evt);    return;
      case "agent_start":           handleAgentStart(ctx);               return;
      case "agent_end":             handleAgentEnd(ctx);                 return;
      case "auto_compaction_start": handleAutoCompactionStart(ctx);      return;
      case "auto_compaction_end":   handleAutoCompactionEnd(ctx, evt);   return;
    }
  };
}
```

Note that `tool_execution_start` uses an `async` handler with `.catch()` to ignore errors—this is because tool start may trigger input prompts (typing indicator), which is a "best effort" operation and should not block subsequent processing.

***

## Section Summary

1. **Streaming** allows users to see text as the model generates it, greatly improving interaction experience.
2. OpenClaw bridges low-level Pi Agent Core event streams to high-level three-class streams through `subscribeEmbeddedPiSession`: lifecycle (lifecycle events), assistant (assistant text), tool (tool execution).
3. **Event routing** uses a switch-case pattern to dispatch to four types of handlers: lifecycle, message, tool, and compaction.
4. **Raw stream logger** provides debug-level event tracing capability, enabled on-demand via environment variables.
5. Each event stream is exposed both through `emitAgentEvent` (global event bus) and callback functions.
