> 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/ch15-piagent-runtime-core/15.5-source-deep-dive-full-journey-of-a-run.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 15.5 Source Deep Dive: The Full Journey of One Run

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

***

§15.1–15.4 established Pi Agent's positioning, loop skeleton, queueing, and timeouts. This section stitches them together and follows one complete run — from `runEmbeddedPiAgent()` being called to the result coming back, and every gate in between.

## 15.5.1 First, Get This Straight: In 88,000 Lines, "Running the Loop" Is One Statement

`src/agents/` is the largest subsystem in the repository (87,781 lines). But the only thing actually driving the agent loop is pi SDK's single `session.prompt()` call.

Everything else falls into three categories:

| Phase               | What it does                                                                      |
| ------------------- | --------------------------------------------------------------------------------- |
| **Before the loop** | Assembly — tools, system prompt, sandbox, auth, history repair                    |
| **During the loop** | Interception — the streamFn wrapper chain, event subscription, steering injection |
| **After the loop**  | Recovery — compaction, truncation, profile rotation, model fallback               |

Three core directories divide the work clearly:

| Directory              | Size           | Responsibility                                                                                                                                                                                           |
| ---------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pi-embedded-runner/`  | \~10,000 lines | The runtime's heart: `runEmbeddedPiAgent()`'s outer retry state machine plus `runEmbeddedAttempt()`'s single-attempt assembly                                                                            |
| `pi-embedded-helpers/` | —              | A toolbox of pure functions: error classification (`isContextOverflowError`, `classifyFailoverReason`), per-provider turn validation, thinking-block handling                                            |
| `pi-extensions/`       | —              | Hooks injected into the engine through pi's extension protocol: `compaction-safeguard` and `context-pruning` — **the only entry point through which OpenClaw can intervene in pi's internal compaction** |

The runner decides *what to do*; helpers decide *how to judge*. That split keeps the retry state machine's branches readable — every judgment is a unit-testable pure function.

## 15.5.2 Gate One: Lane Serialization

The first thing `runEmbeddedPiAgent()` does is not call a model. **It queues:**

```ts
// src/agents/pi-embedded-runner/run.ts:258-275
const sessionLane = resolveSessionLane(params.sessionKey?.trim() || params.sessionId);
const globalLane = resolveGlobalLane(params.lane);
// ...
return enqueueSession(() =>
  enqueueGlobal(async () => {
```

These are the two-tier lanes from §44.5. `resolveSessionLane` itself is trivial — it just prefixes the key with `session:` (`lanes.ts:3-6`); the real queue semantics live in `src/process/command-queue.ts`.

**Why must a single session be strictly serial?** Because two concurrent runs would write the same JSONL transcript file simultaneously. That isn't a performance concern, it's a correctness one.

The channel layer's collect / steer / followup queue modes (Chapter 13) all eventually feed into this lane system.

## 15.5.3 Gate Two: The Outer Retry State Machine

`run.ts`'s body is a `while (true)` loop (`run.ts:807`). Each iteration calls `runEmbeddedAttempt()` once, then decides what's next based on the result:

| Result                                   | Action                                                                      |
| ---------------------------------------- | --------------------------------------------------------------------------- |
| Success                                  | `markAuthProfileGood` + assemble payloads and return                        |
| Context overflow                         | Compact → retry; overflow again → truncate tool results → retry             |
| Auth / rate limit / timeout              | `markAuthProfileFailure` + `advanceAuthProfile`, retry with another account |
| Thinking unsupported                     | Downgrade the thinking level and retry                                      |
| Unrecoverable with a fallback configured | Throw `FailoverError` so the outer layer switches models                    |

**The loop cap isn't an arbitrary constant — it scales with the number of auth profiles:**

```ts
// src/agents/pi-embedded-runner/run.ts:137-147
const BASE_RUN_RETRY_ITERATIONS = 24;
const RUN_RETRY_ITERATIONS_PER_PROFILE = 8;
const MIN_RUN_RETRY_ITERATIONS = 32;
const MAX_RUN_RETRY_ITERATIONS = 160;

function resolveMaxRunRetryIterations(profileCandidateCount: number): number {
  const scaled =
    BASE_RUN_RETRY_ITERATIONS +
    Math.max(1, profileCandidateCount) * RUN_RETRY_ITERATIONS_PER_PROFILE;
  return Math.min(MAX_RUN_RETRY_ITERATIONS, Math.max(MIN_RUN_RETRY_ITERATIONS, scaled));
}
```

The motivation is direct: **a user with ten Claude accounts configured deserves more rotation attempts than a single-account user.** But 160 is a hard ceiling regardless — preventing retry branches from triggering each other into an infinite loop.

The complete control flow:

```mermaid
flowchart TD
    A[agent RPC / CLI] --> B[runEmbeddedPiAgent<br/>session lane + global lane serialization]
    B --> C[before_model_resolve hook<br/>resolveModel + context window guard]
    C --> D[resolveAuthProfileOrder<br/>pick a profile / skip cooling ones]
    D --> E["while(true) retry state machine<br/>cap = f(profile count), ≤160"]
    E --> F[runEmbeddedAttempt single attempt]
    F --> G[createAgentSession<br/>tool assembly + streamFn wrapper chain]
    G --> H[session.prompt<br/>pi-agent-core drives the tool loop]
    H --> I[subscribeEmbeddedPiSession<br/>events → assistant/tool/lifecycle streams]
    I --> J{result?}
    J -->|context overflow| K[compact → retry<br/>→ truncate tool results → retry]
    J -->|auth/rate limit/timeout| L[markAuthProfileFailure<br/>advanceAuthProfile]
    J -->|thinking unsupported| M[downgrade thinking, retry]
    J -->|unrecoverable + fallback configured| N[throw FailoverError]
    K --> E
    L --> E
    M --> E
    N --> O[runWithModelFallback<br/>walk the model candidate chain]
    J -->|success| P[markAuthProfileGood<br/>assemble payloads and return]
```

## 15.5.4 Gate Three: The Single-Attempt Assembly Pipeline

`src/agents/pi-embedded-runner/run/attempt.ts`, **2,096 lines**, the densest file in the directory. §43.4.5 warned against starting here — now that you have the skeleton, it's time.

One attempt does these ten things in order:

**1. Sandbox resolution** (`attempt.ts:761-771`) `resolveSandboxContext()` decides whether the working directory is the host workspace or a sandbox copy. With `workspaceAccess === "rw"` it mounts the original directly.

**2. Skills and bootstrap files** Load the skills snapshot; inject `AGENTS.md` / `SOUL.md` / `TOOLS.md` and friends. Trim to budget — `bootstrapMaxChars` per file (20k characters) and `bootstrapTotalMaxChars` overall (150k). On overflow it **injects a warning block into the prompt** rather than truncating silently.

**3. Tool assembly** `createOpenClawCodingTools()` — see §22.5.

**4. System prompt** `buildEmbeddedSystemPrompt()` assembles Tooling / Safety / Skills / Sandbox / Runtime / Project Context sections. **Subagent and cron sessions use `promptMode: "minimal"`, cutting most sections** (`attempt.ts:612-617`) — they don't need a full personality.

**5. Session lock** `acquireSessionWriteLock()` (`attempt.ts:1060-1065`). The maximum hold time is **derived from the run timeout**, preventing deadlock after a process crash.

**6. SessionManager wrapping** `guardSessionManager(SessionManager.open(...))` (`attempt.ts:1087`) — wraps pi's session manager in a guard that intercepts orphaned `toolCall` / `toolResult` writes. A textbook instance of §44.1's "embed, don't fork."

**7. Create the pi session** and apply system prompt overrides (`attempt.ts:1179-1192`).

**8. History sanitization** (`attempt.ts:1388-1419`) A four-step chain:

```
sanitizeSessionHistory
  → provider-specific turn validation (validateAnthropicTurns / validateGeminiTurns)
  → limitHistoryTurns (different caps for DMs and groups)
  → repair tool_use/tool_result pairing again after truncation
```

That last step can't be skipped: truncation may cut exactly through a tool\_use/tool\_result pair, leaving an orphan.

**9. Orphan message repair** (`attempt.ts:1687-1701`) If the transcript's leaf node is a **user message that never received a response**, branch it away. Otherwise the new prompt creates two consecutive user turns — which most providers reject outright.

**10. Issue the prompt**

```ts
// attempt.ts:1781-1784
await abortable(activeSession.prompt(effectivePrompt, { images }))
```

From here pi-agent-core drives the loop; OpenClaw only intervenes through event subscription and tool execution.

### A byproduct: the system prompt bill

Assembly also produces a **system prompt report** (`buildSystemPromptReport`, `attempt.ts:1029-1056`), persisted to session storage, containing:

* Character count per prompt section
* Each bootstrap file's raw / injected size and truncation flag
* **Tool schema size**
* Sandbox state

`/context list` and `/context detail` display exactly this report.

**It turns "why is my system prompt so big?" from a black box into an itemized, auditable bill.** Tool schemas routinely run 30,000 characters (\~8k tokens) — without this observability, users have no idea what's consuming their context.

> This is the positive case for the warning at the end of §44.2: complex mechanisms must come with observability.

### One bugfix comment that explains the pain of embedding a third-party loop

```ts
// src/agents/pi-embedded-runner/run/attempt.ts:2076-2087
// BUGFIX: Wait for the agent to be truly idle before flushing pending tool results.
// pi-agent-core's auto-retry resolves waitForRetry() on assistant message receipt,
// *before* tool execution completes in the retried agent loop. Without this wait,
// flushPendingToolResults() fires while tools are still executing, inserting
// synthetic "missing tool result" errors and causing silent agent failures.
// See: https://github.com/openclaw/openclaw/issues/8643
removeToolResultContextGuard?.();
await flushPendingToolResultsAfterIdle({ agent: session?.agent, sessionManager, ... });
```

Translated: pi's auto-retry considers itself ready to proceed **on receiving the assistant message**, but at that point the tools in the retried loop **are still executing**. Flushing before it's genuinely idle inserts synthetic "missing tool result" errors and causes silent agent failures.

**You don't control the upstream's timing** — the characteristic cost of embedding a third-party loop, and the concrete form of the "architecture tax" from §44.1.

## 15.5.5 The streamFn Onion: The Only Injection Point Into pi

pi's `AgentSession` exposes `agent.streamFn`. OpenClaw treats it as an AOP seam and wraps it in layers per provider (`attempt.ts:1230-1386`):

| Wrapper layer                           | What it fixes                                                                                                                                                                                                         |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Transport selection                     | Ollama uses its native `/api/chat` (bypassing the SDK stream to fix streaming tool calls); OpenAI Responses uses WebSocket; everything else uses `streamSimple`                                                       |
| Ollama `num_ctx` injection              | Without it the OpenAI-compatible endpoint defaults to a 4096 window                                                                                                                                                   |
| `dropThinkingBlocks`                    | Copilot / Claude reject persisted thinking blocks in history; strip them before each outbound request                                                                                                                 |
| `sanitizeToolCallIdsForCloudCodeAssist` | Mistral and others enforce a regex on tool call id format; pi's internal tool loop doesn't pass through history sanitization, so this must wrap streamFn                                                              |
| `wrapStreamFnTrimToolCallNames`         | Some models emit tool names like `" read "` with spaces; pi dispatches by exact match, so normalization must happen live on the stream (`attempt.ts:245-294` also handles namespaced call names like `mcp/tool.name`) |
| xAI/Grok HTML entity decoding           | `&quot;` shows up inside tool arguments                                                                                                                                                                               |
| `cacheTrace` / `anthropicPayloadLogger` | Debug payload recording, enabled by environment variable, redacted and written to disk                                                                                                                                |

**Every layer corresponds to a real issue.** This chain is the product of "don't fork upstream, but still fix the provider quirks upstream hasn't."

The cost is what §45.2 lists: **order sensitivity and deep debugging stacks** (the logger must be outermost to see the final payload), with no mechanism preventing a later contributor from inserting a layer in the wrong place. `docs/pi.md`'s Future Considerations acknowledges this should be pushed upstream to pi.

## 15.5.6 Timeouts and Interruption: Three Signal Sources, One AbortController

Each attempt has an internal `runAbortController` (`attempt.ts:751`) triggered by three sources:

1. A caller-supplied `abortSignal` (the user's `/stop`)
2. `abortTimer` hard timeout (`attempt.ts:1564-1595`, default `agents.defaults.timeoutSeconds = 600s`)
3. Gateway-level cancellation

**The subtlest part is the interaction with compaction.**

If a timeout fires while compaction is in progress, it marks `timedOutDuringCompaction` and returns results using the **pre-compaction message snapshot**. The snapshot is captured with a double `isCompacting` check to avoid a race (`attempt.ts:1794-1801`).

And this class of timeout **does not trigger profile rotation**:

```
// run.ts:1353-1356 semantics
// the model actually succeeded; compaction was slow — blaming the account would be unjust
```

That's exactly the "precise error attribution" of §45.1's first pattern.

After the prompt ends there's still a **60-second aggregate timeout** waiting for compaction retry (`attempt.ts:1803-1828`); if it doesn't converge, execution continues with the pre-compaction state.

One more detail: sessions whose IDs start with `probe-` share this path but **silence their logs**, so model availability probing can reuse the full runtime without flooding the console.

## 15.5.7 The Streaming Event Bridge: Translating pi Events Into Three Streams

`subscribeEmbeddedPiSession()` (`src/agents/pi-embedded-subscribe.ts:34`) translates pi's session events (`message_start/update/end`, `tool_execution_*`, `auto_compaction_*`) into OpenClaw's three streams: `assistant`, `tool`, `lifecycle`.

It maintains a state object with 50-plus fields, with complexity concentrated in four things.

### Tag stripping

Many models — especially distilled open-weight ones — write reasoning inline in the body or imitate a `<final>` tag.

`stripBlockTags` (`pi-embedded-subscribe.ts:368-456`) performs **stateful stripping across chunks**:

* Content inside `<think>` is discarded;
* With `enforceFinalTag` on, only content inside `<final>...</final>` passes;
* **Fake tags inside code spans are deliberately skipped** (a `<think>` inside a code block is code, not a tag).

In strict mode, if no `<final>` has been seen, not a single character is emitted — preventing "thinking out loud" from leaking to the user.

### Block chunking and deduplication

`EmbeddedBlockChunker` cuts streamed text into sendable blocks of **800–1200 characters, preferring paragraph boundaries** (feeding block streaming on Telegram and similar, §18.2).

It also solves a problem specific to message gateways: **the model sends the answer using the `message` tool, then restates it in the body — "I've already replied on Telegram!"**

The subscription layer records a normalized form of every text already sent by messaging tools and discards body blocks that duplicate it (`pi-embedded-subscribe.ts:493-497`).

The comment notes specifically: **only successfully committed sends are compared, never pending ones** — otherwise a failed tool would leave the user with nothing at all.

### Three shapes of reasoning stream

`reasoningMode` supports three settings:

| Mode     | Behavior                                                                                                                                                                          |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `off`    | No reasoning output                                                                                                                                                               |
| `on`     | Reasoning merged into the final reply text                                                                                                                                        |
| `stream` | Pushed separately via `onReasoningStream`, **and simultaneously** broadcast to WebSocket clients as an agent event with `stream: "thinking"` (`pi-embedded-subscribe.ts:573-585`) |

`stream` mode lets the Control UI show a live "thinking" panel **without polluting the chat record**.

Reasoning deltas use a **prefix defense**: if the previously emitted text isn't a prefix of the new text (meaning formatting rewrote earlier content), it resends the whole thing rather than emitting an incorrect delta.

> Again, "snapshots are more robust than deltas" (§44.5.3).

### Waiting on compaction

pi's auto-compaction is asynchronous. The subscription layer tracks it with a counter plus a single promise (`noteCompactionRetry` / `resolveCompactionRetry`):

* `waitForCompactionRetry()` (`:697-724`) lets the attempt wait for compaction retry to converge after the prompt ends, **and rejects with AbortError on unsubscribe** to avoid dangling;
* `resetForCompactionRetry()` (`:588-604`) **clears all buffered output** when compaction triggers a retry — otherwise the user receives two copies of the answer.

***

## Section Summary

1. In `src/agents/`'s 88,000 lines, **only `session.prompt()` drives the loop**; the rest is pre-loop assembly, in-loop interception, and post-loop recovery, split across `pi-embedded-runner/` (the heart), `pi-embedded-helpers/` (pure-function judgments), and `pi-extensions/` (the only in-engine injection point).
2. **A run's first action is to queue** (two-tier lanes), because concurrent runs on one session would write the same JSONL; **the retry cap scales with auth-profile count** (32–160), so ten-account users get more rotation attempts.
3. `attempt.ts`'s 2,096-line assembly has ten steps; the **four-step history sanitization chain** and the **orphan user-message branch** are what keep providers from rejecting the request. A byproduct is the auditable **system prompt bill** (`/context list`).
4. **The streamFn onion is the only injection point into pi**, seven layers each corresponding to a real issue; the cost is order sensitivity with no mechanism against inserting a layer wrongly.
5. **The timeout/compaction interaction is the subtlest part**: a timeout during compaction returns the pre-compaction snapshot, guarded by a double race check, and **does not charge the account** (the model succeeded; compaction was slow).
6. The event bridge handles four things: **stateful cross-chunk tag stripping** (skipping fake tags in code spans), **block chunking with messaging-tool deduplication** (comparing only committed sends), **three reasoning shapes** (`stream` keeps the chat record clean, with a prefix defense), and **compaction waiting with buffer clearing** (preventing duplicate answers).
