Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): replace removed Pi harness APIs

vastsa880804671185
diff --git a/apps/desktop/test/context-compaction.test.mjs b/apps/desktop/test/context-compaction.test.mjs
index d57835f90..cb4bd3399 100644
--- a/apps/desktop/test/context-compaction.test.mjs
+++ b/apps/desktop/test/context-compaction.test.mjs
@@ -154,7 +154,7 @@ test("a delegate gets the session's turn-boundary budget protection (ADR 0299)",
assert.match(runtime, /budget: contextBudgetLimitsFor\(model\)/);
assert.match(delegationHistory, /truncateSeededMessages/);
assert.match(delegationHistory, /\.\.\.message, content, stopReason: "stop"/);
- // The compaction itself uses pi-agent-core's primitives, the session's
+ // The compaction itself uses the runtime-owned preparation, the session's
// retention rule, and the degradation ladder of decision 4.
assert.match(subagentContext, /prepareCompaction\(/);
assert.match(subagentContext, /generateSummaryWithUsage\(/);
diff --git a/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md b/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md
index 478095896..38c4e5a22 100644
--- a/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md
+++ b/docs/adr/0030-turn-boundary-context-checkpoint-compaction.md
@@ -18,10 +18,11 @@ not protect the next provider request inside that loop. The observed Bedrock
failure reached 1,077,172 tokens against a 1,000,000-token provider maximum,
so the provider rejected the request before PI-Desktop had a recovery point.
-pi-agent-core already supplies session-context reconstruction, token
-estimation, cut-point selection, summary generation, retained-tail handling,
-and compaction records. It does not define PI-Desktop's renderer lifecycle,
-Rust-owned persistence, provider-headroom policy, or long-loop guard.
+At the time of this decision, pi-agent-core supplied session-context
+reconstruction, token estimation, cut-point selection, summary generation,
+retained-tail handling, and compaction records. Those harness exports were
+experimental and have since been removed; the desktop runtime now owns those
+helpers. pi-agent-core still supplies the agent loop and stable agent types.
OpenCode Dynamic Context Pruning (DCP), inspected at commit
`85b6f5ceba144fee9e65eb28dc36cab1b960e418`, demonstrates useful behavioral
@@ -32,8 +33,9 @@ incompatible runtime and licensing boundary to PI-Desktop.
## Decision
-PI-Desktop uses pi-agent-core's public compaction primitives and independently
-implements the desktop-specific controller.
+PI-Desktop owns its context projection, estimation, compaction preparation and
+summary generation, and independently implements the desktop-specific
+controller. pi-agent-core supplies the agent loop and stable agent types.
- The controller runs after every `turn_end` and before pi starts another
provider request. `turn_end` is a model/tool-turn boundary; only `agent_end`
@@ -145,6 +147,15 @@ families, fork inputs, searchability, or diagnostics.
## References
+### Implementation note (2026-10-03)
+
+The accepted ownership boundary is unchanged, but pi-agent-core removed its
+experimental harness/compaction exports. Agent Runtime now owns the context
+projection, conversion, estimation, cut-point preparation, and summary request
+adapter; pi-agent-core remains the agent loop and stable type dependency. Rust
+host-core still owns durable checkpoints and session storage. See
+`docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md`.
+
- `docs/spec/03-runtime/01-ipc-protocol.md`
- `docs/spec/03-runtime/02-agent-runtime.md`
- `docs/spec/03-runtime/04-data-storage.md`
diff --git a/docs/adr/0049-context-compaction-failure-recovery.md b/docs/adr/0049-context-compaction-failure-recovery.md
index 2383bad5a..2107be8fa 100644
--- a/docs/adr/0049-context-compaction-failure-recovery.md
+++ b/docs/adr/0049-context-compaction-failure-recovery.md
@@ -40,8 +40,7 @@ three-outcome controller:
1. Preflight the summary input against the provider model window. If the
serialized history plus the summary output allowance cannot fit, skip the
- doomed summary request; otherwise run the normal pi-agent-core summary
- compaction.
+ doomed summary request; otherwise run the desktop-owned summary compaction.
2. If summary generation fails, or a generated checkpoint remains above the
safe budget, prepare a deterministic fallback checkpoint. It reuses the
previous checkpoint summary when available, adds a short recovery marker,
diff --git a/docs/adr/0064-codex-parity-context-compaction.md b/docs/adr/0064-codex-parity-context-compaction.md
index e7dee1deb..b09d76ab7 100644
--- a/docs/adr/0064-codex-parity-context-compaction.md
+++ b/docs/adr/0064-codex-parity-context-compaction.md
@@ -208,6 +208,15 @@ against "one summary request" from a settings row.
## References
+### Implementation note (2026-10-03)
+
+The desktop runtime now owns the compaction preparation and context projection
+described here because pi-agent-core removed its experimental harness APIs.
+Cut-point, split-turn, retained-tail, and summary behavior remain governed by
+this ADR and the runtime specification; durable checkpoint ownership remains
+with Rust host-core. See
+`docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md`.
+
- `docs/spec/03-runtime/01-ipc-protocol.md`
- `docs/spec/03-runtime/02-agent-runtime.md`
- `docs/spec/03-runtime/03-tools-and-permissions.md`
diff --git a/docs/adr/0282-compaction-summary-retry-and-sizing.md b/docs/adr/0282-compaction-summary-retry-and-sizing.md
index 27e5a0572..572e5c70f 100644
--- a/docs/adr/0282-compaction-summary-retry-and-sizing.md
+++ b/docs/adr/0282-compaction-summary-retry-and-sizing.md
@@ -106,6 +106,15 @@ summary request and is untouched.
including historical ones, because the mark is derived from persisted
details on session open.
+### Implementation note (2026-10-03)
+
+The retry, sizing, reduction, and chunking contract remains unchanged. The
+summary request adapter and conversation serializer are now owned by
+`packages/agent-runtime` because pi-agent-core removed its experimental harness
+exports. The desktop adapter still uses pi-ai `completeSimple` and the same
+retry policy. See
+`docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md`.
+
## Alternatives
### Outer retry loop around `buildCheckpoint` (PR #554)
diff --git a/docs/adr/pi-ai-core-0991-authority.md b/docs/adr/pi-ai-core-0991-authority.md
index 4c1c7b94c..c686bf674 100644
--- a/docs/adr/pi-ai-core-0991-authority.md
+++ b/docs/adr/pi-ai-core-0991-authority.md
@@ -47,3 +47,15 @@ The account adapter reuses Desktop's existing boundaries and preserves saved dat
with a small explicit display-only compatibility gap. Catalog changes now track
reviewed Pi pins. No schema migration is needed for the usage ledger: it uses the
existing turns usage JSON with optional compatible provenance fields.
+
+### Implementation note (2026-10-03)
+
+The 0.99.1 migration initially retained pi-coding-agent for compaction and file
+compatibility. Its experimental pi-agent-core harness APIs have since been
+removed. The normal Desktop runtime now owns transcript projection, estimation,
+checkpoint preparation, and summary generation; Rust host-core remains the
+durable session owner. pi-coding-agent remains temporarily limited to native Pi
+session continuation (including that path's native session behavior) and the
+trusted-extension compatibility shim. Its removal seams and migration criteria
+are recorded in
+`docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md`.
diff --git a/docs/project/pi-0991-gaps.md b/docs/project/pi-0991-gaps.md
index c5a6edeb8..dfc8aa2c8 100644
--- a/docs/project/pi-0991-gaps.md
+++ b/docs/project/pi-0991-gaps.md
@@ -8,7 +8,7 @@ The pi-ai/pi-agent-core migration passes the local candidate gates documented in
| Installed artifacts | Exercise installed Electron loading, native Host and packaged OAuth/image modules across supported platform/architecture lanes. Local standalone bundles and sidecar E2E passed. |
| Real account integration | Real OAuth and paid requests were not authorized or used; offline flows prove contracts, not current vendor service availability. |
| Cross-version rollback | Qualify the prior released version against retained data. Optional provenance fields and the existing usage JSON require no new schema, but that alone is not an executed rollback test. |
-| Dependency removal | pi-coding-agent remains the pre-existing compaction/file utility compatibility dependency. Removing it is a separate refactor. |
+| Dependency removal | pi-coding-agent remains temporarily for native Pi session continuation and the trusted-extension compatibility shim. The normal Desktop checkpoint-compaction path is runtime-owned. Removing the dependency requires replacing both remaining seams; see `docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md`. |
| Design follow-ups | Tool inventory separation, an independent Codemode sandbox adapter, and physical/virtual routing contracts are evaluated in the design review. They are outside this migration and are not enabled. |
No MCP migration, coding-agent session integration, classifier/router feature,
diff --git a/docs/project/pi-coding-agent-design-review.md b/docs/project/pi-coding-agent-design-review.md
index 928e987b0..2419be64a 100644
--- a/docs/project/pi-coding-agent-design-review.md
+++ b/docs/project/pi-coding-agent-design-review.md
@@ -76,9 +76,18 @@ it must not silently broaden the account or provider allowlist.
## Recommendation
-Complete the pi-ai/pi-agent-core migration first. Keep coding-agent as the
-existing compatibility dependency for compaction/file utilities, with no new
-session-runtime dependency. Record the above patterns for follow-up work; first
-consolidate tool inventory, then evaluate the sandbox independently, and add
-routing only with a product policy and persistence contract. None of these
-follow-ups is a migration acceptance requirement.
+At the time of this review, keep coding-agent as the existing compatibility
+dependency for compaction/file utilities, with no new session-runtime
+dependency. Since the experimental pi-agent-core harness APIs were removed,
+the normal Desktop runtime now owns context projection and host-core checkpoint
+compaction. The remaining production dependency is limited to native Pi session
+continuation and the trusted-extension compatibility shim. Do not move removed
+pi-agent-core APIs into coding-agent.
+
+The user-directed follow-up is to remove coding-agent after replacing the
+native-session and extension-compatibility seams. See
+`docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md` for the
+required migration sequence and compatibility checks. Tool inventory
+consolidation, an independent Codemode sandbox adapter, and virtual routing
+remain separate design follow-ups; none is required for this compatibility
+migration.
diff --git a/docs/spec/02-architecture/02-tech-stack.md b/docs/spec/02-architecture/02-tech-stack.md
index 883a9de39..e84c94d2e 100644
--- a/docs/spec/02-architecture/02-tech-stack.md
+++ b/docs/spec/02-architecture/02-tech-stack.md
@@ -18,8 +18,11 @@
> pi-ai owns published metadata, native thinking support, transports and auth.
> Host persists Desktop account rows, credentials, and explicit binding overrides.
-> pi-coding-agent remains an existing compatibility dependency for compaction and
-> file utilities; this migration does not adopt AgentSession, Codemode or routing.
+> Agent Runtime owns desktop context projection and checkpoint compaction. The
+> transitional pi-coding-agent dependency is confined to native Pi session
+> continuation and the trusted-extension compatibility shim; it is not the
+> desktop agent loop, compaction, or durable session store. See
+> [the pi runtime dependency boundary](06-pi-runtime-dependency-boundary.md).
| Node runtime | Node.js | `>= 22.19` | pi requirement |
| DB | SQLite | Rust host-core via `rusqlite` | sessions/settings |
diff --git a/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
new file mode 100644
index 000000000..0ebd869d3
--- /dev/null
+++ b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
@@ -0,0 +1,90 @@
+# 06. Pi Runtime Dependency Boundary
+
+## 1. Purpose
+
+PI-Desktop uses the pi agent loop without adopting the CLI's session runtime
+or giving a JavaScript package ownership of desktop persistence. Package
+boundaries must keep that split clear as upstream packages evolve.
+
+## 2. Current ownership
+
+- `@earendil-works/pi-agent-core` supplies the agent loop and its stable agent,
+ event, and tool types. Agent Runtime owns desktop-specific compaction,
+ prompt-template expansion, and session-context projection.
+- `@earendil-works/pi-ai` supplies provider transports, auth, message types,
+ request retries, and token estimation. Hosted-search request and estimation
+ behavior remains covered by PI-Desktop's pi-ai patch and contract tests.
+- Rust `host-core` remains the sole owner of SQLite and authoritative durable
+ session state. The Node sidecar asks it to persist checkpoints and tool
+ outcomes through the existing RPC contract.
+- `@earendil-works/pi-coding-agent` is a transitional dependency. Production
+ imports are confined to native Pi session continuation and its session-file
+ manager; that native-session path still uses the package's AgentSession and
+ native session behavior. Trusted extensions receive a small compatibility
+ shim from `extensions/loader.ts`. The normal Desktop agent runtime,
+ host-core checkpoint-compaction path, and durable session store do not use
+ the package's AgentSession.
+
+Do not reintroduce imports from removed `pi-agent-core` harness, session,
+compaction, or prompt-template APIs. Keep desktop behavior in the agent-runtime
+boundary and use public `pi-ai` APIs for provider-facing operations.
+
+## 3. `pi-durable` assessment
+
+`@earendil-works/pi-durable` is a candidate for a later runtime migration, not
+a drop-in replacement for the removed `pi-agent-core` helpers. The
+[upstream README](https://github.com/earendil-works/pi/blob/main/packages/durable/README.md)
+currently marks the API experimental and subject to change. It provides a
+complete `Harness` over `Session` storage, immutable conversation entries,
+atomic commits, task checkpoints, compaction, and recovery. Its Node adapters
+include SQLite and JSONL storage; the README states that one process owns a
+storage at a time and that cross-process locking is not provided.
+
+Those semantics differ from PI-Desktop's current boundary: Rust host-core owns
+the SQLite database and session records, while Node owns the in-memory agent
+loop. Do not open a second SQLite writer against host-core's database. Before
+adopting the durable harness, a separate ADR must compare these options:
+
+1. Implement `pi-durable`'s `Storage` contract over host-core RPC, including
+ the atomic transaction guarantees and storage conformance tests it expects.
+2. Keep host-core as the source of truth and use an in-memory durable harness,
+ with explicit reconstruction and recovery semantics from the host transcript.
+3. Retain the current desktop-owned runtime if neither option preserves session
+ compatibility and the existing host permission boundary.
+
+The decision must account for existing SQLite data, JSONL/native Pi sessions,
+checkpoint ordering, duplicate submissions, cancellation, process restart,
+tool replay safety, and the single-writer rule. Any change to the frozen Rust
+storage ownership or RPC contract requires a new ADR and a data migration plan.
+
+## 4. Removing `pi-coding-agent`
+
+The dependency is not a foundation for new agent-runtime code. Remove it after
+these replacement seams are complete:
+
+1. Replace `native-pi-session.ts`'s `AgentSession`, `SessionManager`,
+ `ModelRuntime`, resource loader, trust-manager, and native compaction calls
+ with a desktop-owned reader/writer over the existing native Pi JSONL format
+ and the stable pi agent loop.
+2. Keep the extension SDK contract backward compatible while making the
+ runtime shim and any exported extension types desktop-owned. Preserve the
+ current virtual-module behavior and discovery rules.
+3. Remove the direct dependency, update package pins and patches together, and
+ run native session, trusted-extension, compaction, build, and package-bundle
+ checks against the new dependency graph.
+
+Until then, new imports from `pi-coding-agent` require a concrete compatibility
+need and must stay behind the native-session or extension-compatibility seams.
+Do not move removed `pi-agent-core` APIs there as a shortcut.
+
+## 5. Compatibility invariants
+
+- Renderer, Electron Main, host-core, and sidecar ownership remain unchanged.
+- Existing session data and public RPC / Plugin SDK contracts remain readable.
+- The full transcript stays visible; compaction only changes model context and
+ persists through host-core.
+- Cancellation, provider retry, hosted-search validation, tool ordering, and
+ extension discovery retain their current behavior.
+- Any future switch to `pi-durable` is independently reviewed because it
+ changes the runtime/session lifecycle and cannot be inferred from a package
+ version update.
diff --git a/docs/spec/02-architecture/README.md b/docs/spec/02-architecture/README.md
index 379d5092c..37cc8fe64 100644
--- a/docs/spec/02-architecture/README.md
+++ b/docs/spec/02-architecture/README.md
@@ -7,3 +7,4 @@
| [03-repo-structure.md](03-repo-structure.md) | Repository structure |
| [04-documentation-site.md](04-documentation-site.md) | Documentation site |
| [05-remote-agent-control.md](05-remote-agent-control.md) | Remote Agent Host and Gateway target architecture |
+| [06-pi-runtime-dependency-boundary.md](06-pi-runtime-dependency-boundary.md) | pi runtime package boundaries, pi-durable assessment, and pi-coding-agent removal path |
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 0262e800a..91bb9d8dd 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -372,16 +372,14 @@ The complete visible transcript and the model context are separate views of
the same session. A durable checkpoint summarizes older model context while
the renderer continues to show every original user, assistant, and tool row.
-PI-Desktop reuses pi-agent-core's `convertToLlm`, `estimateContextTokens`,
-`prepareCompaction`, and `compact` primitives, and applies the same session
-context projection pi used to export as `buildSessionContext` (slice from the
-newest compaction, then `compactionSummary` before the retained tail). pi 0.85
-moved that helper off the public package export and made the remaining
-internal builder async for custom-entry projectors; the desktop runtime keeps
-a synchronous local copy because it synthesizes only message and compaction
-entries. The desktop runtime owns when they run and how the result crosses the
-Rust storage boundary; OpenCode DCP is an AGPL-3.0 behavioral reference only,
-not a linked or copied dependency.
+PI-Desktop uses pi-agent-core for the agent loop and stable agent/event/tool
+types, and pi-ai for provider-facing requests and message estimation. The
+runtime owns its context projection, LLM-message conversion, token-estimation
+adapter, compaction cut-point selection, and summary generation because the
+older experimental pi-agent-core harness APIs have been removed. These helpers
+preserve the existing session/checkpoint behavior while keeping the Rust host
+as the only durable session owner; OpenCode DCP remains an AGPL-3.0 behavioral
+reference only, not a linked or copied dependency.
Compaction follows Codex's mechanism (ADR 0064, amended by D623): it remains
inline at turn boundaries, and the model can request it through `new_context`.
@@ -425,11 +423,10 @@ emits `compaction_end`. The blocking path composes the two back to back.
**What survives a checkpoint.** A successful checkpoint leaves the model context
as the summary plus, at most, one **user** message; assistant and tool messages
-are dropped from model context and remain in the visible transcript. pi's
-`prepareCompaction` still chooses the cut point, so its turn-boundary and
-split-turn handling are preserved, but the runtime then folds the split-turn
-prefix and the recent tail back into the summary input, so the summary covers
-the whole compacted range and nothing crosses the boundary uncovered.
+are dropped from model context and remain in the visible transcript. The
+runtime-owned preparation chooses the cut point and preserves turn-boundary
+and split-turn handling, then folds the split-turn prefix and recent tail back
+into the summary input so the summary covers the whole compacted range.
A **retained-tail fallback** is the exception, because no summary covers its
range: it keeps the real recent window — the newest contiguous messages of the
@@ -503,8 +500,8 @@ The hard boundary is the model context window minus request headroom. Automatic
compaction starts at 90% of `hardLimit`; this deterministic margin is not
configurable. Headroom is the maximum of a 16,384-token reserve floor, model
maximum output capped at 25% of the context window, and a 5% safety margin. The
-reserve floor is itself capped at half the window. The cut-point target passed
-to pi is derived from the model window as 20% of the hard budget clamped to
+reserve floor is itself capped at half the window. The cut-point target used by
+the runtime-owned preparation is derived from the model window as 20% of the hard budget clamped to
8,000–64,000 tokens, then capped at half the hard budget; it decides where the
boundary falls, not what survives it. The active-user retention limit is
20,000 tokens, capped at half the hard budget so retention alone cannot fill a
@@ -514,10 +511,10 @@ recovery notice leave, so recovery cannot install a checkpoint the guard
rejects. None of these values are configurable.
**Estimate calibration (D606).** Every threshold above is compared against one
-number, corrected against observed request usage. pi's `estimateContextTokens`
-anchors on the last assistant usage and estimates everything after it as
-`chars / 4`: that constant under-counts CJK text, and with no anchor left it
-omits system/tool overhead. The budget also computes the output-cap estimator
+number, corrected against observed request usage. The runtime estimator anchors
+on the last assistant usage and delegates provider-message estimation to
+pi-ai; desktop-only rows use the existing character heuristic. With no usage
+anchor, the budget also computes the output-cap estimator
over non-system conversation messages plus the current system prompt and active
tool schemas. System-transcript rows are metadata snapshots of that same prompt
and are excluded from this component, so the request estimate counts the prompt
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 35fadaa4d..495d26d40 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -333,7 +333,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.
| D127 | Context-preserving reseed + transport retry | **Reseeding a recreated pi runtime from the persisted transcript restores tool call/result pairs (from tool rows' `toolCallId`/`toolArgs`/`toolResult`) in addition to user/assistant text and thinking. Interrupted tool rows restore as errored results; orphaned tool rows get a synthesized call-only assistant carrier so pairs stay adjacent and well-formed. Failed assistant turns stay transcript-only. Separately, request setup uses one bounded pi-ai retry for transient transport/provider failures; post-response stream recovery is defined by D186.** | Text-only reseed collapsed a session's context after any runtime recreation (regenerate/edit, config change, restart): the model lost every tool result it had gathered and — seeing its own history answer without visible tool use — stopped calling tools, degrading agent sessions into bare chat. The incident trigger was a single un-retried provider timeout that forced the user into regenerate. D127 corrects the initially duplicated D120 identifier; D120 remains the earlier application-update decision frozen by baseline 0.4.6. |
| D136 | pi-ai owns known-model metadata | **Historical decision, superseded for chat metadata by D639 / ADR `models-dev-catalog-authority`.** Previous text: resolved Pi records governed published metadata; unknown IDs used generic metadata. **This supersedes D102 and the provider-override clauses of D096/D107.** | A second desktop-owned model matrix had previously discarded Pi metadata. The later D639 root-cause evidence showed that Pi sibling defaults could misstate the selected model's context window. |
| D183 | Segmented tool and model latency logs *(superseded by D385 / ADR 0212; UI clause superseded by D184)* | **Every `tools.execute` call is timed in segments instead of one opaque duration: host-core emits a `tool timing` line on the `host` channel and persists `prompted`, `permissionWaitMs`, `overheadMs`, and `totalMs` next to the existing `durationMs` on `tool_execute` / `tool_denied` audit rows; the sidecar writes greppable `[timing] kind=tool …` (`hostRttMs`) and `[timing] kind=model …` (`providerWaitMs`, `streamMs`, including failed/aborted turns) lines to the `agent` channel, suppressible with `PI_DESKTOP_TIMING=0`. The original no-UI clause is superseded by D184; logging remains unchanged.** | "Executing a command is slow" was undiagnosable from the logs: approval waiting, the tool body, and the provider round trip were indistinguishable, so a 45s gap between two audit rows with 0ms durations gave no clue whether it was the user, the model, or the host. Splitting the stages makes the answer readable without reproducing the run. |
-| D158 | Turn-boundary context checkpoint compaction *(soft-boundary, model-tool, and visibility clauses superseded by D200; the model tool and visibility restored in Codex's shape by D203)* | **PI-Desktop reuses pi-agent-core's context estimation, session-context, and compaction primitives but owns the orchestration and durability. After every `turn_end`, before any next provider request, the runtime evaluates model-aware soft/hard budgets. A transient deduplicated instruction can ask the model to call the internal `CompactContext` tool; the tool's normal activity row is visible/durable, while the instruction is not. Crossing the hard budget forces checkpoint generation and blocks the request on failure. A final atomic tool batch that reaches half the hard budget is fairly head/tail-truncated only in the checkpoint copy, with explicit markers and every call/result envelope retained; original transcript rows remain complete. Exact provider overflow removes the failed assistant from model context, creates one checkpoint, and retries once. Host protocol v6 appends checkpoint records beside the untouched visible JSONL transcript; restart, late truncation, and included-boundary forks preserve the newest valid checkpoint. Disabling automatic compaction removes the tool and all automatic threshold/overflow recovery, while `/compact` remains available. OpenCode DCP is an AGPL-3.0 behavioral reference only and is neither linked nor copied (ADR 0030).** | pi's end-of-run-only behavior cannot protect long tool loops, and a model reminder alone cannot guarantee provider safety. Reusing pi's tested compaction format while adding a deterministic `turn_end` gate prevents another provider request from crossing the known window, retains user-visible history, and avoids importing an incompatible plugin/runtime and license boundary. |
+| D158 | Turn-boundary context checkpoint compaction *(soft-boundary, model-tool, and visibility clauses superseded by D200; the model tool and visibility restored in Codex's shape by D203)* | **PI-Desktop owns context estimation, session-context projection, compaction preparation, and summary generation; pi-agent-core supplies the agent loop and stable types. After every `turn_end`, before any next provider request, the runtime evaluates model-aware soft/hard budgets. A transient deduplicated instruction can ask the model to call the internal `CompactContext` tool; the tool's normal activity row is visible/durable, while the instruction is not. Crossing the hard budget forces checkpoint generation and blocks the request on failure. A final atomic tool batch that reaches half the hard budget is fairly head/tail-truncated only in the checkpoint copy, with explicit markers and every call/result envelope retained; original transcript rows remain complete. Exact provider overflow removes the failed assistant from model context, creates one checkpoint, and retries once. Host protocol v6 appends checkpoint records beside the untouched visible JSONL transcript; restart, late truncation, and included-boundary forks preserve the newest valid checkpoint. Disabling automatic compaction removes the tool and all automatic threshold/overflow recovery, while `/compact` remains available. OpenCode DCP is an AGPL-3.0 behavioral reference only and is neither linked nor copied (ADR 0030).** | pi's end-of-run-only behavior cannot protect long tool loops, and a model reminder alone cannot guarantee provider safety. Keeping checkpoint behavior in the desktop runtime while adding a deterministic `turn_end` gate prevents another provider request from crossing the known window, retains user-visible history, and avoids importing an incompatible plugin/runtime and license boundary. |
| D185 | Lazy per-turn tool activation *(the always-active `CompactContext` clause is void under D200, and holds again for `new_context` under D203; activation restoration amended by D400 / ADR 0225)* | **The sidecar keeps a complete local tool registry but sends only the mode core set and local `ToolSearch` on each new prompt. `BrowserPreview`, plugin tools, `Skill`, and plugin-development helpers appear as bounded compact catalog entries and are activated by exact-name or capability search; the next turn receives their schemas, native pi-ai deferred search is used when supported, and the in-memory set resets before the next user prompt, then restores only successful activation evidence still present in the effective context and allowed by the current catalog and mode. Host permissions, containment, timeouts, and audits are unchanged.** | Full tool schemas made simple first requests disproportionately large and repeated optional capability cost across turns. A pi-style active set preserves core coding ergonomics while making ancillary tools pay-as-you-go and provider-independent; restoring successful context evidence prevents the model from seeing a capability marker without receiving the corresponding schema. |
| D200 | Imperceptible background context compaction *(background pre-computation, incremental trigger, silence, and no-model-tool clauses superseded by D203)* | **Compaction becomes a host-owned background activity with no user-visible surface. `contextBudget()` keeps the D158 hard limit and request headroom, derives the retained-tail target from the model window (`clamp(hardLimit * 0.2, 8k, 64k)`, still capped at half the hard budget) instead of settings, and adds `backgroundLimit = floor(hardLimit * 0.7)` as a pre-computation trigger; the soft boundary is deleted. Checkpoint generation is split from installation: `buildCheckpoint` produces one without persisting or activating it, and installation re-estimates, appends through host-core, and emits `compaction_end`. Pre-computation runs only in provider-idle windows — while a tool executes and after a run ends — and only when the context is past the background limit **and** grew by at least the retained-tail target since the newest checkpoint's baseline, so a large tail cannot trigger a summary every turn. A pre-computed checkpoint installs at the next turn boundary or prompt only if its base is still active, its `throughMessageId` anchor still exists, and it still fits the current model's budget; any miss falls through to the unchanged blocking path, and a failed background build is discarded with no event, no persistence, and no ADR 0049 fallback. The `CompactContext` tool, the `<context_management>` nudge, and the host no-confirmation allowlist entry are removed, so triggering is entirely deterministic. `compaction_start`/`compaction_end` gain an optional `phase` (`background` \| `blocking`, absent means `blocking`) and `compaction_end` gains an optional `status { generation, summaryTokens }`; both are additive inside protocol v9. A successful automatic compaction produces no toast, no run-state change, and no transcript row; only a `retained_tail` fallback, an overflow retry, and manual `/compact` still notify. The context usage inspector is the single visible trace, reading `status` and the durable `SessionDetail.compaction`, with the generation counter carried inside the checkpoint's opaque `details` so no record schema change is needed. Settings exposes no compaction controls and persisted `contextCompaction` values are ignored (ADR 0061).** | Compaction was correct but intrusive: it toasted, moved the run state, spent a model turn on a tool call, left a transcript row, and always ran at the moment the user was waiting. Codex's graded trigger and increment-scoped threshold show the summary can be paid for off the critical path, and its host-only triggering removes a class of wasted turns. Deriving budgets from the model window also fixes applying one pair of absolute token counts to both a 32k and a 1M window; keeping the hard boundary untouched means none of this trades provider safety for UX. |
| D201 | Bounded subagents behind a `Task` tool | **Agent mode exposes `Task` when the catalog contains one of the four inline builtins or an enabled global document under `~/.agents/subagents/*.md`. The catalog is loaded by Electron main for the next prompt, is capped at 16, and keeps delegate reports out of the parent model context. There is no project-level subagent capability directory; `.pi/agents` is not scanned.** | Keeping delegation as a bounded tool preserves parent ownership of context and permissions while a global user directory makes personal delegates portable across projects (ADR 0062, ADR 0112). |
@@ -444,7 +444,7 @@ section mirrors only marketplace/catalog items still blocking nothing.
| ID | Topic | Decision | Rationale |
|---|---|---|---|
-| D123 | Composer slash commands, three sources | **Typing `/` at position 0 of the composer opens an inline command menu merging (a) pi prompt templates from `<workspace>/.pi/prompts/*.md` and `~/.pi/agent/prompts/*.md` (project overrides user-global on name conflict; frontmatter `description`/`argument-hint`), (b) builtin palette commands through slash aliases defined in one registry shared with palette search, and (c) plugin palette commands. On send, builtin/plugin invocations execute locally through the existing renderer switch / `commandPalette/execute` without creating a session or prompting the model; template invocations are expanded in the Electron main `agent/prompt` handler before persistence (`parseCommandArgs` + `substituteArgs` from pi-agent-core), persisting `content = expanded` plus a new optional `command` field carrying the typed form; unknown `/foo` is sent as literal text.** | Reuses pi's exact CLI semantics and template assets, keeps agent reseed faithful (reseed replays `content`), and keeps the transcript readable by rendering the typed invocation as a chip (ADR 0024). |
+| D123 | Composer slash commands, three sources | **Typing `/` at position 0 of the composer opens an inline command menu merging (a) pi prompt templates from `<workspace>/.pi/prompts/*.md` and `~/.pi/agent/prompts/*.md` (project overrides user-global on name conflict; frontmatter `description`/`argument-hint`), (b) builtin palette commands through slash aliases defined in one registry shared with palette search, and (c) plugin palette commands. On send, builtin/plugin invocations execute locally through the existing renderer switch / `commandPalette/execute` without creating a session or prompting the model; template invocations are expanded in the Electron main `agent/prompt` handler before persistence using the desktop-owned `parseCommandArgs` + `substituteArgs` adapter, persisting `content = expanded` plus a new optional `command` field carrying the typed form; unknown `/foo` is sent as literal text.** | Preserves pi's CLI argument semantics and template assets while keeping command expansion independent of the removed pi-agent-core harness API; agent reseed remains faithful (reseed replays `content`), and the transcript stays readable by rendering the typed invocation as a chip (ADR 0024). |
| D124 | `@` file references are plain-text light references | **`@` at a token boundary opens a fuzzy file menu over a workspace index served by the new Electron-only channel `pi-desktop/fs/index` (files+dirs, `git ls-files -co --exclude-standard` fast path with ignore-set walk fallback, 8000-entry cap with truncation flag, short TTL cache, workspace-rooted, fails soft without a workspace). Accepting creates the canonical `@rel/path ` reference for files (quoted `@"a b.txt" ` when the path has spaces) and inserts `@dir/` without trailing space for directories; D209 amends completed-file draft presentation without changing the dispatched plain-text path. The model follows references with its Read tool in both Plan and Agent. No prompt content inlining or provider attachment conversion; clipboard file materialization is defined by D197.** | Matches pi CLI's model-facing semantics, avoids context inflation and truncation rules, and keeps user-driven file browsing out of the agent tool/permission path per ADR 0019. |
| D125 | Composer autocomplete interaction and IME contract | **One menu component anchored above the composer, full composer width, focus always stays in the textarea. Keys while open: ↑/↓ cycle with wraparound, Enter/Tab accept, Escape closes only the menu (takes precedence over the composer's clear/blur Escape), typing filters live; Enter never sends while an item is highlighted, and an empty result list counts as closed. The menu closes on outside mousedown, blur, deleting past the trigger character, or session switch. All key handling and trigger detection sit behind the IME guard (`isComposing || keyCode === 229` plus composition start/end tracking): during composition nothing triggers, updates, or intercepts, and state is re-evaluated on compositionend.** | First explicit IME rule in the spec — zh-CN Enter-to-send plus candidate confirmation must never fight the menu; uniform insert-then-dispatch keeps two-Enter flows fast and predictable. |
| D632 | Composer input history recall with ArrowUp/ArrowDown | **Amend D125 / D209 / D301: the accepted submissions of one conversation — a normal or steering prompt and a dispatched slash, extension, or mode command — are recorded newest-first in renderer-local `localStorage` (`pi.desktop.composerInputHistory`, one bounded bucket per conversation held newest-written-first, 100 entries per conversation, 20 conversations, consecutive duplicates collapsed) with the draft text and its file-reference snapshot, and recalling shows only that conversation's prompts. With the autocomplete menu closed and the draft empty (no text and no references), ArrowUp loads the newest entry and further ArrowUp walks older entries to the oldest; ArrowDown walks newer entries and past the newest returns to the empty draft. While browsing, both keys keep driving history even for a multi-line entry; any user input event, a submission, or a draft-key (session) change ends browsing, after which arrows are native again. IME composition and an open autocomplete menu keep priority over history. Because an entry is always recalled in the conversation that sent it, its file and image references are restored with its text, and no cross-conversation notice or i18n string exists. The caret moves to the end of the recalled text; the empty home composer (no conversation) recalls nothing, and a prompt sent from home is recorded in the conversation that submission materialized. Storage is best-effort: a missing, blocked, or corrupted store reads as empty and never breaks sending. No protocol, host, storage-schema, permission, theme, or packaging change. See `04-ux/09-interaction-patterns.md` and E2E-COMPOSER-input-history-recall.** | Retyping or re-copying a previous instruction is the most repeated composer action, and the app already keeps renderer-local MRU history for the plugin launcher (D219). Scoping the history to the conversation keeps a recalled draft's context intact and makes attachment restoration unconditional, because attachments live in that conversation's own scratch directory. |
diff --git a/docs/spec/NAV.md b/docs/spec/NAV.md
index d26fc9270..13e0fdf22 100644
--- a/docs/spec/NAV.md
+++ b/docs/spec/NAV.md
@@ -19,6 +19,7 @@
- [04-documentation-site.md](02-architecture/04-documentation-site.md)
- [03-repo-structure.md](02-architecture/03-repo-structure.md)
- [05-remote-agent-control.md](02-architecture/05-remote-agent-control.md)
+- [06-pi-runtime-dependency-boundary.md](02-architecture/06-pi-runtime-dependency-boundary.md)
## 3. Runtime
- [README.md](03-runtime/README.md)
diff --git a/docs/zh-CN/spec/02-architecture/02-tech-stack.md b/docs/zh-CN/spec/02-architecture/02-tech-stack.md
index 764752033..faf585f4f 100644
--- a/docs/zh-CN/spec/02-architecture/02-tech-stack.md
+++ b/docs/zh-CN/spec/02-architecture/02-tech-stack.md
@@ -15,13 +15,16 @@
| 主机后端 | **Rust** | 稳定的 Rust 工具链 | tools/plugins/permissions/persistence 适配器 |
| Rust 异步 | 东京 | 稳定 | 主机服务 |
| 主机 RPC | stdio JSON-RPC (NDJSON) | 冷冻(D001) | Electron 主 ↔ Rust 主机 |
-| Agent 引擎 | `@earendil-works/pi-agent-core` | 0.99.1 | 代理循环 |
+| Agent 引擎 | `@earendil-works/pi-agent-core` | 0.99.1 | Agent 循环及稳定的 agent/event/tool 类型 |
| 模型 API | `@earendil-works/pi-ai` | 0.99.1 | 提供商 |
| Model catalog | pi-ai Providers/Models | pinned 0.99.1 + explicit provider refresh | account-scoped metadata and typed operations |
-> pi-ai owns published metadata, native thinking support, transports and auth.
-> Host retains Desktop account rows, credentials and explicit binding overrides.
-> No AgentSession, Codemode or virtual routing is adopted by this migration.
+> pi-ai 提供已发布的模型元数据、原生思考能力、传输和认证。
+> Host 持有 Desktop 账户行、凭据和显式绑定覆盖。
+> Agent Runtime 自行维护桌面上下文投影和检查点压缩。过渡期内,
+> pi-coding-agent 仅用于原生 Pi 会话续接和可信扩展兼容 shim;它不负责
+> Desktop Agent 循环、压缩或持久会话存储。详见
+> [pi 运行时依赖边界](06-pi-runtime-dependency-boundary.md)。
| Node 运行时 | Node.js | `>= 22.19` | 圆周率要求 |
| 数据库 | SQLite | Rust host-core 通过 `rusqlite` | sessions/settings |
diff --git a/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md b/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md
new file mode 100644
index 000000000..006c7af22
--- /dev/null
+++ b/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md
@@ -0,0 +1,72 @@
+# 06. pi 运行时依赖边界
+
+> **翻译说明:** 本页是与 [英文源规格](/spec/02-architecture/06-pi-runtime-dependency-boundary) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。
+
+## 1. 目的
+
+PI-Desktop 使用 pi Agent 循环,但不把 CLI 会话运行时或桌面持久化交给
+JavaScript 包。上游包演进时,必须保持这一职责划分清晰。
+
+## 2. 当前职责
+
+- `@earendil-works/pi-agent-core` 提供 Agent 循环,以及稳定的 agent、event、tool
+ 类型。Agent Runtime 自行维护桌面专用的上下文投影、压缩和 prompt 模板展开。
+- `@earendil-works/pi-ai` 提供提供商传输、认证、消息类型、请求重试和 token 估算。
+ Hosted search 请求与估算行为继续由 PI-Desktop 的 pi-ai 补丁和契约测试覆盖。
+- Rust `host-core` 仍然是 SQLite 和权威持久会话状态的唯一所有者。Node sidecar
+ 通过现有 RPC 契约请求持久化检查点和工具结果。
+- `@earendil-works/pi-coding-agent` 是过渡期依赖。生产代码仅在原生 Pi 会话续接及
+其 session-file manager 中使用;该路径仍使用包内 `AgentSession` 和原生会话行为。
+可信扩展由 `extensions/loader.ts` 提供小型兼容 shim。Desktop 常规 Agent 运行时、
+host-core 检查点压缩路径和持久会话存储不使用其 `AgentSession`。
+
+不要重新引入已移除的 pi-agent-core harness、session、compaction 或 prompt-template
+API。桌面行为留在 `agent-runtime` 边界内;提供商操作使用 pi-ai 的公开 API。
+
+## 3. `pi-durable` 评估
+
+`@earendil-works/pi-durable` 可作为后续运行时迁移的候选方案,但不是已移除
+pi-agent-core helper 的直接替代品。其[上游 README](https://github.com/earendil-works/pi/blob/main/packages/durable/README.md)
+当前将 API 标为实验性,并说明接口可能变化。它提供围绕 `Session` 存储的完整 `Harness`,
+包括不可变会话条目、
+原子提交、任务检查点、压缩和恢复;Node adapter 包括 SQLite 与 JSONL 存储。README
+同时说明,同一份存储一次由一个进程持有,且没有跨进程锁。
+
+这些语义与 PI-Desktop 的当前边界不同:Rust host-core 拥有 SQLite 数据库和会话
+记录,Node 只拥有内存中的 Agent 循环。不能对 host-core 数据库开启第二个 SQLite
+写入者。采用 durable harness 前,需通过单独 ADR 比较以下选择:
+
+1. 通过 host-core RPC 实现 `pi-durable` 的 `Storage` 契约,并覆盖其原子事务保证和
+ 存储一致性测试。
+2. 保留 host-core 作为事实来源,使用内存 durable harness,并明确从 host transcript
+ 重建与恢复的语义。
+3. 如果上述方案都不能保留会话兼容性和现有 host 权限边界,则继续使用当前桌面自有
+ 运行时。
+
+决策需覆盖现有 SQLite 数据、JSONL/原生 Pi 会话、检查点顺序、重复提交、取消、进程
+重启、工具重放安全和单写入者规则。任何冻结的 Rust 存储所有权或 RPC 契约变更都需要
+新的 ADR 和数据迁移方案。
+
+## 4. 后续移除 `pi-coding-agent`
+
+该依赖不是新 agent-runtime 功能的基础。完成以下替代接口后再移除:
+
+1. 用桌面自有的读写实现替换 `native-pi-session.ts` 中的 `AgentSession`、
+ `SessionManager`、`ModelRuntime`、资源加载器、trust-manager 和原生压缩调用;
+ 实现应读取既有原生 Pi JSONL 格式,并使用稳定的 pi Agent 循环。
+2. 保持扩展 SDK 契约向后兼容,同时让运行时 shim 和导出的扩展类型归 PI-Desktop
+ 所有。保留现有 virtual-module 行为与发现规则。
+3. 一并移除直接依赖、更新包固定版本和补丁,然后对新依赖图运行原生会话、可信扩展、
+ compaction、构建和 package bundle 检查。
+
+在此之前,新增 `pi-coding-agent` 导入必须有明确兼容原因,并限制在原生会话或扩展兼容
+边界内。不要为了接替已移除的 pi-agent-core API 而把这些 API 转移到该包。
+
+## 5. 兼容性不变量
+
+- Renderer、Electron Main、host-core 和 sidecar 的职责保持不变。
+- 现有会话数据及公开 RPC / Plugin SDK 契约仍可读取。
+- 完整转录继续可见;压缩只改变模型上下文,并通过 host-core 持久化。
+- 取消、提供商重试、hosted-search 校验、工具顺序和扩展发现保持当前行为。
+- 未来切换 `pi-durable` 必须单独评审,因为它会改变运行时/会话生命周期,不能仅由
+ 包版本升级推导出来。
diff --git a/docs/zh-CN/spec/02-architecture/README.md b/docs/zh-CN/spec/02-architecture/README.md
index 594b0246b..7081310d2 100644
--- a/docs/zh-CN/spec/02-architecture/README.md
+++ b/docs/zh-CN/spec/02-architecture/README.md
@@ -10,3 +10,4 @@
| [03-repo-struct.md](/zh-CN/spec/02-architecture/03-repo-structure) | 存储库结构 |
| [04-documentation-site.md](/zh-CN/spec/02-architecture/04-documentation-site) | 文档站点 |
| [05-remote-agent-control.md](/zh-CN/spec/02-architecture/05-remote-agent-control) | 远程 Agent Host 和 Gateway 目标架构 |
+| [06-pi-runtime-dependency-boundary.md](/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary) | pi 运行时依赖边界、pi-durable 评估和 pi-coding-agent 后续移除路径 |
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index e98492af2..b01ed892e 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -278,11 +278,12 @@ E2E-SESSION-completion-notice-allows-silence。
同一个会话。持久检查点总结了旧模型上下文,同时
渲染器继续显示每个原始用户、助手和工具行。
-PI-Desktop 复用 pi-agent-core 的 `buildSessionContext`、`convertToLlm`、
-`estimateContextTokens`、`prepareCompaction` 和 `compact` 原语。桌面运行时拥有
-这些原语的运行时机,以及结果如何穿过 Rust 存储
-边界; OpenCode DCP 仅是 AGPL-3.0 行为参考,不是链接或
-复制的依赖关系。
+pi-agent-core 提供 Agent 循环及稳定的 agent/event/tool 类型,pi-ai 提供面向
+提供商的请求与消息估算。由于旧版实验性 harness API 已被移除,运行时自行维护
+上下文投影、LLM 消息转换、token 估算适配器、压缩切点选择和摘要生成。这些实现
+保留现有会话与检查点行为,并继续由 Rust host 独占持久会话状态;OpenCode DCP
+仅作为 AGPL-3.0 行为参考,不是链接或复制的依赖关系。详细依赖边界见
+[pi 运行时依赖边界](../02-architecture/06-pi-runtime-dependency-boundary.md)。
压缩遵循 Codex 的机制 (ADR 0064):它总是内联发生在
回合边界,模型可以通过`new_context`请求,每次compaction
@@ -323,11 +324,9 @@ pi 0.84.4+ 只在循环将要在同一次运行中开启另一个助手回合时
发出 `compaction_end`。阻塞路径将两者背靠背组成。
**在检查点中幸存下来的内容。** 成功检查点留下的模型上下文是
-摘要以及最多一条**用户**消息;助手和工具消息是
-从模型上下文中删除并保留在可见的转录本中。圆周率
-`prepareCompaction` 仍然选择切点,因此其回合边界和
-保留分割回合处理,但运行时会折叠分割回合
-前缀和最近的尾部返回到摘要输入中,因此摘要涵盖
+摘要以及最多一条**用户**消息;助手和工具消息会从模型上下文中删除,
+但仍保留在可见的转录本中。运行时自有的准备逻辑选择切点并保留回合边界
+和分割回合处理,然后把分割回合前缀和最近尾部折叠回摘要输入,因此摘要涵盖
整个紧凑的范围内,没有任何东西跨越边界而未被覆盖。
**保留尾部回退**是例外,因为没有摘要覆盖它负责的范围:它保留真实的近期窗口——
diff --git a/docs/zh-CN/spec/NAV.md b/docs/zh-CN/spec/NAV.md
index 1b697ac28..9b81c23db 100644
--- a/docs/zh-CN/spec/NAV.md
+++ b/docs/zh-CN/spec/NAV.md
@@ -22,6 +22,7 @@
- [04-documentation-site.md](/zh-CN/spec/02-architecture/04-documentation-site)
- [03-repo-structure.md](/zh-CN/spec/02-architecture/03-repo-structure)
- [05-remote-agent-control.md](/zh-CN/spec/02-architecture/05-remote-agent-control)
+- [06-pi-runtime-dependency-boundary.md](/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary)
## 3. 运行时
- [README.md](/zh-CN/spec/03-runtime/README)
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index 095b9bf98..4e1d2e3c1 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -33,7 +33,8 @@
"@pi-desktop/shared": "workspace:*",
"jiti": "2.7.0",
"typebox": "1.3.27",
- "undici": "8.10.2"
+ "undici": "8.10.2",
+ "yaml": "2.9.0"
},
"devDependencies": {
"@types/node": "^24.13.3",
diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.ts
index 708d4e35e..1143dde63 100644
--- a/packages/agent-runtime/src/compaction-request.ts
+++ b/packages/agent-runtime/src/compaction-request.ts
@@ -1,14 +1,14 @@
/**
* Outbound headers for the context-compaction summary request.
*
- * pi-agent-core owns that request: `compact` assembles its own stream options
- * and hands them straight to `Models.completeSimple`, so the call never passes
+ * The desktop-owned compaction adapter assembles the request options and calls
+ * `Models.completeSimple` directly, so the call never passes
* the agent's `streamFn` where every other request of a session picks up its
* provider headers. OpenCode Go answers 400 to a request without
* `x-opencode-session`, which is why `/compact` failed on that provider while
* ordinary turns worked, and a provider row's own custom headers were missing
- * from the same call. `compact` takes the model collection as an argument, so
- * the collection is the seam that reaches its one request.
+ * from the same call. The adapter takes the model collection as an argument,
+ * so the collection is the seam that reaches its request.
*/
import { accountModelResult, nativeCostStatus, requestUsageIdentity, type UsageObserver } from "./request-usage.js";
@@ -35,8 +35,8 @@ import { compactionRequestShape, type CompactionRequestShape } from "./compactio
/**
* The header set `streamFn` puts on a turn, applied to a summary request.
*
- * The session id is the runtime's own, not the per-call id pi-agent-core falls
- * back to, so the summary reaches the same gateway backend as the conversation
+ * The session id is the runtime's own, not a per-call id, so the summary reaches
+ * the same gateway backend as the conversation
* it summarizes — the same id the session's turns already send.
*/
export function compactionRequestOptions(input: {
@@ -72,7 +72,7 @@ const SUMMARY_CONVERSATION_APIS = new Set([
/**
* pi-ai's Responses adapters attach `prompt_cache_key` only while the caller
- * keeps some cache retention, and pi-agent-core asks for `"none"` on a summary,
+ * keeps some cache retention, and the summary adapter asks for `"none"`,
* so the summary alone loses the conversation identity the adapter would have
* sent. Restore it for the Responses-shaped APIs and leave every other payload
* byte-identical. The adapter's own object is never mutated: the key rides a
@@ -99,9 +99,8 @@ function withSummaryPromptCacheKey(input: {
/**
* `models` with compaction's request routed through that header boundary.
*
- * Only `completeSimple` is reached from `compact`; every other member stays the
- * collection's own, so a later pi-agent-core release that calls something else
- * keeps working unchanged.
+ * Only `completeSimple` is reached from desktop compaction; every other member
+ * stays the collection's own, so future adapter changes remain isolated here.
*/
export function withCompactionRequestHeaders(
models: Models,
diff --git a/packages/agent-runtime/src/compaction-summary-input.test.ts b/packages/agent-runtime/src/compaction-summary-input.test.ts
index 2adf69d45..c2f14df00 100644
--- a/packages/agent-runtime/src/compaction-summary-input.test.ts
+++ b/packages/agent-runtime/src/compaction-summary-input.test.ts
@@ -1,8 +1,6 @@
import { describe, expect, it } from "vitest";
-import {
- estimateTokens,
- type AgentMessage,
-} from "@earendil-works/pi-agent-core";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { estimateTokens } from "./pi-runtime-estimates.js";
import {
addSummaryUsage,
compactionSummaryInputLimit,
diff --git a/packages/agent-runtime/src/compaction-summary-input.ts b/packages/agent-runtime/src/compaction-summary-input.ts
index 012701b87..0fa5e94fb 100644
--- a/packages/agent-runtime/src/compaction-summary-input.ts
+++ b/packages/agent-runtime/src/compaction-summary-input.ts
@@ -1,25 +1,24 @@
import {
- convertToLlm,
- estimateTokens,
- serializeConversation,
type AgentMessage,
- type CompactionPreparation,
} from "@earendil-works/pi-agent-core";
import type { RetryPolicy, Usage } from "@earendil-works/pi-ai";
import { truncateMessageText } from "./agent-messages.js";
+import { estimateTokens } from "./pi-runtime-estimates.js";
+import { convertToLlm, serializeConversation } from "./pi-runtime-messages.js";
+import type { CompactionPreparation } from "./pi-runtime-types.js";
import { DEFAULT_MAX_TOKENS } from "./provider-binding.js";
/**
* Sizing and retry policy for the automatic summary request (ADR 0282).
*
- * pi-agent-core serializes the messages it summarizes into one text prompt and
- * caps every tool result at 2 000 characters while doing so. The runtime's
- * budget guard used to add up `estimateTokens` over the raw messages instead,
+ * The desktop summary adapter serializes messages into one text prompt and
+ * caps every tool result at 2 000 characters. The budget guard used to add up
+ * `estimateTokens` over the raw messages instead,
* so a session whose bulk was tool output looked several times larger than the
* prompt it would actually send and was routed to retained-tail recovery
* without ever asking the model (issue #543). These helpers size the prompt the
- * way pi builds it and shrink the input one bounded step — and when even that
- * still does not fit, they split the range into chunks that each do, so the
+ * the way the adapter sends it and shrink the input one bounded step — when
+ * even that does not fit, they split the range into chunks that each do, so the
* budget decides how many requests a summary takes rather than whether the
* model is asked at all (issue #827).
*/
diff --git a/packages/agent-runtime/src/compaction-tail.test.ts b/packages/agent-runtime/src/compaction-tail.test.ts
index f93653a37..0767395bb 100644
--- a/packages/agent-runtime/src/compaction-tail.test.ts
+++ b/packages/agent-runtime/src/compaction-tail.test.ts
@@ -1,8 +1,6 @@
import { describe, expect, it } from "vitest";
-import {
- estimateTokens,
- type AgentMessage,
-} from "@earendil-works/pi-agent-core";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { estimateTokens } from "./pi-runtime-estimates.js";
import {
CHECKPOINT_TRUNCATION_MARKER,
COMPACTION_RETAINED_TAIL_SHAPE,
diff --git a/packages/agent-runtime/src/compaction-tail.ts b/packages/agent-runtime/src/compaction-tail.ts
index ad6fdf26e..c1b8836ad 100644
--- a/packages/agent-runtime/src/compaction-tail.ts
+++ b/packages/agent-runtime/src/compaction-tail.ts
@@ -18,15 +18,13 @@
* existed keep the old one-user-message normalization.
*
* Deliberately dependency-light, like `context-budget.ts`: token estimation is
- * pi-agent-core's, the record guard and the text bounding are the shared
+ * owned by the runtime adapter, the record guard and text bounding are shared
* helpers, and nothing here imports `runtime.ts`, so this module can never form
* a cycle with it.
*/
-import {
- estimateTokens,
- type AgentMessage,
-} from "@earendil-works/pi-agent-core";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { estimateTokens } from "./pi-runtime-estimates.js";
import { isRecord, truncateMessageText } from "./agent-messages.js";
/**
diff --git a/packages/agent-runtime/src/context-budget.ts b/packages/agent-runtime/src/context-budget.ts
index 5ecf73b24..363262772 100644
--- a/packages/agent-runtime/src/context-budget.ts
+++ b/packages/agent-runtime/src/context-budget.ts
@@ -6,17 +6,15 @@
* requests the parent already considers unsafe. Both therefore read the
* formula from here instead of each owning a copy that can drift.
*
- * Deliberately dependency-light — token estimation is delegated to
- * pi-agent-core, and pi-ai only contributes the erased `Model`/`Api` *types*,
- * so this module stays usable from any runtime context and can never form a
- * cycle with `runtime.ts`.
+ * Deliberately dependency-light — token estimation uses the pi-ai utility
+ * boundary through the desktop-owned compatibility adapter, so this module
+ * stays usable from any runtime context and can never form a cycle with
+ * `runtime.ts`.
*/
import type { Api, Model } from "@earendil-works/pi-ai";
-import {
- estimateContextTokens,
- type AgentMessage,
-} from "@earendil-works/pi-agent-core";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { estimateContextTokens } from "./pi-runtime-estimates.js";
import {
DEFAULT_CONTEXT_WINDOW,
DEFAULT_MAX_TOKENS,
diff --git a/packages/agent-runtime/src/context-calibration.ts b/packages/agent-runtime/src/context-calibration.ts
index 95547b0fb..d0f69e7a6 100644
--- a/packages/agent-runtime/src/context-calibration.ts
+++ b/packages/agent-runtime/src/context-calibration.ts
@@ -3,7 +3,8 @@
*
* Every budget decision in this runtime reads one number: the context estimate
* (the automatic compaction check, the idle pre-compaction, and the occupancy
- * the desktop shows). That number comes from pi's `estimateContextTokens`,
+ * the desktop shows). That number comes from the runtime's
+ * `estimateContextTokens`,
* whose shape is:
*
* last assistant usage (real, when the transcript still carries one)
diff --git a/packages/agent-runtime/src/delegation-history.test.ts b/packages/agent-runtime/src/delegation-history.test.ts
index 273940c66..d168d0771 100644
--- a/packages/agent-runtime/src/delegation-history.test.ts
+++ b/packages/agent-runtime/src/delegation-history.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { estimateTokens } from "@earendil-works/pi-agent-core";
+import { estimateTokens } from "./pi-runtime-estimates.js";
import type { Message } from "@earendil-works/pi-ai";
import { MAX_RESUMABLE_READ_LINES, type UiMessage } from "@pi-desktop/shared";
import {
diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.ts
index 588d9028c..282d7d401 100644
--- a/packages/agent-runtime/src/delegation-history.ts
+++ b/packages/agent-runtime/src/delegation-history.ts
@@ -21,7 +21,7 @@
* and api/replay details depend on the binding.
*/
-import { estimateTokens } from "@earendil-works/pi-agent-core";
+import { estimateTokens } from "./pi-runtime-estimates.js";
import type {
AssistantMessage,
Message,
diff --git a/packages/agent-runtime/src/hosted-search-compaction.test.ts b/packages/agent-runtime/src/hosted-search-compaction.test.ts
index e152f5972..32c9ffb36 100644
--- a/packages/agent-runtime/src/hosted-search-compaction.test.ts
+++ b/packages/agent-runtime/src/hosted-search-compaction.test.ts
@@ -1,138 +1,12 @@
-import { realpathSync } from "node:fs";
-import { createRequire } from "node:module";
-import { join } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-
import { describe, expect, it } from "vitest";
import { LocalRequestError } from "@earendil-works/pi-ai";
-import type { Api, AssistantMessage, HostedSearchContent, Message, Model } from "@earendil-works/pi-ai";
-import {
- estimateContextTokens as estimateProviderContextTokens,
- estimateMessageTokens,
-} from "@earendil-works/pi-ai/utils/estimate";
+import type { Api, AssistantMessage, HostedSearchContent, Message } from "@earendil-works/pi-ai";
import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";
-
-/**
- * Compaction hosted-search contract tests.
- *
- * pi-coding-agent and pi-agent-core both carry their own compaction token
- * estimators. These tests pin the bounded completion of that contract:
- *
- * - standard provider roles (system/user/assistant/toolResult) are delegated to
- * the pi-ai estimators, so native hosted search replay buffers grow the
- * estimate exactly like the provider request path does;
- * - the usage anchor is the shared pi-ai rule (a newer prefix timestamp
- * invalidates older assistant usage) and the anchored payload is not counted
- * twice;
- * - an optional target model scopes the hosted search projection, so a model
- * switch cannot overcount replay blocks the target would drop;
- * - internal session roles (custom/bashExecution/branchSummary/compactionSummary)
- * keep their local adapters and the text/thinking/toolCall/image baselines do
- * not move;
- * - serializeConversation keeps each hosted search block's raw wire projection
- * exactly once, without pretending the search was a tool call;
- * - malformed hosted search history fails explicitly instead of being dropped.
- *
- * The modules under test are the installed packages: the test resolves them from
- * its own module graph (createRequire for the manifest, ESM resolution for the
- * module entry) and needs no test-infrastructure shim. The scratch stage loader
- * (compaction-stage-loader.mjs) only redirects those same files to the *-complete
- * pnpm patch edit dirs, so the assertions can run before patch-commit.
- */
-
-const require = createRequire(import.meta.url);
-
-/** Resolve a specifier with the ESM resolver and normalize it to a file URL. */
-function esmResolve(specifier: string): string {
- const resolved = (import.meta as ImportMeta & { resolve(specifier: string): string }).resolve(specifier);
- return resolved.startsWith("file:") ? resolved : pathToFileURL(resolved).href;
-}
-
-/**
- * Resolve the install root of an installed @earendil-works package.
- *
- * pi-agent-core exports "./package.json", so createRequire can read the
- * manifest. pi-ai and pi-coding-agent export neither "./package.json" nor a
- * CommonJS entry (their "." entry only carries the "import" condition), so their
- * root is derived from the module entry resolved by the ESM resolver instead.
- */
-function packageRoot(packageName: string): string {
- try {
- return realpathSync(require.resolve(`${packageName}/package.json`).replace(/[\\/]package\.json$/, ""));
- } catch {
- const entry = fileURLToPath(esmResolve(packageName));
- const marker = entry.lastIndexOf("/dist/");
- if (marker < 0) throw new Error(`cannot locate the dist root of ${packageName}`);
- return realpathSync(entry.slice(0, marker));
- }
-}
-
-const load = async <T>(packageName: string, distRelativePath: string): Promise<T> =>
- (await import(/* @vite-ignore */ pathToFileURL(join(packageRoot(packageName), distRelativePath)).href)) as
- unknown as T;
-
-interface CompactionContextUsage {
- tokens: number;
- usageTokens: number;
- trailingTokens: number;
- lastUsageIndex: number | null;
-}
-
-/** Token estimators shared by both compaction implementations. */
-interface CompactionEstimation {
- estimateTokens(message: Message, model?: Model<Api>): number;
- estimateContextTokens(messages: Message[], model?: Model<Api>): CompactionContextUsage;
-}
-
-/** Summarization serializer shared by both compaction implementations. */
-interface CompactionSerialization {
- serializeConversation(messages: Message[]): string;
-}
-
-/** Selective collapse cutoff helper exported by the pi-agent-core pico3 harness. */
-interface Pico3Collapse {
- chooseThrough(entries: { id: string; model?: Message[] }[], keepRecent: number, model?: Model<Api>): string | undefined;
-}
-const CORE = "@earendil-works/pi-agent-core";
-const CODING = "@earendil-works/pi-coding-agent";
-
-const coreEstimation = await load<CompactionEstimation>(CORE, "dist/harness/compaction/compaction.js");
-const coreSerialization = await load<CompactionSerialization>(CORE, "dist/harness/compaction/utils.js");
-const codingEstimation = await load<CompactionEstimation>(CODING, "dist/core/compaction/compaction.js");
-const codingSerialization = await load<CompactionSerialization>(CODING, "dist/core/compaction/utils.js");
-/** pico3 collapse cutoff helper; its `model` argument scopes hosted search projections. */
-const coreCollapse = await load<Pico3Collapse>(CORE, "dist/harness/pico3/kinds/collapse.js");
-
-const estimators = [
- ["pi-agent-core", coreEstimation],
- ["pi-coding-agent", codingEstimation],
-] as const;
-const serializers = [
- ["pi-agent-core", coreSerialization],
- ["pi-coding-agent", codingSerialization],
-] as const;
-
-/** A generic small test model; tests must not depend on any concrete vendor. */
-function targetModel<TApi extends Api>(api: TApi, id = "test-model"): Model<TApi> {
- return {
- id,
- name: "test",
- api,
- provider: api === "anthropic-messages" ? "anthropic" : "openai",
- baseUrl: "http://localhost",
- reasoning: false,
- input: ["text"],
- contextWindow: 100_000,
- maxTokens: 1_000,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- };
-}
+import { serializeConversation } from "./pi-runtime-messages.js";
function assistant(
content: AssistantMessage["content"],
api: Api = "anthropic-messages",
- tokens = 0,
- timestamp = 2,
): AssistantMessage {
return {
role: "assistant",
@@ -140,30 +14,29 @@ function assistant(
api,
provider: api === "anthropic-messages" ? "anthropic" : "openai",
model: "test-model",
- timestamp,
+ timestamp: 2,
stopReason: "stop",
usage: {
- input: tokens,
+ input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
- totalTokens: tokens,
+ totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
};
}
-const IMAGE: { type: "image"; data: string; mimeType: string } = {
- type: "image",
- data: "AAAA",
- mimeType: "image/png",
-};
-
-/** One provider-native hosted search exchange; `size` grows the replay payload. */
function hostedSearch(size = 1, api: Api = "anthropic-messages"): HostedSearchContent[] {
return api === "anthropic-messages"
? [
- { type: "hostedSearch", phase: "server_tool_use", blockId: "srv_1", name: "web_search", input: { query: "q" } },
+ {
+ type: "hostedSearch",
+ phase: "server_tool_use",
+ blockId: "srv_1",
+ name: "web_search",
+ input: { query: "q" },
+ },
{
type: "hostedSearch",
phase: "web_search_tool_result",
@@ -180,148 +53,62 @@ function hostedSearch(size = 1, api: Api = "anthropic-messages"): HostedSearchCo
type: "hostedSearch",
phase: "web_search_call",
blockId: "ws_1",
- wire: { type: "web_search_call", id: "ws_1", status: "completed", action: { type: "search", query: "x".repeat(size) } },
+ wire: {
+ type: "web_search_call",
+ id: "ws_1",
+ status: "completed",
+ action: { type: "search", query: "x".repeat(size) },
+ },
},
];
}
-describe("compaction hosted search estimation", () => {
- it("grows the estimate when hosted search replay content grows", () => {
- const small = assistant(hostedSearch(1));
- const large = assistant(hostedSearch(4000));
- expect(estimateMessageTokens(large) - estimateMessageTokens(small)).toBeGreaterThan(990);
- for (const [label, estimator] of estimators) {
- // Both native estimators now delegate to the shared provider estimator.
- expect(estimator.estimateTokens(small), label).toBe(estimateMessageTokens(small));
- expect(estimator.estimateTokens(large), label).toBe(estimateMessageTokens(large));
- expect(estimator.estimateTokens(large) - estimator.estimateTokens(small), label).toBeGreaterThan(990);
- expect(estimator.estimateContextTokens([large]), label).toEqual(estimateProviderContextTokens([large]));
- }
- });
-
- it("delegates standard provider roles, including image blocks, to pi-ai", () => {
- const text = "a".repeat(4000);
- const user: Message = { role: "user", content: text, timestamp: 1 };
- const system: Message = { role: "system", content: text, timestamp: 1 };
- const toolResult: Message = {
- role: "toolResult",
- toolCallId: "t1",
- toolName: "read",
- content: [{ type: "text", text }],
- isError: false,
- timestamp: 3,
- };
- const imageUser: Message = { role: "user", content: [IMAGE], timestamp: 1 };
- const textAndImageUser: Message = { role: "user", content: [{ type: "text", text: "a".repeat(400) }, IMAGE], timestamp: 1 };
- const imageToolResult: Message = { ...toolResult, content: [IMAGE] };
- const baselines: [string, Message, number][] = [
- ["user text", user, 1000],
- ["system text", system, 1000],
- ["toolResult text", toolResult, 1000],
- ["user image", imageUser, 1200],
- ["user text+image", textAndImageUser, 1300],
- ["toolResult image", imageToolResult, 1200],
- ];
- for (const [label, estimator] of estimators) {
- for (const [role, message, tokens] of baselines) {
- expect(estimator.estimateTokens(message), `${label} ${role}`).toBe(tokens);
- expect(estimator.estimateTokens(message), `${label} ${role} pi-ai parity`).toBe(estimateMessageTokens(message));
- }
- }
- });
-
- it("anchors usage on the shared pi-ai rule for zero, valid and prefix-invalidated usage", () => {
- const zeroUsage = assistant(hostedSearch(400), "anthropic-messages", 0);
- const valid = assistant(hostedSearch(400), "anthropic-messages", 123);
- const newerPrefix: Message = { role: "user", content: "injected prefix", timestamp: 10 };
- const tail = assistant(hostedSearch(200), "anthropic-messages", 0, 20);
- const failed = { ...assistant(hostedSearch(400), "anthropic-messages", 500), stopReason: "error" as const };
- for (const [label, estimator] of estimators) {
- expect(estimator.estimateContextTokens([zeroUsage]), label).toEqual(estimateProviderContextTokens([zeroUsage]));
- expect(estimator.estimateContextTokens([zeroUsage]).lastUsageIndex, label).toBeNull();
-
- expect(estimator.estimateContextTokens([valid]), label).toEqual({
- tokens: 123,
- usageTokens: 123,
- trailingTokens: 0,
- lastUsageIndex: 0,
- });
-
- // A newer prefix invalidates the older assistant usage instead of scanning backwards.
- expect(estimator.estimateContextTokens([newerPrefix, valid]).lastUsageIndex, label).toBeNull();
- expect(estimator.estimateContextTokens([newerPrefix, valid]), label).toEqual(
- estimateProviderContextTokens([newerPrefix, valid]),
- );
-
- // Aborted/error responses never become the usage anchor.
- expect(estimator.estimateContextTokens([failed]).lastUsageIndex, label).toBeNull();
- expect(estimator.estimateContextTokens([failed]), label).toEqual(estimateProviderContextTokens([failed]));
-
- expect(estimator.estimateContextTokens([valid, tail]), label).toEqual(estimateProviderContextTokens([valid, tail]));
- expect(estimator.estimateContextTokens([valid, tail]).tokens, label).toBe(123 + estimateMessageTokens(tail));
- expect(estimator.estimateContextTokens([valid, tail]).lastUsageIndex, label).toBe(0);
- }
- });
-
- it("does not count the anchored message replay payload twice", () => {
- const valid = assistant(hostedSearch(4000), "anthropic-messages", 123);
- // The payload would be visible if it were charged on top of the usage anchor.
- expect(estimateMessageTokens(valid)).toBeGreaterThan(1000);
- for (const [label, estimator] of estimators) {
- const estimate = estimator.estimateContextTokens([valid]);
- expect(estimate.tokens, label).toBe(123);
- expect(estimate.usageTokens, label).toBe(123);
- expect(estimate.trailingTokens, label).toBe(0);
- }
- });
-
- it("keeps internal session roles on their local adapters", () => {
- const internal: [string, unknown, number][] = [
- ["custom", { role: "custom", content: "12345" }, 2],
- ["custom text+image", { role: "custom", content: [{ type: "text", text: "12345" }, IMAGE] }, 1202],
- ["bashExecution", { role: "bashExecution", command: "1234", output: "5678" }, 2],
- ["branchSummary", { role: "branchSummary", summary: "12345" }, 2],
- ["compactionSummary", { role: "compactionSummary", summary: "12345" }, 2],
- ];
- for (const [label, estimator] of estimators) {
- for (const [role, message, tokens] of internal) {
- expect(estimator.estimateTokens(message as Message), `${label} ${role}`).toBe(tokens);
- }
- }
- });
+describe("desktop compaction hosted-search serialization", () => {
+ it("keeps hosted-search wire projections exactly once without fabricating tool calls", () => {
+ const blocks = hostedSearch(8);
+ const message = assistant([
+ { type: "text", text: "answer text" },
+ ...blocks,
+ { type: "toolCall", id: "t1", name: "read", arguments: { path: "/tmp/x" } },
+ ]);
- it("rejects an unsupported message role explicitly in both packages", () => {
- // Both estimators must fail the same way instead of silently returning 0.
- const unsupported = { role: "notice", content: "hello", timestamp: 1 } as unknown as Message;
- for (const [label, estimator] of estimators) {
- expect(() => estimator.estimateTokens(unsupported), label).toThrow(LocalRequestError);
- expect(() => estimator.estimateTokens(unsupported), `${label} code`).toThrowError(
- expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }),
- );
- expect(() => estimator.estimateContextTokens([unsupported]), `${label} context`).toThrow(LocalRequestError);
+ const output = serializeConversation([message]);
+ expect(output.split("[Assistant hosted search]:").length - 1).toBe(1);
+ for (const block of blocks) {
+ const projection = hostedSearchReplayProjection(block);
+ expect(projection).toBeDefined();
+ expect(output.split(JSON.stringify(projection)).length - 1).toBe(1);
}
+ expect(output.split('"srv_1"').length - 1).toBe(2);
+ expect(output).toContain("[Assistant]: answer text");
+ expect(output).toContain("read(");
+ expect(output).not.toContain("web_search(");
+ expect(output).not.toContain('"hostedSearch"');
});
- it("keeps the text/thinking/toolCall baseline", () => {
- const toolCall = { type: "toolCall" as const, id: "t", name: "run", arguments: { a: 1 } };
- const textTool = assistant([
- { type: "text", text: "12345678" },
- { type: "thinking", thinking: "1234" },
- toolCall,
- ]);
- const expected = Math.ceil((8 + 4 + (toolCall.name.length + JSON.stringify(toolCall.arguments).length)) / 4);
- expect(expected).toBe(6);
- for (const [label, estimator] of estimators) {
- expect(estimator.estimateTokens(textTool), label).toBe(expected);
- expect(estimator.estimateTokens(textTool), `${label} pi-ai parity`).toBe(estimateMessageTokens(textTool));
- }
+ it("keeps a nameless search result and a large replay buffer intact", () => {
+ const nameless: HostedSearchContent = {
+ type: "hostedSearch",
+ phase: "web_search_tool_result",
+ blockId: "srv_9",
+ wire: {
+ type: "web_search_tool_result",
+ tool_use_id: "srv_9",
+ content: [{ type: "web_search_result", encrypted_content: "opaque-result", title: "Result" }],
+ },
+ };
+ const namelessOutput = serializeConversation([assistant([nameless])]);
+ const projection = hostedSearchReplayProjection(nameless);
+ expect(namelessOutput.split(JSON.stringify(projection)).length - 1).toBe(1);
+ expect(namelessOutput).toContain("opaque-result");
+ expect(namelessOutput).not.toContain("undefined(");
+
+ const large = serializeConversation([assistant(hostedSearch(5_000))]);
+ expect(large).toContain("x".repeat(5_000));
});
- it("fails explicitly on malformed hosted search history", () => {
- const emptyBlockId = assistant([
- { type: "hostedSearch", phase: "server_tool_use", blockId: "", name: "web_search", input: { query: "q" } },
- ]);
- const missingResultContent = assistant([
+ it("rejects malformed replay blocks instead of dropping them", () => {
+ const malformed = assistant([
{
type: "hostedSearch",
phase: "web_search_tool_result",
@@ -329,216 +116,30 @@ describe("compaction hosted search estimation", () => {
wire: { type: "web_search_tool_result", tool_use_id: "srv_1" },
},
]);
- const unknownPhase = assistant([
- { type: "hostedSearch", phase: "web_search_pending", blockId: "srv_1" } as unknown as HostedSearchContent,
- ]);
- const invalidTimestamp = assistant(hostedSearch(1), "anthropic-messages", 5, Number.NaN);
- const infiniteTimestamp = assistant(hostedSearch(1), "anthropic-messages", 5, Number.POSITIVE_INFINITY);
- for (const [label, estimator] of estimators) {
- for (const [case_, message] of [
- ["empty block id", emptyBlockId],
- ["unknown phase", unknownPhase],
- ] as const) {
- expect(() => estimator.estimateTokens(message), `${label} ${case_}`).toThrow(LocalRequestError);
- }
- const contextCases: [string, Message[]][] = [
- ["missing result content", [missingResultContent]],
- ["invalid timestamp", [invalidTimestamp]],
- ["infinite timestamp", [infiniteTimestamp]],
- ];
- for (const [case_, messages] of contextCases) {
- expect(() => estimator.estimateContextTokens(messages), `${label} ${case_}`).toThrow(LocalRequestError);
- expect(() => estimator.estimateContextTokens(messages), `${label} ${case_} code`).toThrowError(
- expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }),
- );
- }
- // The same history with a valid zero-usage response still resolves.
- expect(() => estimator.estimateContextTokens([assistant(hostedSearch(1), "anthropic-messages", 0)]), label).not.toThrow();
- }
- });
-});
-
-describe("compaction hosted search target model", () => {
- const anthropicTarget = targetModel("anthropic-messages");
- const responsesTarget = targetModel("openai-responses");
- const anthropicSearch = assistant(hostedSearch(4000));
- const responsesSearch = assistant(hostedSearch(4000, "openai-responses"), "openai-responses");
-
- it("counts replay blocks for the same target in both modules", () => {
- for (const [label, estimator] of estimators) {
- expect(estimator.estimateTokens(anthropicSearch, anthropicTarget), label).toBe(
- estimateMessageTokens(anthropicSearch, anthropicTarget),
- );
- expect(estimator.estimateTokens(responsesSearch, responsesTarget), label).toBe(
- estimateMessageTokens(responsesSearch, responsesTarget),
- );
- expect(estimator.estimateTokens(anthropicSearch, anthropicTarget), label).toBeGreaterThan(900);
- expect(estimator.estimateTokens(responsesSearch, responsesTarget), label).toBeGreaterThan(900);
- }
- });
-
- it("drops replay blocks the switched target would not carry", () => {
- for (const [label, estimator] of estimators) {
- // Anthropic server tool blocks are not replayed to an openai-responses target.
- expect(estimator.estimateTokens(anthropicSearch, responsesTarget), label).toBe(0);
- expect(estimator.estimateTokens(anthropicSearch, responsesTarget), label).toBe(
- estimateMessageTokens(anthropicSearch, responsesTarget),
- );
- // Responses web_search_call blocks are not replayed to an anthropic-messages target.
- expect(estimator.estimateTokens(responsesSearch, anthropicTarget), label).toBe(0);
- expect(estimator.estimateTokens(responsesSearch, anthropicTarget), label).toBe(
- estimateMessageTokens(responsesSearch, anthropicTarget),
- );
- // A responses replay survives only for the model that produced it.
- const otherResponses = { ...responsesTarget, id: "other-model" };
- expect(estimator.estimateTokens(responsesSearch, otherResponses), label).toBe(
- estimateMessageTokens(responsesSearch, otherResponses),
- );
- const otherAnthropic = { ...anthropicTarget, id: "other-model" };
- expect(estimator.estimateTokens(anthropicSearch, otherAnthropic), label).toBe(
- estimateMessageTokens(anthropicSearch, otherAnthropic),
- );
- }
- });
-
- it("stays conservative when the caller has no target model", () => {
- for (const [label, estimator] of estimators) {
- // With partial model facts every replay block is charged rather than assumed away.
- expect(estimator.estimateTokens(anthropicSearch), label).toBe(estimateMessageTokens(anthropicSearch));
- expect(estimator.estimateTokens(responsesSearch), label).toBe(estimateMessageTokens(responsesSearch));
- expect(estimator.estimateTokens(anthropicSearch), label).toBeGreaterThan(
- estimator.estimateTokens(anthropicSearch, responsesTarget),
- );
- expect(estimator.estimateContextTokens([anthropicSearch]), label).toEqual(
- estimateProviderContextTokens([anthropicSearch]),
- );
- }
+ expect(() => serializeConversation([malformed])).toThrow(LocalRequestError);
});
- it("keeps the usage anchor when a target model is provided", () => {
- const valid = assistant(hostedSearch(400), "openai-responses", 123);
- const tail = assistant(hostedSearch(200, "openai-responses"), "openai-responses", 0, 20);
- for (const [label, estimator] of estimators) {
- const estimate = estimator.estimateContextTokens([valid, tail], responsesTarget);
- expect(estimate.lastUsageIndex, label).toBe(0);
- expect(estimate.tokens, label).toBe(123 + estimateMessageTokens(tail, responsesTarget));
- expect(estimate, label).toEqual(estimateProviderContextTokens([valid, tail], responsesTarget));
- }
- });
-});
-
-describe("pico3 collapse cutoff model scoping", () => {
- const anthropicTarget = targetModel("anthropic-messages");
- const responsesTarget = targetModel("openai-responses");
- // One small user exchange followed by an assistant exchange whose hosted search
- // replay buffer exists only for the anthropic target.
- const entries = [
- { id: "u1", model: [{ role: "user", content: "abc", timestamp: 1 } as Message] },
- { id: "a1", model: [assistant(hostedSearch(4000))] },
- ];
- const keepRecent = 100;
-
- it("threads the resolved target model into the cutoff estimate", () => {
- // Without a target every replay block is charged, so the assistant exchange does
- // not fit the retention budget and the cutoff stops before it.
- expect(coreCollapse.chooseThrough(entries, keepRecent)).toBe("u1");
- // Same api: the replay buffer still counts, so the cutoff does not move.
- expect(coreCollapse.chooseThrough(entries, keepRecent, anthropicTarget)).toBe("u1");
- // Switched target: the anthropic buffer is not replayed, the whole history fits
- // and there is nothing to collapse.
- expect(coreCollapse.chooseThrough(entries, keepRecent, responsesTarget)).toBeUndefined();
- // The target model is the only input that changes the outcome.
- expect(estimateMessageTokens(entries[1].model[0], responsesTarget)).toBe(0);
- expect(estimateMessageTokens(entries[1].model[0], anthropicTarget)).toBeGreaterThan(900);
- });
-});
-
-describe("serializeConversation hosted search projection", () => {
- const wired = hostedSearch(8);
- const mixed = assistant([
- { type: "text", text: "answer text" },
- ...wired,
- { type: "toolCall", id: "t1", name: "read", arguments: { path: "/tmp/x" } },
- ]);
-
- for (const [label, serializer] of serializers) {
- it(`${label}: keeps each hosted search wire block exactly once`, () => {
- const out = serializer.serializeConversation([mixed]);
- expect(out.split("[Assistant hosted search]:").length - 1).toBe(1);
- for (const block of wired) {
- const projection = hostedSearchReplayProjection(block);
- expect(projection).toBeDefined();
- expect(out.split(JSON.stringify(projection)).length - 1).toBe(1);
- }
- // The search pair shares srv_1: each block carries it exactly once.
- expect(out.split('"srv_1"').length - 1).toBe(2);
- expect(out).toContain("[Assistant]: answer text");
- expect(out).toContain("read(");
- // The search block stays data: no fabricated tool call and no internal type leak.
- expect(out).not.toContain("web_search(");
- expect(out).not.toContain('"hostedSearch"');
- });
-
- it(`${label}: keeps a nameless search result exactly once`, () => {
- const nameless: HostedSearchContent = {
- type: "hostedSearch",
- phase: "web_search_tool_result",
- blockId: "srv_9",
- wire: {
- type: "web_search_tool_result",
- tool_use_id: "srv_9",
- content: [{ type: "web_search_result", encrypted_content: "opaque-result", title: "Result" }],
- },
- };
- const out = serializer.serializeConversation([assistant([nameless])]);
- const projection = hostedSearchReplayProjection(nameless);
- expect(projection).toBeDefined();
- expect(out.split("[Assistant hosted search]:").length - 1).toBe(1);
- expect(out.split(JSON.stringify(projection)).length - 1).toBe(1);
- expect(out.split("srv_9").length - 1).toBe(1);
- expect(out).toContain("opaque-result");
- expect(out).not.toContain("undefined(");
- expect(out).not.toContain("web_search(");
- });
-
- it(`${label}: keeps the full projection of a large replay buffer`, () => {
- const large = assistant(hostedSearch(5000));
- const out = serializer.serializeConversation([large]);
- expect(out).toContain("x".repeat(5000));
- for (const block of large.content) {
- if (block.type !== "hostedSearch") continue;
- const projection = hostedSearchReplayProjection(block);
- expect(projection).toBeDefined();
- expect(out.split(JSON.stringify(projection)).length - 1).toBe(1);
- }
- });
-
- it(`${label}: fails explicitly on a malformed search block`, () => {
- const malformed = assistant([
- {
- type: "hostedSearch",
- phase: "web_search_tool_result",
- blockId: "srv_1",
- wire: { type: "web_search_tool_result", tool_use_id: "srv_1" },
- },
- ]);
- expect(() => serializer.serializeConversation([malformed])).toThrow(LocalRequestError);
- });
- }
-
it("keeps legacy text-only conversations byte-identical", () => {
const legacy = [
{ role: "user" as const, content: "hello", timestamp: 1 },
- assistant([{ type: "text", text: "hi" }, { type: "toolCall", id: "t", name: "run", arguments: { a: 1 } }]),
- { role: "toolResult" as const, toolCallId: "t", toolName: "run", content: [{ type: "text", text: "done" }], isError: false, timestamp: 3 },
+ assistant([
+ { type: "text", text: "hi" },
+ { type: "toolCall", id: "t", name: "run", arguments: { a: 1 } },
+ ]),
+ {
+ role: "toolResult" as const,
+ toolCallId: "t",
+ toolName: "run",
+ content: [{ type: "text" as const, text: "done" }],
+ isError: false,
+ timestamp: 3,
+ },
];
const expected =
"[User]: hello\n\n" +
"[Assistant]: hi\n\n" +
- '[Assistant tool calls]: run(a=1)\n\n' +
+ "[Assistant tool calls]: run(a=1)\n\n" +
"[Tool result]: done";
- for (const [label, serializer] of serializers) {
- expect(serializer.serializeConversation(legacy as Message[]), label).toBe(expected);
- }
+ expect(serializeConversation(legacy as Message[])).toBe(expected);
});
});
diff --git a/packages/agent-runtime/src/hosted-search-consumers.test.ts b/packages/agent-runtime/src/hosted-search-consumers.test.ts
index b55adb3a6..863e6e2ca 100644
--- a/packages/agent-runtime/src/hosted-search-consumers.test.ts
+++ b/packages/agent-runtime/src/hosted-search-consumers.test.ts
@@ -1,5 +1,3 @@
-import { createRequire } from "node:module";
-import { pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import {
AssistantMessageFrameEncoder,
@@ -22,9 +20,6 @@ import {
} from "@earendil-works/pi-ai/utils/estimate";
import { streamSimple as streamMistral } from "@earendil-works/pi-ai/api/mistral-conversations";
-const require = createRequire(import.meta.url);
-const { applyFrame } = await import(pathToFileURL(require.resolve("@earendil-works/pi-agent-core/package.json").replace(/package\.json$/, "dist/harness/pico3/kinds/frames.js")).href);
-
function assistant(content: AssistantMessage["content"], timestamp = 2, tokens = 0): AssistantMessage {
return {
role: "assistant", content, api: "openai-responses", provider: "openai", model: "source-model",
@@ -108,9 +103,6 @@ describe("hosted-search consumers", () => {
]);
expect(frames.map(frame => frame.type)).toEqual(["start", "hosted_search_update", "text_start", "text_end"]);
expect(reduceAssistantMessageFrames(frames)?.content).toEqual(output.content);
- const tracked: { message?: AssistantMessage } = {};
- for (const frame of frames) applyFrame(tracked, structuredClone(frame));
- expect(tracked.message?.content).toEqual(reduceAssistantMessageFrames(frames)?.content);
});
}
it("replaces snapshots without duplicating blocks and detaches nested wire data", () => {
diff --git a/packages/agent-runtime/src/hosted-search-estimation.test.ts b/packages/agent-runtime/src/hosted-search-estimation.test.ts
index 151ec971d..f355f188c 100644
--- a/packages/agent-runtime/src/hosted-search-estimation.test.ts
+++ b/packages/agent-runtime/src/hosted-search-estimation.test.ts
@@ -1,14 +1,20 @@
-import { createRequire } from "node:module";
-import { pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import type { AssistantMessage, Model, Api } from "@earendil-works/pi-ai";
import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
import { convertResponsesMessages } from "@earendil-works/pi-ai/api/openai-responses-shared";
import { LocalRequestError, localRequestErrorDetails, normalizeHostedSearchContent, normalizeContext } from "@earendil-works/pi-ai";
import type { HostedSearchContent, AssistantMessageEvent } from "@earendil-works/pi-ai";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import {
+ estimateContextTokens as estimateDesktopContextTokens,
+ estimateTokens as estimateDesktopTokens,
+} from "./pi-runtime-estimates.js";
-const require = createRequire(import.meta.url);
-const compaction = await import(pathToFileURL(require.resolve("@earendil-works/pi-agent-core/package.json").replace(/package\.json$/, "dist/harness/compaction/compaction.js")).href);
+const compaction = {
+ estimateTokens: (message: unknown) => estimateDesktopTokens(message as AgentMessage),
+ estimateContextTokens: (messages: unknown[]) =>
+ estimateDesktopContextTokens(messages as AgentMessage[]),
+};
const apis = ["openai-responses", "azure-openai-responses", "anthropic-messages"] as const;
function model<TApi extends Api>(api: TApi): Model<TApi> {
return { id: "test-model", name: "test", api, provider: api === "anthropic-messages" ? "anthropic" : "openai", baseUrl: "http://localhost", reasoning: false, input: ["text"], contextWindow: 100_000, maxTokens: 1000, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } };
diff --git a/packages/agent-runtime/src/pi-file-ops.test.ts b/packages/agent-runtime/src/pi-file-ops.test.ts
index 4d7dd3233..43adef657 100644
--- a/packages/agent-runtime/src/pi-file-ops.test.ts
+++ b/packages/agent-runtime/src/pi-file-ops.test.ts
@@ -1,4 +1,6 @@
-import { prepareCompaction, type AgentMessage, type Entry } from "@earendil-works/pi-agent-core";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { prepareCompaction } from "./pi-runtime-compaction-plan.js";
+import type { Entry } from "./pi-runtime-types.js";
import { describe, expect, it } from "vitest";
import { withPiFileOpToolNames } from "./pi-file-ops.js";
diff --git a/packages/agent-runtime/src/pi-file-ops.ts b/packages/agent-runtime/src/pi-file-ops.ts
index 482dadef6..22b11558e 100644
--- a/packages/agent-runtime/src/pi-file-ops.ts
+++ b/packages/agent-runtime/src/pi-file-ops.ts
@@ -1,4 +1,4 @@
-import type { Entry } from "@earendil-works/pi-agent-core";
+import type { Entry } from "./pi-runtime-types.js";
import { isRecord } from "./agent-messages.js";
@@ -6,12 +6,9 @@ import { isRecord } from "./agent-messages.js";
* The tool names pi's own compaction inspects, mapped from ours to pi's
* spelling.
*
- * `extractFileOpsFromMessage` in `@earendil-works/pi-coding-agent` switches on
- * the lowercase names `read` / `write` / `edit`, because those are the names
- * pi's own tools carry. PI-Desktop registers `Read` / `Write` / `Edit`, so that
- * collector matched nothing: a checkpoint's `readFiles` / `modifiedFiles` and
- * the `<read-files>` section of a summary were always empty (issue #827 turned
- * this up while reading a compaction report).
+ * The compaction planner switches on lowercase names `read` / `write` / `edit`.
+ * PI-Desktop registers `Read` / `Write` / `Edit`, so the conversion keeps
+ * checkpoint file lists and summary tags populated.
*
* Only these three are converted, and only on the way into pi's preparation.
* There is nothing to convert for `grep`, `glob` or `bash`: pi's collector does
diff --git a/packages/agent-runtime/src/pi-runtime-compaction-plan.ts b/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
new file mode 100644
index 000000000..0e80fc118
--- /dev/null
+++ b/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
@@ -0,0 +1,237 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { estimateContextTokens, estimateTokens } from "./pi-runtime-estimates.js";
+import {
+ createBranchSummaryMessage,
+ createCompactionSummaryMessage,
+} from "./pi-runtime-messages.js";
+import {
+ buildContextEntries,
+ sessionEntryToContextMessages,
+} from "./session-context.js";
+import type {
+ CompactionPreparation,
+ CompactionSettings,
+ Entry,
+ FileOperations,
+ Result,
+} from "./pi-runtime-types.js";
+import { CompactionError } from "./pi-runtime-types.js";
+
+export type CutPoint = {
+ firstKeptEntryIndex: number;
+ turnStartIndex: number;
+ isSplitTurn: boolean;
+};
+
+function messageFromEntry(entry: Entry): AgentMessage | undefined {
+ switch (entry.type) {
+ case "message":
+ return entry.message;
+ case "branch_summary":
+ return createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp) as AgentMessage;
+ case "compaction":
+ return createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp) as AgentMessage;
+ case "custom":
+ return undefined;
+ }
+}
+
+function messageForSummary(entry: Entry): AgentMessage | undefined {
+ return entry.type === "compaction" ? undefined : messageFromEntry(entry);
+}
+
+function findValidCutPoints(entries: Entry[], startIndex: number, endIndex: number): number[] {
+ const cutPoints: number[] = [];
+ for (let index = startIndex; index < endIndex; index++) {
+ const entry = entries[index];
+ if (!entry) continue;
+ if (entry.type === "branch_summary") {
+ cutPoints.push(index);
+ continue;
+ }
+ if (entry.type !== "message") continue;
+ switch (entry.message.role) {
+ case "bashExecution":
+ case "custom":
+ case "branchSummary":
+ case "compactionSummary":
+ case "user":
+ case "assistant":
+ cutPoints.push(index);
+ break;
+ }
+ }
+ return cutPoints;
+}
+
+export function findTurnStartIndex(entries: Entry[], entryIndex: number, startIndex: number): number {
+ for (let index = entryIndex; index >= startIndex; index--) {
+ const entry = entries[index];
+ if (entry?.type === "branch_summary") return index;
+ if (entry?.type !== "message") continue;
+ if (entry.message.role === "user" || entry.message.role === "bashExecution") return index;
+ }
+ return -1;
+}
+
+export function findCutPoint(
+ entries: Entry[],
+ startIndex: number,
+ endIndex: number,
+ keepRecentTokens: number,
+): CutPoint {
+ const cutPoints = findValidCutPoints(entries, startIndex, endIndex);
+ if (cutPoints.length === 0) {
+ return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };
+ }
+ let accumulatedTokens = 0;
+ let cutIndex = cutPoints[0]!;
+ for (let index = endIndex - 1; index >= startIndex; index--) {
+ const entry = entries[index];
+ if (entry?.type !== "message") continue;
+ accumulatedTokens += estimateTokens(entry.message);
+ if (accumulatedTokens < keepRecentTokens) continue;
+ cutIndex = cutPoints.find((point) => point >= index) ?? cutIndex;
+ break;
+ }
+ while (cutIndex > startIndex) {
+ const previous = entries[cutIndex - 1];
+ if (previous?.type === "compaction" || previous?.type === "message") break;
+ cutIndex--;
+ }
+ const cutEntry = entries[cutIndex];
+ const startsAtUser = cutEntry?.type === "message" && cutEntry.message.role === "user";
+ const turnStartIndex = startsAtUser ? -1 : findTurnStartIndex(entries, cutIndex, startIndex);
+ return {
+ firstKeptEntryIndex: cutIndex,
+ turnStartIndex,
+ isSplitTurn: !startsAtUser && turnStartIndex !== -1,
+ };
+}
+
+function createFileOperations(): FileOperations {
+ return { read: new Set(), written: new Set(), edited: new Set() };
+}
+
+function collectMessageFileOperations(message: AgentMessage, fileOps: FileOperations): void {
+ if (message.role !== "assistant" || !Array.isArray(message.content)) return;
+ for (const block of message.content) {
+ if (!block || block.type !== "toolCall") continue;
+ const args = block.arguments;
+ const path = args && typeof args.path === "string" ? args.path : undefined;
+ if (!path) continue;
+ switch (block.name) {
+ case "read": fileOps.read.add(path); break;
+ case "write": fileOps.written.add(path); break;
+ case "edit": fileOps.edited.add(path); break;
+ }
+ }
+}
+
+function collectFileOperations(
+ messages: AgentMessage[],
+ entries: Entry[],
+ previousCompactionIndex: number,
+): FileOperations {
+ const fileOps = createFileOperations();
+ if (previousCompactionIndex >= 0) {
+ const previous = entries[previousCompactionIndex];
+ const details = previous?.type === "compaction" ? previous.details : undefined;
+ if (details && typeof details === "object" && !Array.isArray(details)) {
+ const record = details as Record<string, unknown>;
+ if (Array.isArray(record.readFiles)) {
+ for (const path of record.readFiles) if (typeof path === "string") fileOps.read.add(path);
+ }
+ if (Array.isArray(record.modifiedFiles)) {
+ for (const path of record.modifiedFiles) if (typeof path === "string") fileOps.edited.add(path);
+ }
+ }
+ }
+ for (const message of messages) collectMessageFileOperations(message, fileOps);
+ return fileOps;
+}
+
+/** Build the desktop-owned preparation used by host-core checkpoint compaction. */
+export function prepareCompaction(
+ pathEntries: Entry[],
+ settings: CompactionSettings,
+): Result<CompactionPreparation | undefined> {
+ try {
+ if (pathEntries.length === 0 || pathEntries.at(-1)?.type === "compaction") {
+ return { ok: true, value: undefined };
+ }
+ let previousCompactionIndex = -1;
+ for (let index = pathEntries.length - 1; index >= 0; index--) {
+ if (pathEntries[index]?.type === "compaction") {
+ previousCompactionIndex = index;
+ break;
+ }
+ }
+
+ const previousCompaction = previousCompactionIndex >= 0
+ ? pathEntries[previousCompactionIndex]
+ : undefined;
+ const previousSummary = previousCompaction?.type === "compaction"
+ ? previousCompaction.summary
+ : undefined;
+ const virtualRetainedEntries: Entry[] = previousCompaction?.type === "compaction"
+ ? previousCompaction.retainedTail.map((message, index) => ({
+ type: "message",
+ id: `${previousCompaction.id}:retained:${index}`,
+ parentId: index === 0
+ ? previousCompaction.id
+ : `${previousCompaction.id}:retained:${index - 1}`,
+ seq: previousCompaction.seq,
+ timestamp: message.timestamp,
+ message,
+ }))
+ : [];
+ const compactableEntries = previousCompactionIndex >= 0
+ ? [...virtualRetainedEntries, ...pathEntries.slice(previousCompactionIndex + 1)]
+ : pathEntries;
+ const cutPoint = findCutPoint(compactableEntries, 0, compactableEntries.length, settings.keepRecentTokens);
+ const historyEnd = cutPoint.isSplitTurn
+ ? cutPoint.turnStartIndex
+ : cutPoint.firstKeptEntryIndex;
+ const messagesToSummarize: AgentMessage[] = [];
+ for (let index = 0; index < historyEnd; index++) {
+ const message = messageForSummary(compactableEntries[index]!);
+ if (message) messagesToSummarize.push(message);
+ }
+ const turnPrefixMessages: AgentMessage[] = [];
+ if (cutPoint.isSplitTurn) {
+ for (let index = cutPoint.turnStartIndex; index < cutPoint.firstKeptEntryIndex; index++) {
+ const message = messageForSummary(compactableEntries[index]!);
+ if (message) turnPrefixMessages.push(message);
+ }
+ }
+ const retainedTail: AgentMessage[] = [];
+ for (let index = cutPoint.firstKeptEntryIndex; index < compactableEntries.length; index++) {
+ const message = messageForSummary(compactableEntries[index]!);
+ if (message) retainedTail.push(message);
+ }
+ const fileOps = collectFileOperations(messagesToSummarize, pathEntries, previousCompactionIndex);
+ if (cutPoint.isSplitTurn) {
+ for (const message of turnPrefixMessages) collectMessageFileOperations(message, fileOps);
+ }
+ const contextMessages = buildContextEntries(pathEntries).flatMap((entry) =>
+ sessionEntryToContextMessages(entry),
+ );
+ return {
+ ok: true,
+ value: {
+ messagesToSummarize,
+ turnPrefixMessages,
+ retainedTail,
+ isSplitTurn: cutPoint.isSplitTurn,
+ tokensBefore: estimateContextTokens(contextMessages).tokens,
+ ...(previousSummary !== undefined ? { previousSummary } : {}),
+ fileOps,
+ settings,
+ },
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return { ok: false, error: new CompactionError("summarization_failed", message) };
+ }
+}
diff --git a/packages/agent-runtime/src/pi-runtime-compaction-summary.ts b/packages/agent-runtime/src/pi-runtime-compaction-summary.ts
new file mode 100644
index 000000000..8d11f0e94
--- /dev/null
+++ b/packages/agent-runtime/src/pi-runtime-compaction-summary.ts
@@ -0,0 +1,337 @@
+import { randomUUID } from "node:crypto";
+import { retryAssistantCall } from "@earendil-works/pi-ai";
+import type {
+ Api,
+ AssistantMessage,
+ Context,
+ Model,
+ Models,
+ RetryCallbacks,
+ RetryPolicy,
+ SimpleStreamOptions,
+ Usage,
+} from "@earendil-works/pi-ai";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { addSummaryUsage } from "./compaction-summary-input.js";
+import { convertToLlm, serializeConversation, textFromContent } from "./pi-runtime-messages.js";
+import type {
+ CompactResult,
+ CompactionPreparation,
+ Result,
+ RuntimeThinkingLevel,
+} from "./pi-runtime-types.js";
+import { CompactionError } from "./pi-runtime-types.js";
+
+const SUMMARY_SYSTEM_PROMPT = `You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
+
+Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`;
+
+const NEW_SUMMARY_PROMPT = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
+
+Use this EXACT format:
+
+## Goal
+[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
+
+## Constraints & Preferences
+- [Any constraints, preferences, or requirements mentioned by user]
+- [Or "(none)" if none were mentioned]
+
+## Progress
+### Done
+- [x] [Completed tasks/changes]
+
+### In Progress
+- [ ] [Current work]
+
+### Blocked
+- [Issues preventing progress, if any]
+
+## Key Decisions
+- **[Decision]**: [Brief rationale]
+
+## Next Steps
+1. [Ordered list of next steps]
+
+## Critical Context
+- [Any data, examples, or references needed to continue]
+- [Or "(none)" if not applicable]
+
+Keep each section concise. Preserve exact file paths, function names, and error messages.`;
+
+const UPDATE_SUMMARY_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
+
+Update the existing structured summary with new information. RULES:
+- PRESERVE all existing information from the previous summary
+- ADD new progress, decisions, and context from the new messages
+- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
+- UPDATE "Next Steps" based on what was accomplished
+- PRESERVE exact file paths, function names, and error messages
+- If something is no longer relevant, you may remove it
+
+Use this EXACT format:
+
+## Goal
+[Preserve existing goals, add new ones if the task expanded]
+
+## Constraints & Preferences
+- [Preserve existing, add new ones discovered]
+
+## Progress
+### Done
+- [x] [Include previously done items AND newly completed items]
+
+### In Progress
+- [ ] [Current work - update based on progress]
+
+### Blocked
+- [Current blockers - remove if resolved]
+
+## Key Decisions
+- **[Decision]**: [Brief rationale] (preserve all previous, add new)
+
+## Next Steps
+1. [Update based on current state]
+
+## Critical Context
+- [Preserve important context, add new if needed]
+
+Keep each section concise. Preserve exact file paths, function names, and error messages.`;
+
+const TURN_PREFIX_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
+
+Summarize the prefix to provide context for the retained suffix:
+
+## Original Request
+[What did the user ask for in this turn?]
+
+## Early Progress
+- [Key decisions and work done in the prefix]
+
+## Context for Suffix
+- [Information needed to understand the retained recent work]
+
+Be concise. Focus on what's needed to understand the kept suffix.`;
+
+const MAX_SUMMARY_TOKENS = 0.8;
+
+async function requestSummary(
+ messages: AgentMessage[],
+ model: Model<Api>,
+ reserveTokens: number,
+ options: {
+ previousSummary?: string;
+ customInstructions?: string;
+ errorLabel?: string;
+ thinkingLevel?: RuntimeThinkingLevel;
+ signal?: AbortSignal;
+ retry?: RetryPolicy;
+ callbacks?: RetryCallbacks;
+ prompt?: string;
+ outputRatio?: number;
+ },
+ models: Models,
+): Promise<Result<{ text: string; usage: Usage }>> {
+ const maxTokens = Math.min(
+ Math.floor((options.outputRatio ?? MAX_SUMMARY_TOKENS) * reserveTokens),
+ model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY,
+ );
+ const basePrompt = options.prompt ?? (options.previousSummary
+ ? UPDATE_SUMMARY_PROMPT
+ : NEW_SUMMARY_PROMPT);
+ const summaryPrompt = options.customInstructions
+ ? `${basePrompt}\n\nAdditional focus: ${options.customInstructions}`
+ : basePrompt;
+ const conversation = serializeConversation(convertToLlm(messages));
+ let promptText = `<conversation>\n${conversation}\n</conversation>\n\n`;
+ if (options.previousSummary) {
+ promptText += `<previous-summary>\n${options.previousSummary}\n</previous-summary>\n\n`;
+ }
+ promptText += summaryPrompt;
+ const context: Context = {
+ systemPrompt: SUMMARY_SYSTEM_PROMPT,
+ messages: [{
+ role: "user",
+ content: [{ type: "text", text: promptText }],
+ timestamp: Date.now(),
+ }],
+ };
+ const requestOptions: SimpleStreamOptions = {
+ maxTokens,
+ ...(model.reasoning && options.thinkingLevel && options.thinkingLevel !== "off"
+ ? { reasoning: options.thinkingLevel }
+ : {}),
+ ...(options.signal ? { signal: options.signal } : {}),
+ cacheRetention: "none",
+ sessionId: randomUUID(),
+ };
+ let response: AssistantMessage;
+ const errorLabel = options.errorLabel ?? "Summarization";
+ try {
+ response = await retryAssistantCall(
+ () => models.completeSimple(model, context, requestOptions),
+ options.retry,
+ options.signal,
+ options.callbacks,
+ );
+ } catch (error) {
+ if (options.signal?.aborted) {
+ return {
+ ok: false,
+ error: new CompactionError(
+ "aborted",
+ error instanceof Error ? error.message : `${errorLabel} aborted`,
+ ),
+ };
+ }
+ return {
+ ok: false,
+ error: new CompactionError(
+ "summarization_failed",
+ error instanceof Error ? error.message : `${errorLabel} failed`,
+ ),
+ };
+ }
+ if (response.stopReason === "aborted") {
+ return {
+ ok: false,
+ error: new CompactionError("aborted", response.errorMessage || `${errorLabel} aborted`),
+ };
+ }
+ if (response.stopReason === "error") {
+ return {
+ ok: false,
+ error: new CompactionError(
+ "summarization_failed",
+ `${errorLabel} failed: ${response.errorMessage || "Unknown error"}`,
+ ),
+ };
+ }
+ return { ok: true, value: { text: textFromContent(response.content), usage: response.usage } };
+}
+
+export async function generateSummaryWithUsage(
+ currentMessages: AgentMessage[],
+ models: Models,
+ model: Model<Api>,
+ reserveTokens: number,
+ customInstructions: string | undefined,
+ previousSummary: string | undefined,
+ thinkingLevel: RuntimeThinkingLevel | undefined,
+ retry: RetryPolicy | undefined,
+ callbacks: RetryCallbacks | undefined,
+ signal: AbortSignal | undefined,
+): Promise<Result<{ text: string; usage: Usage }>> {
+ return requestSummary(currentMessages, model, reserveTokens, {
+ ...(customInstructions ? { customInstructions } : {}),
+ ...(previousSummary ? { previousSummary } : {}),
+ ...(thinkingLevel ? { thinkingLevel } : {}),
+ ...(retry ? { retry } : {}),
+ ...(callbacks ? { callbacks } : {}),
+ ...(signal ? { signal } : {}),
+ }, models);
+}
+
+function compactFileOperations(fileOps: CompactionPreparation["fileOps"]): {
+ readFiles: string[];
+ modifiedFiles: string[];
+} {
+ const modified = new Set([...fileOps.edited, ...fileOps.written]);
+ return {
+ readFiles: [...fileOps.read].filter((path) => !modified.has(path)).sort(),
+ modifiedFiles: [...modified].sort(),
+ };
+}
+
+function formatFileOperations(readFiles: string[], modifiedFiles: string[]): string {
+ const sections = [
+ ...(readFiles.length ? [`<read-files>\n${readFiles.join("\n")}\n</read-files>`] : []),
+ ...(modifiedFiles.length ? [`<modified-files>\n${modifiedFiles.join("\n")}\n</modified-files>`] : []),
+ ];
+ return sections.length ? `\n\n${sections.join("\n\n")}` : "";
+}
+
+export async function compact(
+ preparation: CompactionPreparation,
+ models: Models,
+ model: Model<Api>,
+ customInstructions: string | undefined,
+ thinkingLevel: RuntimeThinkingLevel | undefined,
+ retry: RetryPolicy | undefined,
+ callbacks: RetryCallbacks | undefined,
+ signal: AbortSignal | undefined,
+): Promise<Result<CompactResult>> {
+ let summary: string;
+ let usage: Usage | undefined;
+ if (preparation.isSplitTurn && preparation.turnPrefixMessages.length > 0) {
+ let history = "No prior history.";
+ let historyUsage: Usage | undefined;
+ if (preparation.messagesToSummarize.length > 0) {
+ const result = await requestSummary(
+ preparation.messagesToSummarize,
+ model,
+ preparation.settings.reserveTokens,
+ {
+ ...(preparation.previousSummary ? { previousSummary: preparation.previousSummary } : {}),
+ ...(customInstructions ? { customInstructions } : {}),
+ ...(thinkingLevel ? { thinkingLevel } : {}),
+ ...(retry ? { retry } : {}),
+ ...(callbacks ? { callbacks } : {}),
+ ...(signal ? { signal } : {}),
+ },
+ models,
+ );
+ if (!result.ok) return result;
+ history = result.value.text;
+ historyUsage = result.value.usage;
+ }
+ const prefix = await requestSummary(
+ preparation.turnPrefixMessages,
+ model,
+ preparation.settings.reserveTokens,
+ {
+ prompt: TURN_PREFIX_PROMPT,
+ errorLabel: "Turn prefix summarization",
+ outputRatio: 0.5,
+ ...(thinkingLevel ? { thinkingLevel } : {}),
+ ...(retry ? { retry } : {}),
+ ...(callbacks ? { callbacks } : {}),
+ ...(signal ? { signal } : {}),
+ },
+ models,
+ );
+ if (!prefix.ok) return prefix;
+ summary = `${history}\n\n---\n\n**Turn Context (split turn):**\n\n${prefix.value.text}`;
+ usage = addSummaryUsage(historyUsage, prefix.value.usage);
+ } else {
+ const result = await requestSummary(
+ preparation.messagesToSummarize,
+ model,
+ preparation.settings.reserveTokens,
+ {
+ ...(preparation.previousSummary ? { previousSummary: preparation.previousSummary } : {}),
+ ...(customInstructions ? { customInstructions } : {}),
+ ...(thinkingLevel ? { thinkingLevel } : {}),
+ ...(retry ? { retry } : {}),
+ ...(callbacks ? { callbacks } : {}),
+ ...(signal ? { signal } : {}),
+ },
+ models,
+ );
+ if (!result.ok) return result;
+ summary = result.value.text;
+ usage = result.value.usage;
+ }
+ const { readFiles, modifiedFiles } = compactFileOperations(preparation.fileOps);
+ summary += formatFileOperations(readFiles, modifiedFiles);
+ return {
+ ok: true,
+ value: {
+ summary,
+ tokensBefore: preparation.tokensBefore,
+ ...(usage ? { usage } : {}),
+ retainedTail: preparation.retainedTail,
+ details: { readFiles, modifiedFiles },
+ },
+ };
+}
diff --git a/packages/agent-runtime/src/pi-runtime-estimates.ts b/packages/agent-runtime/src/pi-runtime-estimates.ts
new file mode 100644
index 000000000..f43cd897d
--- /dev/null
+++ b/packages/agent-runtime/src/pi-runtime-estimates.ts
@@ -0,0 +1,96 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import {
+ calculateContextTokens,
+ estimateMessageTokens as estimateProviderMessageTokens,
+ getLastAssistantUsageInfo,
+} from "@earendil-works/pi-ai/utils/estimate";
+import { LocalRequestError } from "@earendil-works/pi-ai";
+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";
+import type { Api, Message, Model } from "@earendil-works/pi-ai";
+
+export type ContextUsageEstimate = {
+ tokens: number;
+ usageTokens: number;
+ trailingTokens: number;
+ lastUsageIndex: number | null;
+};
+
+function textAndImageChars(content: unknown): number {
+ if (typeof content === "string") return content.length;
+ if (!Array.isArray(content)) return 0;
+ let chars = 0;
+ for (const block of content) {
+ if (!block || typeof block !== "object") continue;
+ if (Reflect.get(block, "type") === "text") {
+ const text = Reflect.get(block, "text");
+ if (typeof text === "string") chars += text.length;
+ } else if (Reflect.get(block, "type") === "image") {
+ chars += 4_800;
+ }
+ }
+ return chars;
+}
+
+/** Provider messages use pi-ai's estimator; desktop-only rows keep their legacy heuristic. */
+export function estimateTokens(
+ message: AgentMessage,
+ model?: Model<Api>,
+): number {
+ switch (message.role) {
+ case "system":
+ case "user":
+ case "assistant":
+ case "toolResult":
+ return estimateProviderMessageTokens(message as unknown as Message, model);
+ case "custom":
+ return Math.ceil(textAndImageChars((message as { content?: unknown }).content) / 4);
+ case "bashExecution": {
+ const value = message as { command: string; output: string };
+ return Math.ceil((value.command.length + value.output.length) / 4);
+ }
+ case "branchSummary":
+ case "compactionSummary": {
+ const summary = (message as { summary?: unknown }).summary;
+ return typeof summary === "string" ? Math.ceil(summary.length / 4) : 0;
+ }
+ default:
+ throw new LocalRequestError("context-validation");
+ }
+}
+
+/** Preserve the provider-usage anchor, estimating only messages after it. */
+export function estimateContextTokens(
+ messages: AgentMessage[],
+ model?: Model<Api>,
+): ContextUsageEstimate {
+ const providerMessages: Message[] = [];
+ const providerMessageIndices: number[] = [];
+ messages.forEach((message, index) => {
+ if (
+ message.role !== "system" &&
+ message.role !== "user" &&
+ message.role !== "assistant" &&
+ message.role !== "toolResult"
+ ) return;
+ providerMessages.push(message as Message);
+ providerMessageIndices.push(index);
+ });
+ validateHostedSearchMessages(providerMessages);
+ const usageInfo = getLastAssistantUsageInfo(providerMessages);
+ if (!usageInfo) {
+ const tokens = messages.reduce((sum, message) => sum + estimateTokens(message, model), 0);
+ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
+ }
+ const lastUsageIndex = providerMessageIndices[usageInfo.index]!;
+ const usageTokens = calculateContextTokens(usageInfo.usage);
+ let trailingTokens = 0;
+ for (let index = lastUsageIndex + 1; index < messages.length; index++) {
+ trailingTokens += estimateTokens(messages[index]!, model);
+ }
+ return {
+ tokens: usageTokens + trailingTokens,
+ usageTokens,
+ trailingTokens,
+ lastUsageIndex,
+ };
+}
diff --git a/packages/agent-runtime/src/pi-runtime-messages.ts b/packages/agent-runtime/src/pi-runtime-messages.ts
new file mode 100644
index 000000000..a595da960
--- /dev/null
+++ b/packages/agent-runtime/src/pi-runtime-messages.ts
@@ -0,0 +1,221 @@
+import type { Message } from "@earendil-works/pi-ai";
+import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+
+export type CompactionSummaryMessage = {
+ role: "compactionSummary";
+ summary: string;
+ tokensBefore: number;
+ timestamp: number;
+};
+
+export type BranchSummaryMessage = {
+ role: "branchSummary";
+ summary: string;
+ fromId: string | null;
+ timestamp: number;
+};
+
+type BashExecutionMessage = {
+ role: "bashExecution";
+ command: string;
+ output: string;
+ exitCode?: number;
+ cancelled: boolean;
+ truncated: boolean;
+ fullOutputPath?: string;
+ timestamp: number;
+ excludeFromContext?: boolean;
+};
+
+type CustomMessage = {
+ role: "custom";
+ content: string | Message["content"];
+ timestamp: number;
+};
+
+type RuntimeMessage =
+ | AgentMessage
+ | CompactionSummaryMessage
+ | BranchSummaryMessage
+ | BashExecutionMessage
+ | CustomMessage;
+
+export const COMPACTION_SUMMARY_PREFIX =
+ "The conversation history before this point was compacted into the following summary:\n\n<summary>\n";
+export const COMPACTION_SUMMARY_SUFFIX = "\n</summary>";
+export const BRANCH_SUMMARY_PREFIX =
+ "The following is a summary of a branch that this conversation came back from:\n\n<summary>\n";
+export const BRANCH_SUMMARY_SUFFIX = "</summary>";
+
+function normalizeTimestamp(timestamp: string | number): number {
+ return typeof timestamp === "number" ? timestamp : new Date(timestamp).getTime();
+}
+
+export function createCompactionSummaryMessage(
+ summary: string,
+ tokensBefore: number,
+ timestamp: string | number,
+): CompactionSummaryMessage {
+ return {
+ role: "compactionSummary",
+ summary,
+ tokensBefore,
+ timestamp: normalizeTimestamp(timestamp),
+ };
+}
+
+export function createBranchSummaryMessage(
+ summary: string,
+ fromId: string | null,
+ timestamp: string | number,
+): BranchSummaryMessage {
+ return {
+ role: "branchSummary",
+ summary,
+ fromId,
+ timestamp: normalizeTimestamp(timestamp),
+ };
+}
+
+function bashExecutionToText(message: BashExecutionMessage): string {
+ let text = `Ran \`${message.command}\`\n`;
+ if (message.output) text += `\`\`\`\n${message.output}\n\`\`\``;
+ else text += "(no output)";
+ if (message.cancelled) text += "\n\n(command cancelled)";
+ else if (message.exitCode !== undefined && message.exitCode !== 0) {
+ text += `\n\nCommand exited with code ${message.exitCode}`;
+ }
+ if (message.truncated && message.fullOutputPath) {
+ text += `\n\n[Output truncated. Full output: ${message.fullOutputPath}]`;
+ }
+ return text;
+}
+
+/** Convert desktop-only transcript rows into provider messages. */
+export function convertToLlm(messages: AgentMessage[]): Message[] {
+ const converted: Message[] = [];
+ for (const message of messages) {
+ const runtimeMessage = message as RuntimeMessage;
+ switch (runtimeMessage.role) {
+ case "bashExecution":
+ if (runtimeMessage.excludeFromContext) continue;
+ converted.push(asProviderMessage({
+ role: "user",
+ content: [{ type: "text", text: bashExecutionToText(runtimeMessage) }],
+ timestamp: runtimeMessage.timestamp,
+ }));
+ break;
+ case "custom":
+ converted.push(asProviderMessage({
+ role: "user",
+ content: typeof runtimeMessage.content === "string"
+ ? [{ type: "text", text: runtimeMessage.content }]
+ : runtimeMessage.content,
+ timestamp: runtimeMessage.timestamp,
+ }));
+ break;
+ case "branchSummary":
+ converted.push(asProviderMessage({
+ role: "user",
+ content: [{
+ type: "text",
+ text: `${BRANCH_SUMMARY_PREFIX}${runtimeMessage.summary}${BRANCH_SUMMARY_SUFFIX}`,
+ }],
+ timestamp: runtimeMessage.timestamp,
+ }));
+ break;
+ case "compactionSummary":
+ converted.push(asProviderMessage({
+ role: "user",
+ content: [{
+ type: "text",
+ text: `${COMPACTION_SUMMARY_PREFIX}${runtimeMessage.summary}${COMPACTION_SUMMARY_SUFFIX}`,
+ }],
+ timestamp: runtimeMessage.timestamp,
+ }));
+ break;
+ case "system":
+ case "user":
+ case "assistant":
+ case "toolResult":
+ converted.push(asProviderMessage(runtimeMessage));
+ break;
+ default:
+ break;
+ }
+ }
+ return converted;
+}
+
+function asProviderMessage(message: unknown): Message {
+ // pi-agent-core and pi-ai may resolve separate copies of the same runtime
+ // message declarations; hosted-search blocks also extend pi-ai's content union.
+ return message as Message;
+}
+
+/** Match pi-ai's `contentText` projection while accepting hosted-search blocks. */
+export function textFromContent(content: unknown, separator = "\n"): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content.flatMap((block: unknown) => {
+ if (!block || typeof block !== "object") return [];
+ if (Reflect.get(block, "type") !== "text") return [];
+ const text = Reflect.get(block, "text");
+ return typeof text === "string" ? [text] : [];
+ }).join(separator);
+}
+
+function safeJsonStringify(value: unknown): string {
+ try {
+ return JSON.stringify(value) ?? "undefined";
+ } catch {
+ return "[unserializable]";
+ }
+}
+
+function truncateForSummary(text: string, maxChars: number): string {
+ if (text.length <= maxChars) return text;
+ return `${text.slice(0, maxChars)}\n\n[... ${text.length - maxChars} more characters truncated]`;
+}
+
+/** Stable plain-text representation used for summary request sizing and input. */
+export function serializeConversation(messages: Message[]): string {
+ const parts: string[] = [];
+ for (const message of messages) {
+ if (message.role === "user") {
+ const content = textFromContent(message.content, "");
+ if (content) parts.push(`[User]: ${content}`);
+ continue;
+ }
+ if (message.role === "assistant") {
+ const thinking: string[] = [];
+ const toolCalls: string[] = [];
+ const hostedSearch: string[] = [];
+ for (const block of message.content) {
+ if (block.type === "thinking") thinking.push(block.thinking);
+ else if (block.type === "toolCall") {
+ const args = Object.entries(block.arguments)
+ .map(([key, value]) => `${key}=${safeJsonStringify(value)}`)
+ .join(", ");
+ toolCalls.push(`${block.name}(${args})`);
+ } else if (block.type === "hostedSearch") {
+ const projection = hostedSearchReplayProjection(block);
+ if (projection !== undefined) hostedSearch.push(safeJsonStringify(projection));
+ }
+ }
+ if (thinking.length) parts.push(`[Assistant thinking]: ${thinking.join("\n")}`);
+ if (message.content.some((block) => block.type === "text")) {
+ parts.push(`[Assistant]: ${textFromContent(message.content)}`);
+ }
+ if (toolCalls.length) parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);
+ if (hostedSearch.length) parts.push(`[Assistant hosted search]: ${hostedSearch.join("\n")}`);
+ continue;
+ }
+ if (message.role === "toolResult") {
+ const content = textFromContent(message.content, "");
+ if (content) parts.push(`[Tool result]: ${truncateForSummary(content, 2_000)}`);
+ }
+ }
+ return parts.join("\n\n");
+}
diff --git a/packages/agent-runtime/src/pi-runtime-types.ts b/packages/agent-runtime/src/pi-runtime-types.ts
new file mode 100644
index 000000000..a6b518622
--- /dev/null
+++ b/packages/agent-runtime/src/pi-runtime-types.ts
@@ -0,0 +1,99 @@
+import type {
+ AgentMessage,
+ ThinkingLevel,
+} from "@earendil-works/pi-agent-core";
+import type { Usage } from "@earendil-works/pi-ai";
+
+/** Desktop-owned transcript projection used by the agent runtime. */
+export type Entry =
+ | MessageEntry
+ | CompactionEntry
+ | BranchSummaryEntry
+ | CustomEntry;
+
+export type EntryBase = {
+ id: string;
+ parentId: string | null;
+ seq: number;
+ timestamp: number;
+ type: "message" | "compaction" | "branch_summary" | "custom";
+};
+
+export type MessageEntry = EntryBase & {
+ type: "message";
+ message: AgentMessage;
+};
+
+export type CompactionEntry = EntryBase & {
+ type: "compaction";
+ summary: string;
+ retainedTail: AgentMessage[];
+ tokensBefore: number;
+ details?: unknown;
+ usage?: Usage;
+ fromHook?: boolean;
+};
+
+export type BranchSummaryEntry = EntryBase & {
+ type: "branch_summary";
+ fromId: string | null;
+ summary: string;
+ details?: unknown;
+ usage?: Usage;
+ fromHook?: boolean;
+};
+
+export type CustomEntry = EntryBase & {
+ type: "custom";
+ customType: string;
+ data?: unknown;
+};
+
+export type CompactionSettings = {
+ enabled: boolean;
+ reserveTokens: number;
+ keepRecentTokens: number;
+};
+
+export type FileOperations = {
+ read: Set<string>;
+ written: Set<string>;
+ edited: Set<string>;
+};
+
+export type CompactionPreparation = {
+ messagesToSummarize: AgentMessage[];
+ turnPrefixMessages: AgentMessage[];
+ retainedTail: AgentMessage[];
+ isSplitTurn: boolean;
+ tokensBefore: number;
+ previousSummary?: string;
+ fileOps: FileOperations;
+ settings: CompactionSettings;
+};
+
+export type CompactResult = {
+ summary: string;
+ tokensBefore: number;
+ usage?: Usage;
+ retainedTail: AgentMessage[];
+ details?: unknown;
+};
+
+export type CompactionErrorCode = "aborted" | "summarization_failed";
+
+export class CompactionError extends Error {
+ constructor(
+ readonly code: CompactionErrorCode,
+ message: string,
+ ) {
+ super(message);
+ this.name = "CompactionError";
+ }
+}
+
+export type Result<T> =
+ | { ok: true; value: T }
+ | { ok: false; error: CompactionError };
+
+export type RuntimeThinkingLevel = ThinkingLevel;
diff --git a/packages/agent-runtime/src/prompt-templates.test.ts b/packages/agent-runtime/src/prompt-templates.test.ts
index db6277026..fd36a9dff 100644
--- a/packages/agent-runtime/src/prompt-templates.test.ts
+++ b/packages/agent-runtime/src/prompt-templates.test.ts
@@ -35,6 +35,17 @@ describe("expandSlashInvocation", () => {
);
});
+ it("preserves pi's default placeholders without recursively expanding arguments", () => {
+ const template = {
+ name: "defaults",
+ content: "${1:-fallback} ${@:-no args} $2 $1",
+ };
+ expect(expandSlashInvocation('/defaults "$2" "$1"', [template])?.expanded)
+ .toBe("$2 $2 $1 $1 $2");
+ expect(expandSlashInvocation("/defaults", [template])?.expanded)
+ .toBe("fallback no args ");
+ });
+
it("drops missing positional args to empty strings", () => {
expect(expandSlashInvocation("/review one", templates)?.expanded).toBe(
"Review one with focus on .",
diff --git a/packages/agent-runtime/src/prompt-templates.ts b/packages/agent-runtime/src/prompt-templates.ts
index 1b4536e9a..09726ec3b 100644
--- a/packages/agent-runtime/src/prompt-templates.ts
+++ b/packages/agent-runtime/src/prompt-templates.ts
@@ -1,23 +1,17 @@
/**
- * Bridge to pi's prompt-template ("slash command") system for the composer
- * (D123, ADR 0024). Loading and expansion reuse pi-agent-core verbatim so
- * `.pi/prompts` assets behave identically in pi CLI and PI-Desktop.
+ * Desktop-owned prompt-template loading and expansion for the composer slash
+ * menu (D123, ADR 0024). Keeping this adapter local avoids depending on the
+ * removed pi-agent-core harness exports while preserving pi's file and argument
+ * conventions.
*
* Discovery: `<workspace>/.pi/prompts/*.md` (project) and
* `~/.pi/agent/prompts/*.md` (user-global); project wins name conflicts.
*/
-import { readFile } from "node:fs/promises";
+import { lstat, readFile, readdir, realpath } from "node:fs/promises";
import { homedir } from "node:os";
-import { join } from "node:path";
-import {
- BACKGROUND_CONTEXT,
- loadSourcedPromptTemplates,
- parseCommandArgs,
- substituteArgs,
- type PromptTemplate,
-} from "@earendil-works/pi-agent-core";
-import { NodeExecutionEnv } from "@earendil-works/pi-agent-core/node";
+import { join, resolve } from "node:path";
+import { parse } from "yaml";
/**
* Prompt-enhancement templates live in `@pi-desktop/shared` so the runtime,
@@ -26,6 +20,12 @@ import { NodeExecutionEnv } from "@earendil-works/pi-agent-core/node";
*/
export type ComposerTemplateSource = "project" | "user";
+export type PromptTemplate = {
+ name: string;
+ description?: string;
+ content: string;
+};
+
export type ComposerTemplate = PromptTemplate & {
source: ComposerTemplateSource;
/** Frontmatter `argument-hint`, e.g. "<file> [focus]". */
@@ -37,6 +37,30 @@ export type ComposerTemplateDirs = {
user: string;
};
+type TemplateDiagnosticCode =
+ | "file_info_failed"
+ | "list_failed"
+ | "read_failed"
+ | "parse_failed";
+
+type TemplateDiagnostic = {
+ code: TemplateDiagnosticCode;
+ message: string;
+ path: string;
+ source: ComposerTemplateSource;
+};
+
+type LoadedTemplate = {
+ promptTemplate: PromptTemplate;
+ argumentHint?: string;
+ source: ComposerTemplateSource;
+};
+
+type ParsedPrompt = {
+ frontmatter: Record<string, unknown>;
+ body: string;
+};
+
function normalizeTemplateName(name: string): string {
const normalized = name.replace(/\\/g, "/").replace(/\/+$/, "");
const slashIndex = normalized.lastIndexOf("/");
@@ -54,26 +78,174 @@ export function composerTemplateDirs(
};
}
-/**
- * pi's loader keeps only name/description/content; `argument-hint` needs a
- * second look at the file's frontmatter block. Missing/unreadable files are
- * non-fatal — the hint is cosmetic.
- */
-async function readArgumentHint(filePath: string): Promise<string | undefined> {
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function parsePrompt(raw: string): ParsedPrompt {
+ const normalized = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
+ if (!normalized.startsWith("---")) {
+ return { frontmatter: {}, body: normalized };
+ }
+ const endIndex = normalized.indexOf("\n---", 3);
+ if (endIndex === -1) return { frontmatter: {}, body: normalized };
+ const parsed: unknown = parse(normalized.slice(4, endIndex)) ?? {};
+ return {
+ frontmatter: isRecord(parsed) ? parsed : {},
+ body: normalized.slice(endIndex + 4).trim(),
+ };
+}
+
+function parseErrorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+async function resolvePathKind(
+ path: string,
+): Promise<{ path: string; kind: "file" | "directory" } | undefined> {
try {
- const raw = await readFile(filePath, "utf8");
- const normalized = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
- if (!normalized.startsWith("---")) return undefined;
- const end = normalized.indexOf("\n---", 3);
- if (end === -1) return undefined;
- const frontmatter = normalized.slice(4, end);
- const match = frontmatter.match(/^argument-hint:[ \t]*(.+)$/m);
- if (!match) return undefined;
- const value = match[1].trim().replace(/^["']|["']$/g, "");
- return value || undefined;
- } catch {
+ const stats = await lstat(path);
+ if (stats.isFile()) return { path, kind: "file" };
+ if (stats.isDirectory()) return { path, kind: "directory" };
+ if (!stats.isSymbolicLink()) return undefined;
+ const target = await realpath(path);
+ const targetStats = await lstat(target);
+ if (targetStats.isFile()) return { path, kind: "file" };
+ if (targetStats.isDirectory()) return { path, kind: "directory" };
return undefined;
+ } catch (error) {
+ if (isMissingPath(error)) return undefined;
+ throw error;
+ }
+}
+
+function isMissingPath(error: unknown): boolean {
+ return isRecord(error) && error.code === "ENOENT";
+}
+
+async function loadTemplateFile(
+ filePath: string,
+ source: ComposerTemplateSource,
+): Promise<{ template?: LoadedTemplate; diagnostic?: TemplateDiagnostic }> {
+ let raw: string;
+ try {
+ raw = await readFile(filePath, "utf8");
+ } catch (error) {
+ return {
+ diagnostic: {
+ code: "read_failed",
+ message: parseErrorMessage(error),
+ path: filePath,
+ source,
+ },
+ };
+ }
+
+ let parsed: ParsedPrompt;
+ try {
+ parsed = parsePrompt(raw);
+ } catch (error) {
+ return {
+ diagnostic: {
+ code: "parse_failed",
+ message: parseErrorMessage(error),
+ path: filePath,
+ source,
+ },
+ };
+ }
+
+ const firstLine = parsed.body.split("\n").find((line) => line.trim());
+ let description = typeof parsed.frontmatter.description === "string"
+ ? parsed.frontmatter.description
+ : "";
+ if (!description && firstLine) {
+ description = firstLine.slice(0, 60);
+ if (firstLine.length > 60) description += "...";
+ }
+ const name = normalizeTemplateName(filePath);
+ const promptTemplate: PromptTemplate = {
+ name,
+ description,
+ content: parsed.body,
+ };
+ const argumentHint = typeof parsed.frontmatter["argument-hint"] === "string"
+ ? parsed.frontmatter["argument-hint"]
+ : undefined;
+ return {
+ template: {
+ promptTemplate,
+ ...(argumentHint ? { argumentHint } : {}),
+ source,
+ },
+ };
+}
+
+async function loadTemplatesFromPath(
+ path: string,
+ source: ComposerTemplateSource,
+ cwd: string,
+): Promise<{ templates: LoadedTemplate[]; diagnostics: TemplateDiagnostic[] }> {
+ const resolved = resolve(cwd, path);
+ let info: { path: string; kind: "file" | "directory" } | undefined;
+ try {
+ info = await resolvePathKind(resolved);
+ } catch (error) {
+ return {
+ templates: [],
+ diagnostics: [{
+ code: "file_info_failed",
+ message: parseErrorMessage(error),
+ path: resolved,
+ source,
+ }],
+ };
+ }
+ if (!info) return { templates: [], diagnostics: [] };
+
+ const diagnostics: TemplateDiagnostic[] = [];
+ let files: string[];
+ if (info.kind === "file") {
+ files = info.path.endsWith(".md") ? [info.path] : [];
+ } else {
+ let names: string[];
+ try {
+ names = await readdir(info.path);
+ } catch (error) {
+ return {
+ templates: [],
+ diagnostics: [{
+ code: "list_failed",
+ message: parseErrorMessage(error),
+ path: info.path,
+ source,
+ }],
+ };
+ }
+ files = [];
+ for (const name of names.sort((a, b) => a.localeCompare(b))) {
+ if (!name.endsWith(".md")) continue;
+ const filePath = join(info.path, name);
+ try {
+ if ((await resolvePathKind(filePath))?.kind === "file") files.push(filePath);
+ } catch (error) {
+ diagnostics.push({
+ code: "file_info_failed",
+ message: parseErrorMessage(error),
+ path: filePath,
+ source,
+ });
+ }
+ }
}
+
+ const templates: LoadedTemplate[] = [];
+ for (const file of files) {
+ const fileInfo = await loadTemplateFile(file, source);
+ if (fileInfo.template) templates.push(fileInfo.template);
+ if (fileInfo.diagnostic) diagnostics.push(fileInfo.diagnostic);
+ }
+ return { templates, diagnostics };
}
/**
@@ -86,27 +258,23 @@ export async function loadComposerTemplates(
overrideDirs?: ComposerTemplateDirs,
): Promise<{ templates: ComposerTemplate[]; diagnostics: string[] }> {
const dirs = overrideDirs ?? composerTemplateDirs(workspaceRoot);
- const env = new NodeExecutionEnv({ cwd: workspaceRoot || homedir() });
+ const cwd = workspaceRoot || homedir();
const inputs: Array<{ path: string; source: ComposerTemplateSource }> = [
...(dirs.project ? [{ path: dirs.project, source: "project" as const }] : []),
- { path: dirs.user, source: "user" as const },
+ { path: dirs.user, source: "user" },
];
- const loaded = await loadSourcedPromptTemplates(
- env,
- inputs,
- undefined,
- BACKGROUND_CONTEXT,
- );
+ const loaded: LoadedTemplate[] = [];
+ const diagnostics: TemplateDiagnostic[] = [];
+ for (const input of inputs) {
+ const result = await loadTemplatesFromPath(input.path, input.source, cwd);
+ loaded.push(...result.templates);
+ diagnostics.push(...result.diagnostics);
+ }
const byName = new Map<string, ComposerTemplate>();
- for (const { promptTemplate, source } of loaded.promptTemplates) {
- // Inputs are ordered project-first, so the first occurrence wins.
+ for (const { promptTemplate, argumentHint, source } of loaded) {
const name = normalizeTemplateName(promptTemplate.name);
if (byName.has(name)) continue;
- const dir = source === "project" ? dirs.project : dirs.user;
- const argumentHint = dir
- ? await readArgumentHint(join(dir, `${name}.md`))
- : undefined;
byName.set(name, {
...promptTemplate,
name,
@@ -116,13 +284,13 @@ export async function loadComposerTemplates(
}
return {
templates: [...byName.values()],
- diagnostics: loaded.diagnostics.map(
- (d) => `${d.source}:${d.code}: ${d.message} (${d.path})`,
+ diagnostics: diagnostics.map(
+ (diagnostic) => `${diagnostic.source}:${diagnostic.code}: ${diagnostic.message} (${diagnostic.path})`,
),
};
}
-const PLACEHOLDER_RE = /\$\d+|\$\{@:\d+(?::\d+)?\}|\$ARGUMENTS|\$@/;
+const PLACEHOLDER_RE = /\$\{(?:\d+|ARGUMENTS|@):-[^}]*\}|\$\{@:\d+(?::\d+)?\}|\$ARGUMENTS|\$@|\$\d+/;
export type SlashExpansion = {
/** Expanded prompt text the model receives (persisted as `content`). */
@@ -131,10 +299,61 @@ export type SlashExpansion = {
command: string;
};
+/** Parse an argument string using simple shell-style single and double quotes. */
+export function parseCommandArgs(argsString: string): string[] {
+ const args: string[] = [];
+ let current = "";
+ let inQuote: "'" | '"' | null = null;
+ for (const char of argsString) {
+ if (inQuote) {
+ if (char === inQuote) inQuote = null;
+ else current += char;
+ } else if (char === '"' || char === "'") {
+ inQuote = char;
+ } else if (char === " " || char === "\t") {
+ if (current) {
+ args.push(current);
+ current = "";
+ }
+ } else {
+ current += char;
+ }
+ }
+ if (current) args.push(current);
+ return args;
+}
+
+/** Substitute pi's prompt-template positional and aggregate argument placeholders. */
+export function substituteArgs(content: string, args: string[]): string {
+ const allArgs = args.join(" ");
+ return content.replace(
+ /\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,
+ (_match, defaultTarget: string | undefined, defaultValue: string | undefined,
+ sliceStart: string | undefined, sliceLength: string | undefined, simple: string | undefined) => {
+ if (defaultTarget) {
+ const value = defaultTarget === "@" || defaultTarget === "ARGUMENTS"
+ ? allArgs
+ : args[Number.parseInt(defaultTarget, 10) - 1];
+ return value ? value : defaultValue ?? "";
+ }
+ if (sliceStart) {
+ const start = Math.max(0, Number.parseInt(sliceStart, 10) - 1);
+ if (sliceLength) {
+ return args.slice(start, start + Number.parseInt(sliceLength, 10)).join(" ");
+ }
+ return args.slice(start).join(" ");
+ }
+ if (simple === "ARGUMENTS" || simple === "@") return allArgs;
+ if (simple) return args[Number.parseInt(simple, 10) - 1] ?? "";
+ return _match;
+ },
+ );
+}
+
/**
* Expand a leading `/name args` invocation against loaded templates using
- * pi's exact argument grammar. Returns null when the draft is not a
- * template invocation (unknown names stay literal text, D123).
+ * pi's argument grammar. Returns null when the draft is not a template
+ * invocation (unknown names stay literal text, D123).
*
* One deliberate extension over pi: when a template has no placeholder at
* all, non-empty arguments are appended after a blank line instead of being
@@ -149,11 +368,10 @@ export function expandSlashInvocation(
const token = tokenEnd === -1 ? content : content.slice(0, tokenEnd);
const name = token.slice(1);
if (!name) return null;
- const template = templates.find((t) => t.name === name);
+ const template = templates.find((item) => item.name === name);
if (!template) return null;
const rest = (tokenEnd === -1 ? "" : content.slice(tokenEnd)).trim();
- // parseCommandArgs only splits on spaces/tabs; fold newlines in first.
const args = parseCommandArgs(rest.replace(/[\n\r]+/g, " "));
let expanded = substituteArgs(template.content, args);
if (rest && !PLACEHOLDER_RE.test(template.content)) {
@@ -161,6 +379,3 @@ export function expandSlashInvocation(
}
return { expanded, command: content.trim() };
}
-
-export { parseCommandArgs, substituteArgs };
-export type { PromptTemplate };
diff --git a/packages/agent-runtime/src/reasoning-replay.test.ts b/packages/agent-runtime/src/reasoning-replay.test.ts
index a196e10c6..22bf329d1 100644
--- a/packages/agent-runtime/src/reasoning-replay.test.ts
+++ b/packages/agent-runtime/src/reasoning-replay.test.ts
@@ -1,9 +1,8 @@
import { describe, expect, it } from "vitest";
import type {
AgentMessage,
- CompactionEntry,
- MessageEntry,
} from "@earendil-works/pi-agent-core";
+import type { CompactionEntry, MessageEntry } from "./pi-runtime-types.js";
import { convertMessages } from "@earendil-works/pi-ai/api/openai-completions";
import { DEEPSEEK_REASONING_REPLAY_PLACEHOLDER } from "@pi-desktop/shared";
import {
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index a511a7060..b26e27786 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
-import { estimateContextTokens as estimateAgentContextTokens, estimateTokens, type Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
+import { type Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
import {
createAssistantMessageEventStream,
getCurrentTools,
@@ -10,6 +10,7 @@ import {
import { formatSessionMessage, type SessionMessageOrigin } from "@pi-desktop/shared";
import { estimateContextTokens as estimateTranscriptTokens } from "@earendil-works/pi-ai/utils/estimate";
import { buildSessionContext } from "./session-context.js";
+import { estimateContextTokens as estimateAgentContextTokens, estimateTokens } from "./pi-runtime-estimates.js";
import {
COMPACTION_FALLBACK_MARKER,
DesktopAgentRuntime,
@@ -5942,9 +5943,9 @@ describe("DesktopAgentRuntime per-turn context protection", () => {
it("keeps the summary a fallback checkpoint carries forward", async () => {
// A fallback checkpoint stores any carried-forward summary ahead of its
// recovery notice (see `createFallbackCheckpoint`). The next preparation
- // must strip only the notice: pi's `prepareCompaction` cannot rebuild the
- // older context from the transcript on its own, so dropping the carried
- // summary would lose it permanently (#224).
+ // must strip only the notice: preparation cannot rebuild the older context
+ // from the transcript on its own, so dropping the carried summary would
+ // lose it permanently (#224).
const runtime = createRuntime();
(runtime as any).fullEntries = [
{
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 4b3a47556..38e3f9b49 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -14,13 +14,6 @@ import {
} from "./delegation-message.js";
import {
Agent,
- BACKGROUND_CONTEXT,
- compact,
- convertToLlm,
- estimateContextTokens,
- estimateTokens,
- prepareCompaction,
- withAbortSignal,
type AgentContext,
type AgentEvent,
type AgentLoopTurnUpdate,
@@ -29,13 +22,8 @@ import {
type AgentToolResult,
type AfterToolCallContext,
type AfterToolCallResult,
- type CompactionPreparation,
- type CompactionEntry,
- type CompactionSettings,
type BeforeToolCallContext,
type BeforeToolCallResult,
- type Entry,
- type MessageEntry,
type PrepareNextTurnContext,
} from "@earendil-works/pi-agent-core";
import {
@@ -134,6 +122,20 @@ import {
} from "./agent-messages.js";
import { withExplicitRequired } from "./tool-schema.js";
import { buildSessionContext } from "./session-context.js";
+import { prepareCompaction } from "./pi-runtime-compaction-plan.js";
+import { compact } from "./pi-runtime-compaction-summary.js";
+import {
+ estimateContextTokens,
+ estimateTokens,
+} from "./pi-runtime-estimates.js";
+import { convertToLlm } from "./pi-runtime-messages.js";
+import type {
+ CompactionEntry,
+ CompactionPreparation,
+ CompactionSettings,
+ Entry,
+ MessageEntry,
+} from "./pi-runtime-types.js";
import {
initialSystemTranscript,
rebuildSystemTranscript,
@@ -6999,9 +7001,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
try {
const result = await compact(
preparation,
- // The summary is a provider request like any other turn, but
- // pi-agent-core builds its options itself and never reaches `streamFn`,
- // so the headers have to ride on the collection.
+ // The summary is a provider request like any other turn. The desktop
+ // compaction adapter calls `completeSimple` directly instead of
+ // `streamFn`, so headers have to ride on the collection.
models,
this.model,
undefined,
@@ -7011,7 +7013,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// pi's classifier decides what is transient; the waits honour `signal`.
COMPACTION_SUMMARY_RETRY_POLICY,
undefined,
- withAbortSignal(signal, BACKGROUND_CONTEXT),
+ signal,
);
if (!result.ok) {
this.emitCompactionFailureDiagnostic(
diff --git a/packages/agent-runtime/src/session-context.test.ts b/packages/agent-runtime/src/session-context.test.ts
index 3fd3522f2..618928123 100644
--- a/packages/agent-runtime/src/session-context.test.ts
+++ b/packages/agent-runtime/src/session-context.test.ts
@@ -1,9 +1,8 @@
import { describe, expect, it } from "vitest";
import type {
AgentMessage,
- CompactionEntry,
- MessageEntry,
} from "@earendil-works/pi-agent-core";
+import type { CompactionEntry, MessageEntry } from "./pi-runtime-types.js";
import { buildSessionContext } from "./session-context.js";
function user(id: string, text: string, seq: number): MessageEntry {
diff --git a/packages/agent-runtime/src/session-context.ts b/packages/agent-runtime/src/session-context.ts
index 5aae7c8de..bf640bb67 100644
--- a/packages/agent-runtime/src/session-context.ts
+++ b/packages/agent-runtime/src/session-context.ts
@@ -1,23 +1,22 @@
/**
* Project pi session entries into the model context.
*
- * pi 0.85 moved `buildSessionContext` off the public package export and made
- * the remaining helper async for custom-entry projectors. PI-Desktop
- * synthesizes only message and compaction entries, so the projection stays
- * synchronous and keeps the `{ messages }` shape the runtime already uses.
+ * The runtime owns this synchronous projection because its transcript includes
+ * desktop-only entries and persisted host checkpoints. It keeps the
+ * `{ messages }` shape consumed by the agent loop.
*
* The slice-from-latest-compaction and compactionSummary-before-retainedTail
- * order are copied from pi-agent-core; D203 depends on that order. Retained
+ * order preserve the behavior D203 depends on. Retained
* reasoning turns (#296) sit between the summary and the user tail so strict
* DeepSeek relays still see real thinking without replaying tool-call pairs.
*/
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
createBranchSummaryMessage,
createCompactionSummaryMessage,
- type AgentMessage,
- type Entry,
-} from "@earendil-works/pi-agent-core";
+} from "./pi-runtime-messages.js";
+import type { Entry } from "./pi-runtime-types.js";
import {
retainedReasoningFromDetails,
retainedReasoningToMessages,
diff --git a/packages/agent-runtime/src/subagent-context.test.ts b/packages/agent-runtime/src/subagent-context.test.ts
index b83e48672..0e51803f9 100644
--- a/packages/agent-runtime/src/subagent-context.test.ts
+++ b/packages/agent-runtime/src/subagent-context.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it } from "vitest";
import {
- createCompactionSummaryMessage,
type AgentMessage,
type PrepareNextTurnContext,
} from "@earendil-works/pi-agent-core";
+import { createCompactionSummaryMessage } from "./pi-runtime-messages.js";
import type {
Api,
AssistantMessage,
diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.ts
index 725661f93..2bb801697 100644
--- a/packages/agent-runtime/src/subagent-context.ts
+++ b/packages/agent-runtime/src/subagent-context.ts
@@ -15,16 +15,7 @@
*/
import {
- BACKGROUND_CONTEXT,
- createCompactionSummaryMessage,
- generateSummaryWithUsage,
- prepareCompaction,
- withAbortSignal,
type AgentMessage,
- type CompactionSettings,
- type CompactionSummaryMessage,
- type Entry,
- type MessageEntry,
type PrepareNextTurnContext,
type ThinkingLevel,
} from "@earendil-works/pi-agent-core";
@@ -54,6 +45,10 @@ import {
reduceSummaryInput,
type CompactionSummaryInput,
} from "./compaction-summary-input.js";
+import { prepareCompaction } from "./pi-runtime-compaction-plan.js";
+import { generateSummaryWithUsage } from "./pi-runtime-compaction-summary.js";
+import { createCompactionSummaryMessage, type CompactionSummaryMessage } from "./pi-runtime-messages.js";
+import type { CompactionSettings, Entry, MessageEntry } from "./pi-runtime-types.js";
import type { UsageObserver } from "./request-usage.js";
import { withCompactionRequestHeaders } from "./compaction-request.js";
import {
@@ -120,9 +115,9 @@ export function subagentContextOverflowError(modelId: string): {
/**
* Build the provider registry a delegate summary request goes through, with
- * the same header seam the session's compaction uses: pi-agent-core hands the
- * collection to its own request path, so provider and session headers have to
- * ride on it.
+ * the same header seam as the session's compaction adapter. The summary
+ * request uses `completeSimple` on this collection, so provider and session
+ * headers have to ride on it.
*/
export function delegateSummaryModels(
provider: RuntimeProviderConfig,
@@ -258,7 +253,7 @@ function delegateContextBudgetFor(
}
/**
- * Compact through pi-agent-core's primitives, shaped the way the session's
+ * Compact through desktop-owned primitives, shaped the way the session's
* checkpoint is shaped: pi's three contiguous ranges are summarized as one,
* and the retained tail is rebuilt from the retention mode rather than pi's
* token cut, so no tool call can be orphaned from its result. Returns
@@ -326,7 +321,7 @@ async function compactDelegateContext(
input.thinkingLevel,
COMPACTION_SUMMARY_RETRY_POLICY,
undefined,
- withAbortSignal(input.signal, BACKGROUND_CONTEXT),
+ input.signal,
);
if (!result.ok) {
if (result.error.code === "aborted" || input.signal.aborted) {
@@ -504,8 +499,8 @@ function delegateSummaryInputExceedsBudget(
/**
* Synthetic message-entry chain for `prepareCompaction`. A delegate has no
- * durable entry log, so the cut point is computed over its in-memory messages
- * wrapped in the entry shape pi's compaction expects.
+ * durable entry log, so the runtime computes the cut point over its in-memory
+ * messages wrapped in the entry shape its preparation helper expects.
*/
function delegateMessageEntries(messages: AgentMessage[]): Entry[] {
let parentId: string | null = null;
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 5eef97509..cb2758698 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -24,7 +24,6 @@ import { join } from "node:path";
import { randomUUID } from "node:crypto";
import {
Agent,
- convertToLlm,
type AfterToolCallContext,
type AfterToolCallResult,
type AgentEvent,
@@ -59,6 +58,7 @@ import type { RuntimeProviderConfig } from "./provider-binding.js";
import { clampThinkingLevel } from "./thinking-level.js";
import { subagentModelBinding, type SubagentProviderRetryState } from "./subagent-model-binding.js";
import { contextBudgetFor } from "./context-budget.js";
+import { convertToLlm } from "./pi-runtime-messages.js";
import {
delegateRetentionMode,
delegateSummaryModels,
diff --git a/packages/agent-runtime/src/system-transcript.test.ts b/packages/agent-runtime/src/system-transcript.test.ts
index 0b5bf732e..854809a06 100644
--- a/packages/agent-runtime/src/system-transcript.test.ts
+++ b/packages/agent-runtime/src/system-transcript.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { Agent, convertToLlm, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
+import { Agent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
import {
createAssistantMessageEventStream,
getCurrentSystemMessage,
@@ -12,6 +12,7 @@ import {
type Tool,
} from "@earendil-works/pi-ai";
import { estimateContextTokens as estimateTranscriptTokens } from "@earendil-works/pi-ai/utils/estimate";
+import { convertToLlm } from "./pi-runtime-messages.js";
import {
initialSystemTranscript,
rebuildSystemTranscript,
diff --git a/patches/@[email protected] b/patches/@[email protected]
index b86f94477..17a4aa7ad 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -42,351 +42,3 @@ index a8ccfc0bd..0f98e4736 100644
timestamp: Date.now(),
};
await this.processEvents({ type: "message_start", message: failureMessage });
-diff --git a/dist/harness/compaction/compaction.d.ts b/dist/harness/compaction/compaction.d.ts
-index 85c89e80b..995a28d5e 100644
---- a/dist/harness/compaction/compaction.d.ts
-+++ b/dist/harness/compaction/compaction.d.ts
-@@ -53,12 +53,12 @@ export interface ContextUsageEstimate {
- /** Index of the message that provided usage, or null when none exists. */
- lastUsageIndex: number | null;
- }
--/** Estimate context tokens for messages using provider usage when available. */
--export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
-+/** Estimate context tokens for messages using provider usage when available. Pass `model` to scope hosted search replay projections to the estimation target. */
-+export declare function estimateContextTokens(messages: AgentMessage[], model?: Model<Api>): ContextUsageEstimate;
- /** Return whether context usage exceeds the configured compaction threshold. */
- export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean;
--/** Estimate token count for one message using a conservative character heuristic. */
--export declare function estimateTokens(message: AgentMessage): number;
-+/** Estimate token count for one message using a conservative character heuristic. Pass `model` to scope hosted search replay projections to the estimation target. */
-+export declare function estimateTokens(message: AgentMessage, model?: Model<Api>): number;
- /** Find the user-visible message that starts the turn containing an entry. */
- export declare function findTurnStartIndex(entries: Entry[], entryIndex: number, startIndex: number): number;
- /** Cut point selected for compaction. */
-diff --git a/dist/harness/compaction/compaction.js b/dist/harness/compaction/compaction.js
-index d430a3f96..1682577b7 100644
---- a/dist/harness/compaction/compaction.js
-+++ b/dist/harness/compaction/compaction.js
-@@ -1,18 +1,12 @@
--import { contentText, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";
-+import { contentText, retryAssistantCall, uuidv7, LocalRequestError, } from "@earendil-works/pi-ai";
-+import { estimateMessageTokens, getLastAssistantUsageInfo } from "@earendil-works/pi-ai/utils/estimate";
-+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";
- import { getTelemetryContext } from "../context.js";
- import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage } from "../messages.js";
- import { buildContextEntries, sessionEntryToContextMessages } from "../session/context.js";
- import { CompactionError, err, ok } from "../types.js";
- import { addUsage } from "../utils/usage.js";
- import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, serializeConversation, } from "./utils.js";
--function safeJsonStringify(value) {
-- try {
-- return JSON.stringify(value) ?? "undefined";
-- }
-- catch {
-- return "[unserializable]";
-- }
--}
- function extractFileOperations(messages, entries, prevCompactionIndex) {
- const fileOps = createFileOps();
- if (prevCompactionIndex >= 0) {
-@@ -105,21 +99,14 @@ export function getLastAssistantUsage(entries) {
- }
- return undefined;
- }
--function getLastAssistantUsageInfo(messages) {
-- for (let i = messages.length - 1; i >= 0; i--) {
-- const usage = getAssistantUsage(messages[i]);
-- if (usage)
-- return { usage, index: i };
-- }
-- return undefined;
--}
- /** Estimate context tokens for messages using provider usage when available. */
--export function estimateContextTokens(messages) {
-+export function estimateContextTokens(messages, model) {
-+ validateHostedSearchMessages(messages);
- const usageInfo = getLastAssistantUsageInfo(messages);
- if (!usageInfo) {
- let estimated = 0;
- for (const message of messages) {
-- estimated += estimateTokens(message);
-+ estimated += estimateTokens(message, model);
- }
- return {
- tokens: estimated,
-@@ -131,7 +118,7 @@ export function estimateContextTokens(messages) {
- const usageTokens = calculateContextTokens(usageInfo.usage);
- let trailingTokens = 0;
- for (let i = usageInfo.index + 1; i < messages.length; i++) {
-- trailingTokens += estimateTokens(messages[i]);
-+ trailingTokens += estimateTokens(messages[i], model);
- }
- return {
- tokens: usageTokens + trailingTokens,
-@@ -163,30 +150,15 @@ function estimateTextAndImageContentChars(content) {
- return chars;
- }
- /** Estimate token count for one message using a conservative character heuristic. */
--export function estimateTokens(message) {
-+export function estimateTokens(message, model) {
- let chars = 0;
- switch (message.role) {
-- case "user": {
-- chars = estimateTextAndImageContentChars(message.content);
-- return Math.ceil(chars / 4);
-- }
-- case "assistant": {
-- const assistant = message;
-- for (const block of assistant.content) {
-- if (block.type === "text") {
-- chars += block.text.length;
-- }
-- else if (block.type === "thinking") {
-- chars += block.thinking.length;
-- }
-- else if (block.type === "toolCall") {
-- chars += block.name.length + safeJsonStringify(block.arguments).length;
-- }
-- }
-- return Math.ceil(chars / 4);
-- }
-- case "custom":
-- case "toolResult": {
-+ case "system":
-+ case "user":
-+ case "assistant":
-+ case "toolResult":
-+ return estimateMessageTokens(message, model);
-+ case "custom": {
- chars = estimateTextAndImageContentChars(message.content);
- return Math.ceil(chars / 4);
- }
-@@ -200,7 +172,7 @@ export function estimateTokens(message) {
- return Math.ceil(chars / 4);
- }
- }
-- return 0;
-+ throw new LocalRequestError("context-validation");
- }
- function findValidCutPoints(entries, startIndex, endIndex) {
- const cutPoints = [];
-diff --git a/dist/harness/compaction/utils.js b/dist/harness/compaction/utils.js
-index f7c6a26ac..a5de5589f 100644
---- a/dist/harness/compaction/utils.js
-+++ b/dist/harness/compaction/utils.js
-@@ -1,4 +1,5 @@
- import { contentText } from "@earendil-works/pi-ai";
-+import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";
- /** Create an empty file-operation accumulator. */
- export function createFileOps() {
- return {
-@@ -86,6 +87,7 @@ export function serializeConversation(messages) {
- else if (msg.role === "assistant") {
- const thinkingParts = [];
- const toolCalls = [];
-+ const hostedSearchParts = [];
- for (const block of msg.content) {
- if (block.type === "thinking") {
- thinkingParts.push(block.thinking);
-@@ -97,6 +99,13 @@ export function serializeConversation(messages) {
- .join(", ");
- toolCalls.push(`${block.name}(${argsStr})`);
- }
-+ else if (block.type === "hostedSearch") {
-+ // Keep the hosted search replay buffer explicit: the projection is the raw wire block, never a toolCall.
-+ const projection = hostedSearchReplayProjection(block);
-+ if (projection !== undefined) {
-+ hostedSearchParts.push(safeJsonStringify(projection));
-+ }
-+ }
- }
- if (thinkingParts.length > 0) {
- parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);
-@@ -107,6 +116,9 @@ export function serializeConversation(messages) {
- if (toolCalls.length > 0) {
- parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);
- }
-+ if (hostedSearchParts.length > 0) {
-+ parts.push(`[Assistant hosted search]: ${hostedSearchParts.join("\n")}`);
-+ }
- }
- else if (msg.role === "toolResult") {
- const content = contentText(msg.content, "");
-diff --git a/dist/harness/pico3/kinds/collapse.d.ts b/dist/harness/pico3/kinds/collapse.d.ts
-index 736c315ec..4517456d3 100644
---- a/dist/harness/pico3/kinds/collapse.d.ts
-+++ b/dist/harness/pico3/kinds/collapse.d.ts
-@@ -1,5 +1,5 @@
- import type { Context } from "@earendil-works/chord";
--import { type CoreKind, type Entry, type HookInfo, type HookResult, type Id, type ModelRef, type RetryPolicy, type ThinkingLevel } from "../types.ts";
-+import { type CoreKind, type Entry, type HookInfo, type HookResult, type Id, type Model, type ModelRef, type RetryPolicy, type ThinkingLevel } from "../types.ts";
- export type CollapseInput = {
- reason: "threshold" | "manual" | "overflow";
- through: Id;
-@@ -44,6 +44,7 @@ export declare const collapseConfig: {
- export declare const collapse: CoreKind<CollapseInput, CollapseCheckpoint, {
- summary: Id;
- }, CollapseFailure, null, CollapseHooks, typeof collapseConfig>;
--export declare function chooseThrough(entries: Entry[], keepRecent: number): Id | undefined;
-+/** Select the collapse cutoff. Pass `model` to scope hosted search replay projections to the target model. */
-+export declare function chooseThrough(entries: Entry[], keepRecent: number, model?: Model): Id | undefined;
- export {};
- //# sourceMappingURL=collapse.d.ts.map
-\ No newline at end of file
-diff --git a/dist/harness/pico3/kinds/collapse.js b/dist/harness/pico3/kinds/collapse.js
-index 2fa0e3570..1a22a7d33 100644
---- a/dist/harness/pico3/kinds/collapse.js
-+++ b/dist/harness/pico3/kinds/collapse.js
-@@ -2,7 +2,7 @@ import { estimateContextTokens } from "@earendil-works/pi-ai/utils/estimate";
- import { effectiveTools } from "../system.js";
- import { toStored, } from "../types.js";
- import { retryDecision } from "./generation.js";
--const estimate = (messages) => estimateContextTokens(messages.filter((message) => message.role !== "system")).tokens;
-+const estimate = (messages, model) => estimateContextTokens(messages.filter((message) => message.role !== "system"), model).tokens;
- export const collapseConfig = { rewindable: { threshold: 0, keepRecent: 20_000 } };
- const failed = (reason, detail) => ({
- status: "failed",
-@@ -159,12 +159,12 @@ function afterFailure(base, message, detail, runtime) {
- },
- };
- }
--export function chooseThrough(entries, keepRecent) {
-+export function chooseThrough(entries, keepRecent, model) {
- const exchanges = [];
- let open;
- for (const entry of entries) {
- const role = entry.model?.[0]?.role;
-- const tokens = estimate((entry.model ?? []));
-+ const tokens = estimate((entry.model ?? []), model);
- if (role === "assistant") {
- open = { last: entry.id, tokens };
- exchanges.push(open);
-diff --git a/dist/harness/pico3/kinds/frames.js b/dist/harness/pico3/kinds/frames.js
-index f34eede37..fc0191d71 100644
---- a/dist/harness/pico3/kinds/frames.js
-+++ b/dist/harness/pico3/kinds/frames.js
-@@ -1,3 +1,4 @@
-+import { normalizeHostedSearchContent } from "@earendil-works/pi-ai";
- /**
- * Apply one encoded frame to the tracked output. Same switch as pi-ai's
- * reduceAssistantMessageFrames (the test oracle); no buffering, no second copy.
-@@ -12,6 +13,21 @@ export function applyFrame(o, frame) {
- throw new Error(`${frame.type} before start`);
- const c = m.content;
- switch (frame.type) {
-+ case "hosted_search_update": {
-+ // Search snapshots are not tool calls: preserve indices and detach mutable encoder objects.
-+ const index = frame.contentIndex;
-+ if (!Number.isInteger(index) || index < 0 || index > c.length)
-+ throw new Error("Invalid hosted search frame content index or gap");
-+ const content = normalizeHostedSearchContent(structuredClone(frame.content));
-+ // Match the encoder's optional-field snapshot rather than materializing a default.
-+ if (content.phase === "web_search_tool_result" && frame.content.isError === undefined)
-+ delete content.isError;
-+ const previous = c[index];
-+ if (previous && (previous.type !== "hostedSearch" || previous.phase !== content.phase || previous.blockId !== content.blockId))
-+ throw new Error("Hosted search frame changed block identity");
-+ c[index] = content;
-+ return;
-+ }
- case "text_start":
- c[frame.contentIndex] = { ...frame.content };
- return;
-diff --git a/dist/harness/pico3/kinds/generation.js b/dist/harness/pico3/kinds/generation.js
-index 01ffaa587..73970f394 100644
---- a/dist/harness/pico3/kinds/generation.js
-+++ b/dist/harness/pico3/kinds/generation.js
-@@ -1,3 +1,4 @@
-+import { localRequestErrorDetails } from "@earendil-works/pi-ai";
- import { AssistantMessageFrameEncoder, isRetryableAssistantError } from "@earendil-works/pi-ai";
- import { estimateContextTokens } from "@earendil-works/pi-ai/utils/estimate";
- import { planManagedEntry, prepareDraft, sameSnapshot, takeSnapshot } from "../system.js";
-@@ -28,8 +29,8 @@ const failStep = (task, reason, detail) => ({
- },
- });
- /** pi-ai drops system messages and aborted/error assistant messages before sending; estimate what is sent. */
--const estimate = (messages) => estimateContextTokens(messages.filter((m) => m.role !== "system" &&
-- !(m.role === "assistant" && (m.stopReason === "aborted" || m.stopReason === "error")))).tokens;
-+const estimate = (messages, model) => estimateContextTokens(messages.filter((m) => m.role !== "system" &&
-+ !(m.role === "assistant" && (m.stopReason === "aborted" || m.stopReason === "error"))), model).tokens;
- const emptyUsage = () => ({
- input: 0,
- output: 0,
-@@ -93,8 +94,8 @@ export const generation = {
- if (model === undefined)
- return failStep(task, "no_model", `model ${cp.model.provider}/${cp.model.modelId} unavailable`);
- const derived = await derive(task, cp, rt, ctx);
-- if (estimate(derived.messages) > model.contextWindow - model.maxTokens)
-- return overflow(task, rt);
-+ if (estimate(derived.messages, model) > model.contextWindow - model.maxTokens)
-+ return overflow(task, rt, model);
- const attempt = cp.attempt + 1;
- await rt.commit((tx) => {
- tx.checkpoint({ ...cp, phase: "requesting", attempt });
-@@ -280,6 +281,7 @@ async function stream(cp, model, messages, rt, ctx) {
- catch (error) {
- if (ctx.abortSignal?.aborted)
- throw error;
-+ const errorDetails = localRequestErrorDetails(error);
- terminal = {
- role: "assistant",
- content: [],
-@@ -288,7 +290,8 @@ async function stream(cp, model, messages, rt, ctx) {
- model: model.id,
- usage: emptyUsage(),
- stopReason: "error",
-- errorMessage: String(error),
-+ errorMessage: errorDetails?.message ?? String(error),
-+ ...(errorDetails ? { errorDetails } : {}),
- timestamp: rt.now(),
- };
- }
-@@ -342,7 +345,7 @@ async function classify(task, cp, message, rt, ctx) {
- return {
- done: async (tx, current) => {
- const c = current.conversationId;
-- const collapseThrough = await thresholdCollapseThrough(tx, c, message); // read BEFORE the append
-+ const collapseThrough = await thresholdCollapseThrough(tx, c, message, rt.models.resolve(cp.model)); // read BEFORE the append
- const assistant = tx.appendEntry(c, {
- kind: "pi.assistant",
- model: [stored],
-@@ -379,7 +382,7 @@ async function classify(task, cp, message, rt, ctx) {
- return {
- done: async (tx, current) => {
- const c = current.conversationId;
-- const collapseThrough = await thresholdCollapseThrough(tx, c, message); // read BEFORE the append
-+ const collapseThrough = await thresholdCollapseThrough(tx, c, message, rt.models.resolve(cp.model)); // read BEFORE the append
- const head = await tx.newestEntry(c, { withHead: true });
- const assistant = tx.appendEntry(c, { kind: "pi.assistant", model: [stored], data: { attempt: cp.attempt } });
- tx.emit({ type: "generation.completed", taskId: current.id, entry: assistant, toolCalls: 0 });
-@@ -455,25 +458,25 @@ export function retryDecision(cp, message, now) {
- // Collapse triggers
- // ---------------------------------------------------------------------------
- /** Read-side of threshold collapse: computed before the assistant is appended, applied after. */
--async function thresholdCollapseThrough(tx, conversationId, message) {
-+async function thresholdCollapseThrough(tx, conversationId, message, model) {
- if ((await tx.tasks({ conversationId, kind: "pi.collapse", status: ["pending", "running"] })).length > 0)
- return undefined;
- const state = tx.rewindable(conversationId);
- if (state.threshold <= 0)
- return undefined;
- const { entries, messages } = await tx.context(conversationId);
-- const used = Math.max((message.usage?.input ?? 0) + (message.usage?.output ?? 0), estimate([...messages, toStored(message)]));
-+ const used = Math.max((message.usage?.input ?? 0) + (message.usage?.output ?? 0), estimate([...messages, toStored(message)], model));
- if (used <= state.threshold)
- return undefined;
-- return chooseThrough(entries, state.keepRecent);
-+ return chooseThrough(entries, state.keepRecent, model);
- }
--function overflow(task, rt) {
-+function overflow(task, rt, model) {
- return {
- done: async (tx, current) => {
- const c = current.conversationId;
- const state = tx.rewindable(c);
- const { entries, head } = await tx.context(c);
-- const through = chooseThrough(entries, state.keepRecent);
-+ const through = chooseThrough(entries, state.keepRecent, model);
- tx.sticky(c).turn = { tools: [] };
- if (through === undefined) {
- await tx.write(c, {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4010b26e9..0d8d79462 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -6,6 +6,9 @@ importers:
.:
configDependencies: {}
packageManagerDependencies:
+ '@pnpm/exe':
+ specifier: 12.8.1
+ version: 12.8.1
pnpm:
specifier: 12.8.1
version: 12.8.1
@@ -89,6 +92,11 @@ packages:
cpu: [x64]
os: [win32]
+ resolution: {integrity: sha512-ju5MeefhEEXI7NO3u6oj54uGBOkN0pVhI+tcmuZDkTTqVdRZvEVEo+zhjwAoe8vEXguQCvsa6cTDhmFPxpOXeQ==}
+ engines: {node: '>=18.*'}
+ hasBin: true
+
resolution: {integrity: sha512-9kupB1B/XOr+BsjTjmBS0BeURFgOwSed3Vv8EctIqoomRLZlmOB+dh2oSHKp/FfV+QK4f6SdAkGY1VhhKqu+RQ==}
engines: {node: '>=18.*'}
@@ -138,6 +146,23 @@ snapshots:
optional: true
+ optionalDependencies:
+ '@pnpm/exe.android-arm64': 12.8.1
+ '@pnpm/exe.android-x64': 12.8.1
+ '@pnpm/exe.darwin-arm64': 12.8.1
+ '@pnpm/exe.darwin-x64': 12.8.1
+ '@pnpm/exe.freebsd-x64': 12.8.1
+ '@pnpm/exe.linux-arm64': 12.8.1
+ '@pnpm/exe.linux-arm64-musl': 12.8.1
+ '@pnpm/exe.linux-ppc64': 12.8.1
+ '@pnpm/exe.linux-riscv64': 12.8.1
+ '@pnpm/exe.linux-s390x': 12.8.1
+ '@pnpm/exe.linux-x64': 12.8.1
+ '@pnpm/exe.linux-x64-musl': 12.8.1
+ '@pnpm/exe.win32-arm64': 12.8.1
+ '@pnpm/exe.win32-x64': 12.8.1
+
optionalDependencies:
'@pnpm/exe.android-arm64': 12.8.1
@@ -175,7 +200,7 @@ overrides:
patchedDependencies:
'@earendil-works/[email protected]':
- hash: b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7
+ hash: bbec87b73d8febb2bfc1441c900bb56488965269dcd1e858ec58e09365b09853
path: patches/@[email protected]
'@earendil-works/[email protected]':
hash: c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4
@@ -401,7 +426,7 @@ importers:
dependencies:
'@earendil-works/pi-agent-core':
specifier: 0.99.1
- version: 0.99.1(patch_hash=b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
+ version: 0.99.1(patch_hash=bbec87b73d8febb2bfc1441c900bb56488965269dcd1e858ec58e09365b09853)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-ai':
specifier: 0.99.1
version: 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
@@ -420,6 +445,9 @@ importers:
undici:
specifier: 8.10.2
version: 8.10.2
+ yaml:
+ specifier: 2.9.0
+ version: 2.9.0
devDependencies:
'@types/node':
specifier: ^24.13.3
@@ -5307,7 +5335,7 @@ snapshots:
dependencies:
esbuild: 0.28.2
- '@earendil-works/[email protected](patch_hash=b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=bbec87b73d8febb2bfc1441c900bb56488965269dcd1e858ec58e09365b09853)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':
dependencies:
'@earendil-works/chord': 0.99.1
'@earendil-works/pi-ai': 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
@@ -5386,7 +5414,7 @@ snapshots:
'@earendil-works/[email protected](patch_hash=0e05051778ef4ffca9bac7ec68cae64f1d659d4b8640eeeb1a121e0f620a6abe)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])':
dependencies:
'@earendil-works/chord': 0.99.1
- '@earendil-works/pi-agent-core': 0.99.1(patch_hash=b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
+ '@earendil-works/pi-agent-core': 0.99.1(patch_hash=bbec87b73d8febb2bfc1441c900bb56488965269dcd1e858ec58e09365b09853)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-ai': 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-codemode': 0.99.1
'@earendil-works/pi-mcp': 0.99.1
diff --git a/scripts/e2e-hosted-search.mjs b/scripts/e2e-hosted-search.mjs
index 64581c7b8..deaf64ed8 100644
--- a/scripts/e2e-hosted-search.mjs
+++ b/scripts/e2e-hosted-search.mjs
@@ -5,13 +5,84 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
-import { copyFile, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { parseArgs } from "node:util";
import { isolatedEnv } from "./e2e/hosted-search-sidecar.mjs";
import { runScenarios } from "./e2e/hosted-search-scenarios.mjs";
+async function collectArtifactFiles(directory, relative = "") {
+ const entries = await readdir(join(directory, relative), { withFileTypes: true });
+ const files = [];
+ for (const entry of entries) {
+ const child = relative ? join(relative, entry.name) : entry.name;
+ if (entry.isDirectory()) files.push(...(await collectArtifactFiles(directory, child)));
+ else if (entry.isFile()) files.push(child);
+ }
+ return files;
+}
+
+async function bundleArtifactHash(entry) {
+ const directory = resolve(entry, "..");
+ const packagePath = join(directory, "package.json");
+ let packageManifest;
+ try {
+ packageManifest = await readFile(packagePath);
+ } catch (error) {
+ if (error?.code !== "ENOENT") throw error;
+ packageManifest = Buffer.from('{"type":"module"}\n');
+ }
+
+ const files = [
+ ["entry", await readFile(entry)],
+ ["package.json", packageManifest],
+ ];
+ const chunksDirectory = join(directory, "chunks");
+ try {
+ if ((await stat(chunksDirectory)).isDirectory()) {
+ for (const relative of await collectArtifactFiles(chunksDirectory)) {
+ files.push([join("chunks", relative), await readFile(join(chunksDirectory, relative))]);
+ }
+ }
+ } catch (error) {
+ if (error?.code !== "ENOENT") throw error;
+ }
+
+ const digest = createHash("sha256");
+ for (const [name, content] of files.sort(([left], [right]) => left.localeCompare(right))) {
+ digest.update(name);
+ digest.update("\0");
+ digest.update(content);
+ }
+ return digest.digest("hex");
+}
+
+async function snapshotBundleArtifact(entry, directory) {
+ await mkdir(directory, { recursive: true });
+ const snapshotEntry = join(directory, "sidecar.mjs");
+ await copyFile(entry, snapshotEntry);
+
+ const sourceDirectory = resolve(entry, "..");
+ const packagePath = join(sourceDirectory, "package.json");
+ try {
+ await copyFile(packagePath, join(directory, "package.json"));
+ } catch (error) {
+ if (error?.code !== "ENOENT") throw error;
+ await writeFile(join(directory, "package.json"), '{"type":"module"}\n');
+ }
+
+ const chunksDirectory = join(sourceDirectory, "chunks");
+ try {
+ if ((await stat(chunksDirectory)).isDirectory()) {
+ await cp(chunksDirectory, join(directory, "chunks"), { recursive: true });
+ }
+ } catch (error) {
+ if (error?.code !== "ENOENT") throw error;
+ }
+ return snapshotEntry;
+}
+
const { values } = parseArgs({ options: {
bundle: { type: "string" }, "timeout-ms": { type: "string", default: "15000" },
help: { type: "boolean", short: "h" },
@@ -106,22 +177,23 @@ when the run ends; any change between the two fails the run.`);
}
}
const source = resolve(root, values.bundle ?? "packages/agent-runtime/dist-bundle/sidecar.js");
- const bundle = join(dir, "sidecar.mjs");
+ const bundleDirectory = join(dir, "artifact");
evidence.bundleSource = source;
- evidence.sha256 = await hash(source);
- // Snapshot the complete artifact so another agent's bundle rebuild cannot
- // silently replace code halfway through the child-process scenarios.
- await copyFile(source, bundle);
- assert.equal(await hash(bundle), evidence.sha256, "bundle changed during snapshot; rebuild and retry");
- console.log(`Bundle SHA-256: ${evidence.sha256}`);
+ evidence.sha256 = await bundleArtifactHash(source);
+ evidence.entrySha256 = await hash(source);
+ // Snapshot the entry, ESM package marker, and every relative chunk so a
+ // concurrent bundle rebuild cannot replace code halfway through scenarios.
+ const bundle = await snapshotBundleArtifact(source, bundleDirectory);
+ assert.equal(await bundleArtifactHash(bundle), evidence.sha256, "bundle changed during snapshot; rebuild and retry");
+ console.log(`Bundle artifact SHA-256: ${evidence.sha256}`);
evidence.results = await runScenarios(bundle, dir, timeoutMs, (result) => {
console.log(`${result.passed ? "PASS" : "FAIL"} ${result.name} (${result.requests} provider requests)`);
if (!result.passed) console.error(result.error);
});
- assert.equal(await hash(bundle), evidence.sha256, "executed snapshot was modified");
- // The snapshot protects execution; qualification also requires its source
- // artifact to remain stable for a reproducible build-to-test attribution.
- evidence.bundleSourceSha256After = await hash(source);
+ assert.equal(await bundleArtifactHash(bundle), evidence.sha256, "executed snapshot was modified");
+ // The snapshot protects execution; qualification also requires the source
+ // artifact and every relative chunk to remain stable during the run.
+ evidence.bundleSourceSha256After = await bundleArtifactHash(source);
evidence.bundleSourceRewrittenDuringRun = evidence.bundleSourceSha256After !== evidence.sha256;
assert.equal(evidence.bundleSourceRewrittenDuringRun, false, "bundle source changed during qualification");
evidence.passed = evidence.results.every((result) => result.passed);