Skip to content

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

fix(agent-runtime): repair hosted-search continuation contracts

ZeroY33cc4bc9a952
diff --git a/.gitattributes b/.gitattributes
index 6313b56c5..f07182edc 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1,5 @@
* text=auto eol=lf
+
+# Generated diffs encode an empty context line as one significant space.
+# Keep other whitespace diagnostics enabled; source-file checks are unchanged.
+patches/*.patch whitespace=-blank-at-eol
diff --git a/docs/adr/0297-provider-hosted-web-search-adapter-capability.md b/docs/adr/0297-provider-hosted-web-search-adapter-capability.md
index 21ccf2785..5df3434c3 100644
--- a/docs/adr/0297-provider-hosted-web-search-adapter-capability.md
+++ b/docs/adr/0297-provider-hosted-web-search-adapter-capability.md
@@ -102,8 +102,12 @@ Two upstream facts forced the design:
- `pause_turn` keeps pi-ai's existing mapping to `stop`; a long searching
turn may end early on the official Anthropic wire. This is a known
limitation to revisit with the upstream patch.
-- Compaction rewrites history and drops search blocks; later turns lose old
- grounding and the model searches again as needed. Documented behavior.
+- The original implementation omitted search from compaction serialization.
+ The 2026-09-22 contract repair supplies actual search replay projections to
+ the summary request instead. Prefix/tail retention is unchanged: compacted
+ content becomes a model-generated text summary (not lossless raw replay),
+ and retained-tail search follows the existing adapter replay policy. The
+ model can search again when the summary lacks sufficient grounding.
- Search executes on the provider. There is no local fetch, no ask/allow
prompt, and billing is the provider's. The model-level opt-in (default
off) is the user consent surface.
diff --git a/docs/project/hosted-search-contract-verification.md b/docs/project/hosted-search-contract-verification.md
new file mode 100644
index 000000000..089d5deb3
--- /dev/null
+++ b/docs/project/hosted-search-contract-verification.md
@@ -0,0 +1,219 @@
+# Hosted-search contract repair and verification
+
+## Outcome
+
+The ten approved acceptance criteria are met for the isolated, offline Desktop/sidecar scope. The original hosted-search tool-continuation failure is reproduced on the task baseline and prevented by formal content contracts, shared replay-aware estimates, semantically stable system reconstruction, and explicit local-error provenance. No fake tool fields, exception-to-zero fallback, history migration, timestamp forgery, or disabled search/Task path is used.
+
+Implementation qualification was completed on the uncommitted `fix/hosted-search-contract` candidate. The user subsequently authorized committing, pushing this task branch and opening a PR on 2026-09-22. The evidence below records the pre-commit candidate; PR delivery does not install, merge or release the application, or qualify a live provider.
+
+## Baseline and dependency identity
+
+- Refreshed `origin/main` and task HEAD: `46d4ee4ee3b608d103c5dacab2fbb754bacd6eca` (2026-09-22 local date).
+- Isolated worktree: `$PI_SCRATCH_DIR/hosted-search-worktree`.
+- At implementation qualification, the main checkout was clean at `0111e306c120ad5820688d7608cb37bad8fbcc1f`, with no task commit, push or PR. Follow-up PR delivery is separately authorized; no merge, release or application installation is included.
+- Node `24.21.0`, pnpm `10.34.5`. Installed `@earendil-works/pi-ai`, `pi-agent-core`, and `pi-coding-agent` are all **0.86.1**. The main checkout's stale 0.85.1 installation was not used for qualification.
+- Initial locked install reused 809 packages with zero downloads. Final patch generation and `pnpm install --frozen-lockfile` succeeded; package-patch generation is not a Git commit.
+- Parent byte comparison: all **1,093** staged runtime/declaration files match the installed packages (pi-ai 370, core 232, coding 491). Recorded in `hosted-final-dependency-identity.json` under session scratch.
+
+| Artifact | SHA-256 |
+| --- | --- |
+| pi-ai 0.86.1 patch | `db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe` |
+| pi-agent-core 0.86.1 patch | `62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1` |
+| pi-coding-agent 0.86.1 patch | `60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227` |
+| pnpm-lock.yaml | `9be9b37e77706661106729449a1347371470e12aea3a9fd3dc7c5557563d57f9` |
+| Final sidecar bundle | `6a3f4b96438578bd4a92976f44189bf8416ee81b31fbf9e05454d50ad020f5cd` |
+
+The lock, workspace patch entries, installed dependency links and final patch contents were independently cross-checked in review. Existing OAuth and provider-adapter modifications remain present.
+
+## Root cause and preserved architecture
+
+PR #635 (`23859ea38`) integrated search from #624 (`2e763893f`) and restart replay repair (`003bc0aeb`). Adapter search blocks/events were present without corresponding dependency declarations or estimator branches. The later pi upgrade (`c9db30629`) introduced transcript compatibility setters which refreshed a leading system timestamp during every rebuild. That incorrectly invalidated nonzero usage and exposed an estimator assuming every non-text/non-thinking assistant block was a tool call: `block.name.length` failed on legitimate nameless search results.
+
+The repair retains ADR 0297's adapter ownership, per-model opt-in, display rounds/raw replay separation, stored history shape, model-switch replay policy, and search UI. It does not add a local search implementation or runtime SSE re-parser.
+
+## Dependency delivery decision
+
+| Option | Feasibility and scope | Maintenance / upgrade cost | Decision |
+| --- | --- | --- | --- |
+| Existing public request/provider hooks | Can transform a context or replace a provider, but cannot register one content type across built-in parser events, declarations, replay, frame consumers and estimators. | Small hook changes would leave unpatched consumers; replacing search data with text/tool placeholders would hide the defect. | Insufficient alone. |
+| Desktop-owned adapter/source copies | Could implement the behavior, but duplicate Anthropic, Responses and Azure streaming/auth/replay plus independent compaction consumers. | Large parallel source surface and recurring upstream merge/testing burden. | Reject unnecessary duplication. |
+| New permanent upstream source fork | Could own the whole message contract and build all package entrypoints. | New repository, release pipeline, dependency ownership and long-term maintenance; outside the approved boundary. | Not required for this bounded fix. |
+| Existing pinned dependency patches | Already deliver the 0.86.1 search/OAuth modifications. The same reproducible channel can cover declarations and each actual Desktop consumer together. | Three pinned patch files must be rebased on upgrades; rerun type, adapter, estimation, frame, compaction and sidecar gates, not only a clean patch application. | Selected. |
+
+The package archives contain distributed JavaScript/declarations, not an upstream TypeScript source workspace. The bounded repair maintains both in the existing patch channel and tests the actual installed modules. `pnpm-workspace.yaml`, the three patch files and `pnpm-lock.yaml` reconstruct the installation; no direct installed-node_modules edit is required. pi-coding-agent needs its own patch because Desktop's native-session library has an independent compaction implementation.
+
+## Implementation invariants
+
+1. `HostedSearchContent` is a discriminated union for Anthropic `server_tool_use`, result/error results, and Responses `web_search_call`; stream events and runtime validation use the same formal capability. Legitimate result/activity blocks need no `name` or `arguments`.
+2. Shared normalization and replay projection drive requests, request-preflight estimates, output budgets, main/native compaction estimates and summary serialization. Display rounds/parser scratch are not billed twice. A known target model applies the existing adapter replay boundary; callers without target identity remain conservative.
+3. Valid usage covers its prefix once. Zero, error/aborted or genuinely invalidated usage falls back to complete estimation. Missing/non-finite timestamps are explicitly invalid, never replaced with an invented old time.
+4. Unchanged system reconstruction preserves semantic timestamps, system sections and effective tool additions/removals. Real instruction/tool changes invalidate prior usage. Restore remains conservative where persisted data cannot establish the former configuration.
+5. Search frames preserve identity, content indices, deep snapshots and optional fields; Mistral no longer treats search as an implicit function call. Both frame consumers are tested against the same encoder.
+6. Explicit `LOCAL_REQUEST_ERROR` plus a recognized phase preserves local provenance. Local validation, estimation and preparation failures are terminal `INTERNAL`, with safe details and no provider retry/fetch. Ordinary transport `TypeError`, HTTP transient retries and cancellation retain separate behavior. Wrapped cancellation produces an aborted main/subagent result.
+7. Old nameless search history remains readable without migration. Invalid restored data is rejected before a provider request or persistence write, with safe RPC metadata and a healthy process. In-memory input immutability is checked by source replay tests; the artifact boundary verifies no persistence Host RPC.
+8. Compaction strategy is unchanged: search projections are included in the summary request; the compacted prefix becomes generated text, not a lossless raw replay archive. The retained tail continues under the existing replay policy.
+
+## Red-to-green evidence
+
+All logs and fixture artifacts below are retained under `$PI_SCRATCH_DIR`, not committed as user/session data.
+
+| Regression | Observed red evidence | Final protection |
+| --- | --- | --- |
+| Real request preflight | Baseline dependency tests: 14/18 failed, including `streamSimple -> buildBaseOptions -> estimateMessageTokens` `.name.length`; `dependency-hosted-search-red.log`. | Installed contract/estimation tests in the green runtime suite. |
+| Output budget growth | Baseline 12 passed / 2 failed; +10,000 search characters added zero rather than 2,500 tokens, CJK correction zero rather than 750; `hosted-output-cap-red.log`. | Search projection and existing CJK policy both tested. |
+| System reconstruction | Unchanged rebuild invalidated usage and lost sections/tool deltas; `system-transcript-red-assertions.log`. | Helper and runtime restore/compaction/update regressions. |
+| Full continuation | Pure baseline bundle: 2/5 passed; Read, real instruction-change and Task failed with original `.length`; `hosted-search-e2e-e08Uj8/result.json`. Baseline bundle SHA `962446d15398de870b434b37620eb7c8c80dc9cf4f81b8f5ab48ee7ab3ae3495`. | Fresh final sidecar: 7/7 passed. |
+| Frames/model switching | Consumer baseline 17/21 failed; `dependency-consumers-red.log`. | 23 installed consumer tests pass, including both reducers. |
+| Native/main compaction | Final tests before installation: 18 failed / 4 passed; `compaction-test-preinstall-red.log`; staged 22/22 pass. | The same 22 tests pass without a loader against installed packages. |
+| Local error/cancellation provenance | Reverting provenance/cancellation changes makes four tests fail; `negcheck-summary.txt`. The new subagent un-aborted-signal cancellation case also fails on pre-fix code. | Error/retry/subagent tests pass, including ordinary 429/503 retry-before-fallback. |
+| Invalid restore RPC | Earlier repaired bundle passed five success cases but failed two new provenance checks; `hosted-search-e2e-J6J42v/result.json`. | Two real sender cases plus three real Host decoder tests. |
+| Anthropic citation shape | New test rejects non-URL/document citations on the old adapter; `hosted-citation-red.log`. | Valid raw URL citations preserved; final 3/3 error-result/citation tests pass. |
+
+The first final installed full-suite run exposed one real frame optional-field mismatch and two old retry fixtures lacking the required user timestamp (`hosted-runtime-final.log`: 913 passed / 3 failed). The core reducer now preserves an absent `isError` exactly like the encoder. The retry fixture is a typed `Message` with a legitimate timestamp; retry count/fallback assertions were not weakened. The subsequent full suite is 916/916 green (`hosted-runtime-final2.log`). Earlier green bundles and failed/intermediate build logs remain evidence, not substitutes for final qualification.
+
+## Final commands and observed results
+
+Run from the task worktree. Tests use synthetic/in-process or loopback external boundaries only; no real model/search service is called.
+
+| Command / check | Final observed result | Evidence under session scratch |
+| --- | --- | --- |
+| Three `pnpm patch-commit` operations, then `pnpm install --frozen-lockfile` | PASS; latest core optional-field correction regenerated and reinstalled successfully | `hosted-patch-*-final*.log`, `hosted-patched-install-final2.log` |
+| Installed package byte/version/hash comparison | PASS; 1,093 files, all three versions 0.86.1 | `hosted-final-dependency-identity.json` |
+| `pnpm --filter @pi-desktop/agent-runtime test` | PASS; **58 files / 916 tests** | `hosted-runtime-final2.log` |
+| Native-session coverage within runtime suite | PASS; **36 tests** (also independently run, not additional to 916) | `native-pi-session.json` |
+| `pnpm --filter @pi-desktop/shared test` | PASS; 80 files / 928 collected tests, including compiled mirrors | `hosted-shared-final.log` |
+| `pnpm --filter @pi-desktop/shared exec vitest run src` | PASS; **40 source files / 464 tests**; use this non-duplicated source count | `hosted-shared-source-final.log` |
+| `pnpm --filter @pi-desktop/host-runtime test` | PASS; **7 files / 38 tests**, including three new real stdio decoder cases | `hosted-host-runtime-final.log` |
+| `node --test apps/desktop/test/error-code-registry.test.mjs apps/desktop/test/rpc-lifecycle-contract.test.mjs apps/desktop/test/runtime-build-contract.test.mjs` | PASS; **20 tests** | `hosted-cross-process-final.log` |
+| `pnpm build:js` | PASS; all **11** recursive build projects, no downstream failures | `hosted-build-js-final2.log` |
+| `pnpm -r --if-present typecheck` | PASS; all **10** packages with that script; docs has no typecheck script | `hosted-typecheck-all-final2.log` |
+| `pnpm test:e2e:hosted-search` | PASS; fresh shared build + sidecar bundle, **7/7** cases; stricter no-write whitelist rerun also green | `hosted-e2e-final4.log`, `hosted-search-e2e-CS9uZW/result.json` |
+| `pnpm lint` | PASS; repository-configured coverage, not an invented runtime lint gate | `hosted-lint-final.log` |
+| `pnpm docs:check` | PASS; EN/ZH parity and documentation checks | `hosted-docs-check-final.log` |
+| `pnpm check:agent-policy`, `pnpm check:pr-base` | PASS | `hosted-check-agent-policy-final.log`, `hosted-check-pr-base-final.log` |
+| `git diff --check`, final Git state | PASS for the original 45-file unstaged implementation delta; the later PR preparation also checks staged files (see below) | `hosted-final-git-state.log`, `hosted-final-file-manifest.txt` |
+
+The root `test` / Rust build, `verify:ui:*`, application installation, real provider calls and manual application clicking were **not run**. No Rust source or method/storage schema changed. The additive error metadata travels through the existing RPC `error.data` field; shared, Host decoder, desktop registry/lifecycle and real sidecar sender tests cover that boundary.
+
+### Final artifact scenarios
+
+Final evidence directory: `$PI_SCRATCH_DIR/hosted-search-e2e-CS9uZW`. The bundle is copied to immutable `sidecar.mjs`. `result.json` records Node/pnpm, installed versions, baseline, lock hash, bundle hash and source fingerprints. The 251-file source scope fingerprint is `34ee5bac7d9dd0af5d7a828624d92a0439fe63fda7daca3c6e53ee7a54aa9b15` before and after; the original bundle hash also remains unchanged. Source identity unavailable/changed or bundle rewrite makes qualification fail.
+
+| Scenario | Result | Provider requests |
+| --- | --- | --- |
+| `search-next-prompt` | PASS | 2 |
+| `search-read` | PASS; ordinary real Read tool | 2 |
+| `search-read-instruction-change` | PASS; real changed prefix after nonzero usage (1,000 input / 1,030 total tokens) | 2 |
+| `search-task-delegation` | PASS; real Task/TaskWait and parent continuation | 4 |
+| `search-persist-restore` | PASS; disk JSON boundary and a new sidecar process | 2 |
+| `invalid-search-container` | PASS; safe local validation error, no persistence call/runtime leak | 0 |
+| `invalid-search-phase` | PASS; explicit rejection, no persistence call/runtime leak | 0 |
+
+Each invalid-history case subsequently completes a clean session in the same process using a separate loopback fixture provider (one request). Those recovery requests are recorded separately and are not hidden in the malformed-history zero-request count. The changed-prefix artifact verifies changed request instructions; direct usage-anchor invalidation is asserted by the companion estimator/system tests rather than inferred solely from the RPC boundary.
+
+## Independent review and disposition
+
+The complete change was partitioned for independent read-only review; failed model-quota review attempts are not counted as completed reviews. A local receipt summary is retained in `hosted-independent-review-summary.md`; the full reports are in this conversation's Task results.
+
+- Runtime source/system/budget/history/error/subagent partition: reviewer `e29420d1...`; cancellation and both RPC halves re-reviewed by `5f8dfc53...` — accepted, no blocker. The initial producer-test gap was corrected after reading the real bundled sender tests.
+- Dependency types/adapters/estimators/frames/compaction and final patch/lock/install partition: reviewer `a4695593...`, final `74371a0b...` — no blocker. Final review explicitly includes the latest core `isError` optional-field fix and hash `62947f96...`; prior OAuth/provider modifications confirmed retained.
+- Artifact harness/documentation partition: original reviewer `240c6e4a...`, final reviewer `9ad1cbf7...` — no blocker after fixes. Replaced the vacuous parent-object immutability assertion with no-persistence RPC checks, verified no registered-runtime leak and successful recovery, made source/provenance failures fail qualification, and clarified summary-request versus retained-tail semantics in EN/ZH specs and ADR 0297. The final whitelist was further narrowed to only `session.get`; final artifact rerun passed.
+- All substantive gaps were addressed: model threading, unknown-role zero fallback, citation shape, subagent cancel classification, frame snapshot consistency and evidence qualification. Existing duplicate budget computation is a non-blocking performance observation, not a changed result. A suggested stale retry-marker scenario was not demonstrated on the serial production path: `retryPendingProviderFailure` clears the marker before continuing the next request.
+
+## Acceptance criteria
+
+| # | Criterion | Status | Observed evidence |
+| --- | --- | --- | --- |
+| 1 | Reproducible baseline/dependencies | MET | Refreshed baseline, unchanged task HEAD/clean main, exact patch/lock identities and 1,093 installed file comparisons. |
+| 2 | Maintainable dependency decision | MET | Alternatives/cost table, three reproducible pinned patches, frozen installation and preserved existing modifications. |
+| 3 | Search as a formal message capability | MET | Declared discriminated phases/events/citations, explicit validation, nameless/error results and consumer/frame tests; full consuming TypeScript checks pass. |
+| 4 | Estimation agrees with replay | MET | Shared projection; request/output/main/native budgets; valid/zero/stale usage, growth/CJK, no duplicate usage count, original content regressions; installed tests pass. |
+| 5 | Correct system reconstruction | MET | Stable unchanged prefix, actual instruction/tool changes invalidate usage, sections/tool deltas retained, restore/compaction runtime tests and changed-prefix artifact pass. |
+| 6 | History and request compatibility | MET | Nameless legacy replay without migration, real disk/process restore, Responses/Azure/Anthropic request contracts, no internal fields in payloads, preserved model/opt-in policy. |
+| 7 | Correct errors and retry | MET | Three local phases terminal with safe provenance and no invalid model request; stale 429, transient HTTP/TypeError retry, main/subagent cancellation and both RPC halves covered. |
+| 8 | Complete user paths | MET | Baseline Read/Task/changed-prefix red; final fresh sidecar next-prompt/Read/Task+TaskWait/changed-prefix/restore green using real internal request preparation. |
+| 9 | Built artifact qualification | MET | 916 runtime, 464 shared-source, 38 Host and 20 desktop contract tests; 11-package JS build, 10-package typecheck, applicable lint and fresh 7-case sidecar pass. |
+| 10 | Review and documentation | MET | Independent full partitioned review, substantive findings resolved, EN/ZH specs/ADR/release note and this command/hash/manifest report synchronized. |
+
+## Remaining limits and process disclosure
+
+- Offline synthetic qualification only. No installed desktop UI, real search/provider service, billing behavior, or Rust build was tested or claimed.
+- Estimates are heuristics, not exact billing. No-target cut-point/manual-harness callers remain conservative instead of inventing model identity; prefix/tail retention algorithms are unchanged.
+- Non-finite/missing timestamps and unsupported message roles now fail explicitly. This does not migrate or delete old data. Legitimate nameless search records are supported; corrupt metadata is not silently repaired.
+- The patch covers Desktop's library imports (`native-pi-session.ts` uses `createAgentSession` from the main package entry). The dependency's separately prebundled standalone pi CLI/RPC entry and upstream source maps are not rebuilt/qualified here; existing source-map limitations remain.
+- The existing frame protocol saves the final full message separately. It is not extended to preserve `hostedSearchCitations` in every interrupted partial-frame reconstruction; normal full-message persistence and hosted-search content snapshots are covered. Existing unrelated tool-frame delta differences were not rewritten.
+- **Process deviation:** the harness fixer reported prohibited `rm -rf` use targeting two not-yet-existing scratch negative-fixture paths. It reported no existing files deleted and no access to main/user data by that command. This violated the no-`rm` instruction despite the empty targets; it was disclosed immediately and is not represented as compliant. No further such deletion was used.
+
+## PR preparation follow-up
+
+The user subsequently authorized committing, pushing and creating a PR. The
+45-file implementation candidate remains production-code-identical to the
+qualified bundle. PR preparation updates this report and adds one metadata
+file, `.gitattributes` (46 final changed files).
+
+Staging the previously untracked pi-coding-agent patch exposed a Git whitespace
+warning that the earlier unstaged `git diff --check` did not inspect: a blank
+unified-diff context line is encoded as one significant space. The generated
+patch is not hand-edited. `patches/*.patch whitespace=-blank-at-eol` disables
+only that format-inapplicable diagnostic for patch artifacts; other whitespace
+diagnostics and all source-file checks remain enabled. Patch bytes in the
+index equal their working-tree bytes and locked hashes. The PR preparation
+runs `git diff --cached --check` and frozen installation with this rule.
+
+The refreshed remote base is unchanged. Runtime (916), shared source (464) and
+Host-runtime (38) tests were rerun successfully before committing. The PR's
+commit metadata records the final revision; earlier artifact evidence remains
+explicitly tied to the uncommitted implementation candidate.
+
+## Changed-file manifest (46 files)
+
+All paths below are relative to the isolated task worktree. Generated builds, installed dependencies and scratch evidence are excluded.
+
+```text
+.gitattributes
+docs/adr/0297-provider-hosted-web-search-adapter-capability.md
+docs/project/hosted-search-contract-verification.md
+docs/project/unreleased.md
+docs/spec/03-runtime/08-error-codes.md
+docs/spec/03-runtime/11-provider-model-system.md
+docs/spec/06-delivery/04-e2e-test-plan.md
+docs/zh-CN/spec/03-runtime/08-error-codes.md
+docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+package.json
+packages/agent-runtime/src/agent-errors.test.ts
+packages/agent-runtime/src/agent-errors.ts
+packages/agent-runtime/src/context-budget.test.ts
+packages/agent-runtime/src/context-budget.ts
+packages/agent-runtime/src/hosted-search-compaction.test.ts
+packages/agent-runtime/src/hosted-search-consumers.test.ts
+packages/agent-runtime/src/hosted-search-error-results.test.ts
+packages/agent-runtime/src/hosted-search-estimation.test.ts
+packages/agent-runtime/src/hosted-search-replay.test.ts
+packages/agent-runtime/src/hosted-search-replay.ts
+packages/agent-runtime/src/local-request-errors.ts
+packages/agent-runtime/src/output-cap.test.ts
+packages/agent-runtime/src/output-cap.ts
+packages/agent-runtime/src/provider-retry.test.ts
+packages/agent-runtime/src/provider-retry.ts
+packages/agent-runtime/src/reasoning-replay.ts
+packages/agent-runtime/src/runtime.test.ts
+packages/agent-runtime/src/runtime.ts
+packages/agent-runtime/src/sidecar.ts
+packages/agent-runtime/src/subagent-context.test.ts
+packages/agent-runtime/src/subagent-context.ts
+packages/agent-runtime/src/subagent.test.ts
+packages/agent-runtime/src/subagent.ts
+packages/agent-runtime/src/system-transcript.test.ts
+packages/agent-runtime/src/system-transcript.ts
+packages/host-runtime/src/sidecar-local-error.test.ts
+pnpm-lock.yaml
+pnpm-workspace.yaml
+scripts/e2e-hosted-search.mjs
+scripts/e2e/hosted-search-provider.mjs
+scripts/e2e/hosted-search-scenarios.mjs
+scripts/e2e/hosted-search-sidecar.mjs
+```
diff --git a/docs/project/unreleased.md b/docs/project/unreleased.md
index bc12e7a45..fe76a1452 100644
--- a/docs/project/unreleased.md
+++ b/docs/project/unreleased.md
@@ -1,5 +1,10 @@
# Unreleased changes
+- Hosted web search now has a complete replay and estimation contract, including
+ tool/Task continuation and restart recovery. Context rebuilding preserves
+ system-prefix semantics, and structured local preparation failures no longer
+ masquerade as retryable provider failures. Existing search histories need no migration.
+
- The Composer reasoning slider now moves smoothly to clicked or
keyboard-selected levels, follows dragging immediately, and respects
reduced-motion settings. Rapid clicks redirect the animation; failed saves
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 4468fd325..ccde15c80 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -387,6 +387,22 @@ execution interrupted by abort or host recovery. `PLAN_KIND_MISMATCH` is a
terminating tool error like `PLAN_NOT_ACTIVE`: the submit tool ran against the
wrong contract, so no artifact is written and no approval row is created.
+### Local request preparation failures
+
+A structured `LOCAL_REQUEST_ERROR` from context validation, context estimation,
+or request preparation maps to the existing `INTERNAL` code with
+`retriable: false`. Preserve its local origin and phase before adapter errors
+are flattened to text. Diagnostics may retain the cause type, but must not
+copy request content, search results, credentials or arbitrary cause messages
+into the UI. Do not identify these failures by matching an exception sentence
+or by treating all JavaScript `TypeError`s alike: fetch transport failures
+retain the existing network/retry and cancellation behavior.
+
+Restored-history validation may fail before a runtime stream exists. In that case
+the existing RPC error `data` carries `errorCode`, `retriable: false`, and safe
+`details` (`origin`, `phase`, optional cause type). No provider request is made;
+the sidecar stays available and the stored record is not rewritten or skipped.
+
## 5. UI handling guidelines
| class | UI behavior |
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index 4754f1180..efc7922ce 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -237,7 +237,9 @@ PI-Desktop must not permanently restrict users to a short fixed model list.
when the provider's API style is neither of those two. Gateways that do
not support the tool surface the provider error; the remedy is unchecking.
Search runs on the provider: there is no local fetch and no permission
- prompt. Compaction still drops search blocks.
+ prompt. Compaction keeps its existing prefix/tail retention strategy. The
+ summary request includes search replay data from the compacted prefix; the
+ generated text summary is not a lossless copy of raw provider search blocks.
11. `ModelInfo` is the published record the settings surface compares against,
so a stored binding must not shape its capabilities or reasoning fields.
Effective limits, reasoning and thinking levels are resolved through the
@@ -259,6 +261,28 @@ Catalog and custom model entry must support common capability classes:
- tool-calling capable models
- JSON/structured output capable models (where provider supports)
+### Hosted-search message and budget contract
+
+- Search content and progress events are declared adapter types, not disguised
+ client tool calls. A search result or Responses search item does not require
+ `name` or `arguments`. Existing replay records remain compatible.
+- Replay and token estimation share the search-phase interpretation. Valid
+ usage covers its prefix once; zero or invalidated usage triggers a complete
+ estimate which includes search replay data. Display rounds and streaming
+ scratch must not duplicate that data. Estimates are not billing guarantees.
+ This applies to main-agent and native pi-session compaction as well as output
+ budgets. When a target model is known, estimates follow that adapter's existing
+ model-switch replay boundary. Compaction serialization includes search replay
+ projections in the summary request, without treating them as client tool calls.
+ The compacted prefix becomes a generated text summary; raw search in the
+ retained tail follows the existing replay policy. No lossless summary is promised.
+- Rebuilding an unchanged context must preserve system-prefix semantics.
+ Actual instruction or tool-declaration changes remain visible to usage
+ validation. System sections and tool additions/removals cannot be discarded.
+- Search followed by a local tool, Task, a new user prompt, or restart recovery
+ must exercise the same contract. Dependency upgrades must run the offline
+ adapter and bundled-sidecar continuation regressions, not only UI tests.
+
## 7. Configuration schema
```ts
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 633af017f..94ae0d176 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -14393,3 +14393,35 @@ the latest destination. These assertions measure work counts, not device FPS.
`fork_preserves_referenced_pasted_files_independently` and `sessions::fork_files`
cover ownership, deletion, repeated/bounded forks, retained checkpoint paths,
expired inputs, rollback, and symlink rejection.
+
+## Hosted-search continuation contract (offline sidecar)
+
+**Scope:** ADR 0297; provider-hosted search content, estimation, local tools,
+Task delegation, and saved-history recovery. No real model or search service.
+
+**Entry:** `pnpm test:e2e:hosted-search`, which rebuilds the shared
+package and `@pi-desktop/agent-runtime` sidecar bundle. The test starts that
+bundle over its ordinary stdio RPC interface, with an isolated data root,
+a synthetic Host and a loopback-only Responses endpoint. Source-only mocks
+or an already installed desktop application do not satisfy this test.
+
+| Case | Required observation |
+| --- | --- |
+| Search then new user prompt | Valid search item is replayed and the second turn completes. |
+| Search then ordinary local tool | A real tool round completes and the next provider request is prepared without type/estimation failure. |
+| Search then Task | Actual delegation orchestration runs against a synthetic provider; parent continuation finishes without repeated local errors. |
+| Saved search history restored | A fresh runtime preserves search replay without adding fake tool fields or rewriting the original record. |
+| Usage invalidated by a real prefix change | The isolated sidecar changes instructions during a real Read round; the prior nonzero usage no longer covers that prefix, and continuation succeeds. |
+| Invalid saved replay container | Restore returns safe INTERNAL/context-validation, sends no provider request or persistence Host RPC, and keeps the process healthy. In-memory immutability is checked by the replay unit tests. |
+| Unknown saved search phase | The same explicit rejection is observed without silently discarding the search record. |
+
+**Companion gates:** Responses/Azure/Anthropic adapter contracts; typed search
+phases; zero/valid/stale usage; changed/unchanged system prefix and tool ledger;
+search content growth and CJK output budgets; structured local preparation
+failures without retry/fetch, ordinary transport retry and cancellation. Dependency upgrades must run
+these gates against the locked dependency version and record the tested bundle.
+
+**Evidence:** record build and test exit codes, baseline SHA, dependency versions,
+artifact identity and independent review in
+`docs/project/hosted-search-contract-verification.md`. Never record private
+conversation content or credentials. A skipped test remains NOT RUN, not PASS.
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 204b27dec..08eae182d 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -433,3 +433,14 @@ transcript 保留稳定错误码、传输 errno 和原始 details,但使用本
而不是通用连接错误摘要。它会提示用户检查证书、系统时间以及安全软件或代理使用的
信任根,并在修改信任设置后重启。文案不会断言一定是流量拦截,也不会提供关闭 TLS
校验的绕过方式。修复原因后,用户仍可手动继续。
+
+## 本地请求准备错误
+
+上下文校验、估算或请求准备阶段产生的结构化 `LOCAL_REQUEST_ERROR`,映射为既有
+`INTERNAL` 且 `retriable: false`。在适配器把异常压成文字前保留本地来源与阶段;
+诊断可以保留原因类型,不向界面复制请求正文、搜索结果、凭据或任意底层异常文字。
+不能靠匹配异常句子或统一禁用所有 `TypeError` 重试来分类;网络故障和取消维持原有策略。
+
+历史恢复校验可能在运行时流创建前失败。此时使用既有 RPC 错误 `data`,携带
+`errorCode`、`retriable: false` 及安全的 `details`(来源、阶段、可选原因类型)。
+不得发出模型请求;sidecar 保持可用,不改写或跳过损坏历史。
diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
index 4278942ee..145f156b1 100644
--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md
@@ -210,7 +210,8 @@ PI-Desktop 不得把用户永久限制在一份简短的固定模型列表上。
用于 convertMessages),并在后续回合——包括重启之后——回放这些原始
搜索块(ADR 0297)。提供商接口风格不属于这两种时复选框禁用。不支持
该工具的网关会把提供商错误暴露出来;处理方式是取消勾选。搜索在提供商
- 侧执行:没有本地抓取,也没有权限询问。压缩仍会丢掉搜索块。
+ 侧执行:没有本地抓取,也没有权限询问。压缩保持既有的前缀/尾部保留策略;
+ 摘要请求包含被压缩前缀中的搜索回放数据,但生成的文本摘要不是原始搜索块的无损副本。
11. `ModelInfo` 是设置界面用来对照的已发布记录,因此已存储的 binding 不得
塑造它的能力或推理字段。有效上限、推理与思考级别都通过那个确切的 binding
解析;有效的传输模态数组还会额外套用显式的附件覆盖。
@@ -646,3 +647,20 @@ OpenAI Responses 适配器必须把 `response.completed`(以及
- 自动发现每个供应商门户的付费计划
- 不支持 pi-ai 的专有非 HTTP SDK
- 云同步的提供商配置文件
+
+## 托管搜索消息与预算契约
+
+- 搜索内容和进度事件必须拥有正式适配器类型,不能伪装成客户端工具调用。
+ 搜索结果和 Responses 搜索项不要求 `name` 或 `arguments`;既有回放记录保持兼容。
+- 回放与 token 估算共享搜索阶段的解释规则。有效 usage 只覆盖其前缀一次;
+ usage 为零或失效时,全量估算必须包含搜索回放数据,不重复计算展示轮次和流式临时字段。
+ 估算不是服务端计费保证。
+- 相同上下文重建保留系统前缀语义;真实指令或工具声明变化仍影响 usage 有效性。
+ 系统分段、工具增加和移除不能在重建时丢弃。
+- 搜索后本地工具续跑、Task、普通续聊和重启恢复均须验证;依赖升级必须运行
+ 离线适配器与打包 sidecar 回归,不能只验证界面。
+
+同一搜索投影适用于主代理与原生 pi 会话的上下文/压缩估算及输出预算。
+已知目标模型时,估算遵守该适配器既有的模型切换回放边界。压缩序列化把搜索投影传入摘要请求,
+不伪装成客户端工具调用。被压缩前缀转为生成的文本摘要;保留尾部中的原始搜索仍按既有规则回放,
+不承诺摘要无损保留原始搜索块。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 75ac12b71..b112f80c0 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -8550,3 +8550,27 @@ the latest destination. These assertions measure work counts, not device FPS.
`fork_preserves_referenced_pasted_files_independently` 和 `sessions::fork_files`
覆盖附件归属、删除、重复与截断分支、保留的压缩检查点引用、过期输入、失败回滚
及符号链接拒绝。
+
+## 原生搜索续跑契约(离线 sidecar)
+
+**范围:** ADR 0297;供应商原生搜索内容、估算、本地工具、Task 委派及历史恢复。不调用真实模型或搜索服务。
+
+**入口:** `pnpm test:e2e:hosted-search` 自行重建 shared 与 agent-runtime sidecar。
+通过普通 stdio RPC 驱动该产物,使用隔离数据目录、合成 Host 与仅回环地址的 Responses 服务。
+只测源码或使用已有桌面安装包不满足本测试。
+
+| 场景 | 必须观察到的结果 |
+| --- | --- |
+| 搜索后新用户消息 | 合法搜索项被回放,第二轮正常结束。 |
+| 搜索后普通本地工具 | 真实工具轮完成,下一模型请求准备无类型或估算错误。 |
+| 搜索后 Task | 实际委派流程使用合成模型,父代理继续且不重复报告本地错误。 |
+| 保存搜索历史后恢复 | 新运行时保留搜索回放,不添加假工具字段或改写原记录。 |
+| 真实前缀变化使 usage 失效 | 隔离 sidecar 在真实 Read 轮中更新指令;此前非零 usage 不再覆盖该前缀,续跑正常结束。 |
+| 非法历史回放容器 | 恢复返回安全的 INTERNAL/context-validation;不发送模型请求或持久化 Host RPC,进程仍健康。内存中输入不变性由回放单元测试验证。 |
+| 未知历史搜索阶段 | 明确拒绝该记录,而不是静默丢弃搜索内容;其余断言同上。 |
+
+**配套检查:** Responses/Azure/Anthropic 请求契约、搜索阶段类型、有效/零/失效 usage、
+真实与无变化的系统前缀及工具增删、搜索数据增长、中文输出预算;结构化本地准备失败不重试、不 fetch,普通传输重试与取消保持正确。依赖升级必须对锁定版本运行这些检查,记录测试的 bundle。
+
+**证据:** 记录构建和测试退出码、基线 SHA、依赖版本、产物标识及独立评审,报告位于
+`docs/project/hosted-search-contract-verification.md`。不得记录真实会话或凭据。未执行明确标为 NOT RUN,不得标为 PASS。
diff --git a/package.json b/package.json
index 5ce9ea21b..84fd27edf 100644
--- a/package.json
+++ b/package.json
@@ -35,6 +35,7 @@
"test:e2e:provider-order": "node scripts/e2e-provider-order.mjs",
"test:e2e:project-edit": "node scripts/e2e-project-edit.mjs",
"test:e2e:provider-api-style": "node scripts/e2e-provider-api-style.mjs",
+ "test:e2e:hosted-search": "node scripts/e2e-hosted-search.mjs",
"test:e2e:oauth-retry": "node --test apps/desktop/test/anthropic-oauth-retry.test.mjs",
"test:e2e:boot": "node scripts/e2e-electron-boot.mjs",
"test:e2e:layout": "node scripts/e2e-three-column-layout.mjs",
diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.ts
index 9118f0e72..9d3db7808 100644
--- a/packages/agent-runtime/src/agent-errors.test.ts
+++ b/packages/agent-runtime/src/agent-errors.test.ts
@@ -5,6 +5,186 @@ import {
} from "./agent-errors.js";
describe("classifyAgentError", () => {
+ it.each(["context-validation", "context-estimation", "request-preparation"])(
+ "keeps explicitly local %s failures terminal, safe and diagnosable", (phase) => {
+ const cause = new TypeError("private prompt api_key=test-secret\nprivate stack");
+ const error = Object.assign(new Error("502: fetch failed; prompt is too long", { cause }), {
+ code: "LOCAL_REQUEST_ERROR", phase,
+ });
+ const classified = classifyAgentError(error);
+ expect(classified).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase, causeName: "TypeError" },
+ });
+ expect(classified).toHaveProperty("cause", error);
+ expect(error.cause).toBe(cause);
+ expect(Object.keys(classified)).not.toContain("cause");
+ const serialized = JSON.stringify(classified);
+ for (const text of ["private prompt", "test-secret", "private stack", "502", "fetch failed"]) {
+ expect(serialized).not.toContain(text);
+ }
+ },
+ );
+
+ it.each(["fetch failed", "429: overloaded", "503: unavailable", "aborted field", "prompt is too long"])(
+ "classifies local message metadata before provider wording: %s", (errorMessage) => {
+ expect(classifyAgentError({
+ role: "assistant", stopReason: "error", errorMessage,
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR", phase: "context-estimation",
+ message: "private prompt", causeName: "TypeError", stack: "private stack",
+ },
+ })).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
+ });
+ },
+ );
+
+ it("requires the complete local marker, never error names or wording", () => {
+ for (const error of [
+ new TypeError("fetch failed"),
+ "LOCAL_REQUEST_ERROR context-validation fetch failed",
+ Object.assign(new Error("fetch failed"), { name: "LocalRequestError" }),
+ { errorMessage: "fetch failed", errorDetails: { code: "LOCAL_REQUEST_ERROR", phase: "remote" } },
+ { errorMessage: "fetch failed", errorDetails: { phase: "context-validation", message: "failed" } },
+ { errorMessage: "fetch failed", errorDetails: { code: "local_request_error", phase: "context-validation" } },
+ ]) {
+ expect(classifyAgentError(error)).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
+ }
+ });
+
+ it("takes pi-ai's code+phase marker as provenance even without a message", () => {
+ // Upstream's own reader accepts `code` plus a known `phase`; details that lost
+ // their message in transit are still explicit provenance and must not fall
+ // through to the transport bucket, which would be retried.
+ for (const errorDetails of [
+ { code: "LOCAL_REQUEST_ERROR", phase: "context-validation" },
+ { code: "LOCAL_REQUEST_ERROR", phase: "request-preparation", causeName: "TypeError" },
+ ]) {
+ const classified = classifyAgentError({
+ role: "assistant", stopReason: "error", errorMessage: "fetch failed", errorDetails,
+ });
+ expect(classified).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: errorDetails.phase },
+ });
+ expect(classified.message).toMatch(/^Local request .* failed\.$/);
+ expect(JSON.stringify(classified)).not.toContain("fetch failed");
+ }
+ // The marker is the whole contract: a message alone is not provenance.
+ expect(classifyAgentError({
+ errorMessage: "fetch failed",
+ errorDetails: { code: "LOCAL_REQUEST_ERROR", phase: "network", message: "fetch failed" },
+ })).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
+ });
+
+ it("does not expose an arbitrary cause name from local metadata", () => {
+ const classified = classifyAgentError({
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ message: "private prompt", causeName: "api_key=test-secret\nprivate stack",
+ },
+ });
+ expect(classified.details).toEqual({ origin: "local", phase: "request-preparation" });
+ expect(JSON.stringify(classified)).not.toMatch(/private|test-secret|stack/);
+ });
+
+ it("keeps explicit cancellation ahead of local metadata", () => {
+ const errorDetails = { code: "LOCAL_REQUEST_ERROR", phase: "context-validation", message: "failed" };
+ expect(classifyAgentError({ stopReason: "aborted", errorDetails })).toMatchObject({
+ code: "TURN_ABORTED", retriable: false,
+ });
+ expect(classifyAgentError(Object.assign(new Error("Request aborted"), {
+ name: "AbortError", ...errorDetails,
+ }))).toMatchObject({ code: "TURN_ABORTED", retriable: false });
+ });
+
+ it("keeps a cancelled local cause cancelled however the outer error is named", () => {
+ // pi-ai wraps a synchronous AbortError in LocalRequestError before
+ // `signal.aborted` flips, so the outer name is not "AbortError": the cause
+ // name the marker preserved is the only evidence of the user's Stop.
+ const cause = Object.assign(new Error("The operation was aborted"), {
+ name: "AbortError",
+ });
+ const wrapped = Object.assign(new Error("Local request preparation failed."), {
+ name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
+ phase: "request-preparation", cause,
+ });
+ const classified = classifyAgentError(wrapped);
+ expect(classified).toMatchObject({ code: "TURN_ABORTED", retriable: false });
+ expect(classified.message).toBe("Request aborted");
+ // A cancelled turn is not reported as a local request failure.
+ expect(classified.details?.origin).toBeUndefined();
+ expect(classified.details?.phase).toBeUndefined();
+
+ // The same cancellation on the wire shape the adapters emit.
+ expect(classifyAgentError({
+ role: "assistant", stopReason: "error",
+ errorMessage: "Local request preparation failed",
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ message: "Local request preparation failed", causeName: "AbortError",
+ },
+ })).toMatchObject({ code: "TURN_ABORTED", retriable: false });
+
+ // A wrapped, non-abort local failure stays a terminal local failure.
+ expect(classifyAgentError(Object.assign(new Error("wrapped setup failure"), {
+ name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
+ phase: "request-preparation", cause: new TypeError("private prompt"),
+ }))).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "request-preparation", causeName: "TypeError" },
+ });
+ });
+
+ it("reads the marker through a bounded, cycle-safe cause chain", () => {
+ const marker = Object.assign(new Error("Local request context estimation failed."), {
+ name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
+ phase: "context-estimation", cause: new TypeError("private prompt"),
+ });
+ expect(classifyAgentError(Object.assign(new TypeError("fetch failed"), {
+ cause: marker,
+ }))).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
+ });
+
+ // A cycle without the marker stays a transport failure, and it has to
+ // terminate instead of being walked forever.
+ const first = new TypeError("fetch failed");
+ const second = Object.assign(new Error("socket hang up"), { cause: first });
+ (first as any).cause = second;
+ expect(classifyAgentError(first)).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
+
+ // The same cycle with the marker on the second node is explicit provenance.
+ Object.assign(second, { code: "LOCAL_REQUEST_ERROR", phase: "request-preparation" });
+ expect(classifyAgentError(first)).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "request-preparation" },
+ });
+
+ // A self-referencing marker terminates as well.
+ const self = Object.assign(new Error("Local request preparation failed."), {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ });
+ (self as any).cause = self;
+ expect(classifyAgentError(self)).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "request-preparation" },
+ });
+
+ // Past the traversal bound the marker is out of reach, so the failure keeps
+ // its transport classification rather than claiming local provenance.
+ let deep: unknown = Object.assign(new Error("Local request preparation failed."), {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ });
+ for (let depth = 0; depth < 6; depth += 1) {
+ deep = Object.assign(new TypeError("fetch failed"), { cause: deep });
+ }
+ expect(classifyAgentError(deep)).toMatchObject({ code: "NETWORK_ERROR", retriable: true });
+ });
+
it.each([
"SELF_SIGNED_CERT_IN_CHAIN",
"DEPTH_ZERO_SELF_SIGNED_CERT",
diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.ts
index d833a5450..f85aa7fee 100644
--- a/packages/agent-runtime/src/agent-errors.ts
+++ b/packages/agent-runtime/src/agent-errors.ts
@@ -9,6 +9,7 @@
*/
import { isCertificateVerificationError } from "@pi-desktop/shared";
+import { readLocalRequestErrorDetails } from "./local-request-errors.js";
export type ClassifiedAgentError = {
code: string;
@@ -16,6 +17,8 @@ export type ClassifiedAgentError = {
retriable: boolean;
/** Safe, low-cardinality diagnostics for logs and the error details panel. */
details?: Record<string, unknown>;
+ /** Local-only original failure; non-enumerable so UI/JSON never receives it. */
+ cause?: unknown;
};
/** Keep envelopes/persisted rows small; provider bodies can be huge. */
@@ -342,13 +345,45 @@ export function networkFailureDiagnostics(
}
export function classifyAgentError(err: unknown): ClassifiedAgentError {
+ const envelope = err !== null && typeof err === "object"
+ ? err as Record<string, unknown> : undefined;
+ const local = readLocalRequestErrorDetails(err);
+ // Cancellation outranks local diagnostics: pi-ai wraps a synchronous AbortError
+ // that fired before `signal.aborted` flipped in a LocalRequestError, whose own
+ // name says nothing about it, so the marker's preserved cause name is the only
+ // trace of the user's Stop — the same field the runtime reads off a settled
+ // message.
+ const explicitlyAborted =
+ (err instanceof Error && err.name === "AbortError") ||
+ envelope?.stopReason === "aborted" ||
+ local?.causeName === "AbortError";
+ if (local && !explicitlyAborted) {
+ // Local preparation cannot be repaired by provider retries. Keep the
+ // original chain in-process, but never copy its payload/message/stack to UI.
+ const classified: ClassifiedAgentError = {
+ code: "INTERNAL",
+ message: local.message,
+ retriable: false,
+ details: {
+ origin: "local",
+ phase: local.phase,
+ ...(local.causeName ? { causeName: local.causeName } : {}),
+ },
+ };
+ return Object.defineProperty(classified, "cause", { value: err });
+ }
const rawMessage =
typeof err === "string"
? err
: err instanceof Error
? err.message
- : String(err);
- const safeMessage = redactSensitiveErrorText(rawMessage);
+ : typeof envelope?.errorMessage === "string"
+ ? envelope.errorMessage
+ : envelope?.role === "assistant"
+ ? "provider stream failed"
+ : String(err);
+ const safeMessage = local && explicitlyAborted
+ ? "Request aborted" : redactSensitiveErrorText(rawMessage);
const message =
safeMessage.length > MAX_ERROR_MESSAGE_CHARS
? `${safeMessage.slice(0, MAX_ERROR_MESSAGE_CHARS)}…`
@@ -387,7 +422,7 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {
// while a checkpoint is being summarized fails the compaction with an abort
// cause, and that turn must read as stopped, not as a compaction failure.
if (
- (err instanceof Error && err.name === "AbortError") ||
+ explicitlyAborted ||
/\babort/i.test(rawMessage)
) {
return result("TURN_ABORTED", false);
diff --git a/packages/agent-runtime/src/context-budget.test.ts b/packages/agent-runtime/src/context-budget.test.ts
index 582cc47d8..7d6c4828c 100644
--- a/packages/agent-runtime/src/context-budget.test.ts
+++ b/packages/agent-runtime/src/context-budget.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import type { AssistantMessage, Model } from "@earendil-works/pi-ai";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
COMPACTION_MAX_KEEP_RECENT_TOKENS,
@@ -130,3 +131,88 @@ describe("retainedUserMessageBudget", () => {
expect(retainedUserMessageBudget({ hardLimit: 1 })).toBe(1);
});
});
+
+describe("hosted search target model threading", () => {
+ /** A Responses model carrying the identity an adapter stamps. */
+ const model = (id: string): Model<"openai-responses"> => ({
+ id,
+ name: "test",
+ api: "openai-responses",
+ provider: "openai",
+ baseUrl: "http://localhost",
+ reasoning: false,
+ input: ["text"],
+ contextWindow: 200_000,
+ maxTokens: 8_192,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ });
+
+ const searchHistory = (modelId: string, size: number): AssistantMessage => ({
+ role: "assistant",
+ api: "openai-responses",
+ provider: "openai",
+ model: modelId,
+ content: [
+ {
+ type: "hostedSearch",
+ phase: "web_search_call",
+ blockId: "search_fixture",
+ wire: {
+ type: "web_search_call",
+ id: "search_fixture",
+ status: "completed",
+ action: { type: "search", query: "a".repeat(size) },
+ },
+ },
+ ],
+ timestamp: 1,
+ stopReason: "stop",
+ usage: {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ });
+
+ it("charges the search history the target model replays", () => {
+ const target = model("gpt-test");
+ const small = contextBudgetFor(target, [searchHistory("gpt-test", 100)]).tokens;
+ const large = contextBudgetFor(target, [searchHistory("gpt-test", 10_100)])
+ .tokens;
+ expect(small).toBeGreaterThan(0);
+ expect(large - small).toBe(2_500);
+ });
+
+ it("charges nothing for search the target model cannot replay", () => {
+ // The Responses adapter replays `web_search_call` items only for the model
+ // that produced them: the request carries nothing for another id, so the
+ // budget must not count it either.
+ expect(
+ contextBudgetFor(model("gpt-test"), [searchHistory("other-model", 10_000)])
+ .tokens,
+ ).toBe(0);
+ });
+
+ it("stays conservative when the caller has partial model facts", () => {
+ // Window facts alone say nothing about which items the provider replays;
+ // charging them keeps the hard limit safe.
+ const tokens = contextBudgetFor(
+ { contextWindow: 200_000, maxTokens: 8_192 },
+ [searchHistory("other-model", 10_000)],
+ ).tokens;
+ expect(tokens).toBeGreaterThan(2_000);
+ });
+
+ it("derives the same thresholds from a full model as from its window facts", () => {
+ const full = model("gpt-test");
+ expect(contextBudgetLimitsFor(full)).toEqual(
+ contextBudgetLimitsFor({
+ contextWindow: full.contextWindow,
+ maxTokens: full.maxTokens,
+ }),
+ );
+ });
+});
diff --git a/packages/agent-runtime/src/context-budget.ts b/packages/agent-runtime/src/context-budget.ts
index a6703a08f..57f6291c9 100644
--- a/packages/agent-runtime/src/context-budget.ts
+++ b/packages/agent-runtime/src/context-budget.ts
@@ -7,10 +7,12 @@
* formula from here instead of each owning a copy that can drift.
*
* Deliberately dependency-light — token estimation is delegated to
- * pi-agent-core and nothing else is imported, so this module stays usable from
- * any runtime context and can never form a cycle with `runtime.ts`.
+ * 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`.
*/
+import type { Api, Model } from "@earendil-works/pi-ai";
import {
estimateContextTokens,
type AgentMessage,
@@ -70,6 +72,13 @@ export type ContextBudgetModel = {
maxTokens?: number;
};
+/**
+ * Estimation input. A full pi-ai `Model` additionally carries the replay
+ * identity (`api`/`provider`/`id`) that hosted-search token estimation needs,
+ * which is why it is named on its own next to the partial window facts above.
+ */
+export type ContextBudgetModelInput = ContextBudgetModel | Model<Api>;
+
/** Thresholds only, for callers that already know their own token count. */
export type ContextBudgetLimits = Omit<ContextBudget, "tokens">;
@@ -117,13 +126,32 @@ export function contextBudgetLimitsFor(
return { hardLimit, requestHeadroom, keepRecentTokens };
}
+/**
+ * Token estimate of `messages` as the target model will carry them.
+ *
+ * Hosted search is model-dependent: the Responses adapter replays a
+ * `web_search_call` only for the model that produced it, so `api` is the
+ * discriminant that says whether a target model is known at all. A caller with
+ * partial model facts (a catalog entry, a caller test) has no target and keeps
+ * the conservative estimate — every search block is charged rather than
+ * assumed away.
+ */
+function estimateContextTokensFor(
+ model: ContextBudgetModelInput,
+ messages: AgentMessage[],
+): ReturnType<typeof estimateContextTokens> {
+ return "api" in model
+ ? estimateContextTokens(messages, model)
+ : estimateContextTokens(messages);
+}
+
/** Thresholds for a model window, plus the estimated size of `messages`. */
export function contextBudgetFor(
- model: ContextBudgetModel,
+ model: ContextBudgetModelInput,
messages: AgentMessage[],
): ContextBudget {
return {
- tokens: estimateContextTokens(messages).tokens,
+ tokens: estimateContextTokensFor(model, messages).tokens,
...contextBudgetLimitsFor(model),
};
}
diff --git a/packages/agent-runtime/src/hosted-search-compaction.test.ts b/packages/agent-runtime/src/hosted-search-compaction.test.ts
new file mode 100644
index 000000000..e152f5972
--- /dev/null
+++ b/packages/agent-runtime/src/hosted-search-compaction.test.ts
@@ -0,0 +1,544 @@
+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 { 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 },
+ };
+}
+
+function assistant(
+ content: AssistantMessage["content"],
+ api: Api = "anthropic-messages",
+ tokens = 0,
+ timestamp = 2,
+): AssistantMessage {
+ return {
+ role: "assistant",
+ content,
+ api,
+ provider: api === "anthropic-messages" ? "anthropic" : "openai",
+ model: "test-model",
+ timestamp,
+ stopReason: "stop",
+ usage: {
+ input: tokens,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: tokens,
+ 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: "web_search_tool_result",
+ blockId: "srv_1",
+ wire: {
+ type: "web_search_tool_result",
+ tool_use_id: "srv_1",
+ content: [{ type: "web_search_result", encrypted_content: "x".repeat(size) }],
+ },
+ },
+ ]
+ : [
+ {
+ 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) } },
+ },
+ ];
+}
+
+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);
+ }
+ }
+ });
+
+ 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);
+ }
+ });
+
+ 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("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([
+ {
+ type: "hostedSearch",
+ phase: "web_search_tool_result",
+ blockId: "srv_1",
+ 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]),
+ );
+ }
+ });
+
+ 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 },
+ ];
+ const expected =
+ "[User]: hello\n\n" +
+ "[Assistant]: hi\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);
+ }
+ });
+});
diff --git a/packages/agent-runtime/src/hosted-search-consumers.test.ts b/packages/agent-runtime/src/hosted-search-consumers.test.ts
new file mode 100644
index 000000000..b55adb3a6
--- /dev/null
+++ b/packages/agent-runtime/src/hosted-search-consumers.test.ts
@@ -0,0 +1,239 @@
+import { createRequire } from "node:module";
+import { pathToFileURL } from "node:url";
+import { describe, expect, it } from "vitest";
+import {
+ AssistantMessageFrameEncoder,
+ LocalRequestError,
+ normalizeContext,
+ reduceAssistantMessageFrames,
+} from "@earendil-works/pi-ai";
+import type {
+ AssistantMessage,
+ AssistantMessageEvent,
+ AssistantMessageFrame,
+ HostedSearchContent,
+ Message,
+ Model,
+} from "@earendil-works/pi-ai";
+import {
+ estimateContextTokens,
+ estimateMessageTokens,
+ getLastAssistantUsageInfo,
+} 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",
+ timestamp, stopReason: "stop",
+ usage: { input: tokens, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: tokens,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ };
+}
+function searches(): HostedSearchContent[] {
+ return [
+ { type: "hostedSearch", phase: "server_tool_use", blockId: "srv_1", name: "web_search", input: { query: "local query" } },
+ { type: "hostedSearch", phase: "web_search_tool_result", blockId: "srv_1", wire: { type: "web_search_tool_result", tool_use_id: "srv_1", content: [{ type: "web_search_result", encrypted_content: "opaque-result", url: "https://example.test" }] } },
+ { type: "hostedSearch", phase: "web_search_call", blockId: "ws_1", status: "in_progress", wire: { type: "web_search_call", id: "ws_1", status: "in_progress", action: { type: "search", query: "local query" } } },
+ ];
+}
+const mistral: Model<"mistral-conversations"> = {
+ id: "target-model", name: "test", api: "mistral-conversations", provider: "mistral",
+ baseUrl: "http://localhost", reasoning: false, input: ["text"], contextWindow: 100_000, maxTokens: 1000,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+};
+async function mistralRequest(content: AssistantMessage["content"]) {
+ let body: { messages: { role: string; content?: unknown; tool_calls?: unknown[] }[] } | undefined;
+ let fetches = 0;
+ const result = await streamMistral(mistral, normalizeContext({ messages: [assistant(content)] }), {
+ apiKey: "test", maxRetries: 0,
+ fetch: async (_url, init) => {
+ fetches++;
+ body = JSON.parse(String(init?.body));
+ return new Response('data: {"id":"m","choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n', { headers: { "content-type": "text/event-stream" } });
+ },
+ }).result();
+ expect(result.stopReason).toBe("stop");
+ expect(fetches).toBe(1);
+ return body!;
+}
+function encode(events: AssistantMessageEvent[]): AssistantMessageFrame[] {
+ const encoder = new AssistantMessageFrameEncoder();
+ return events.flatMap(event => {
+ const frame = encoder.encode(event);
+ return frame ? [frame] : [];
+ });
+}
+
+describe("hosted-search consumers", () => {
+ describe("Mistral model switches", () => {
+ for (const block of searches()) {
+ it(`does not turn ${block.phase} into a malformed function call`, async () => {
+ const body = await mistralRequest([block, { type: "text", text: "retained answer" }]);
+ const message = body.messages.find(item => item.role === "assistant");
+ expect(message?.content).toEqual([{ type: "text", text: "retained answer" }]);
+ expect(message).not.toHaveProperty("tool_calls");
+ expect(JSON.stringify(body)).not.toContain("opaque-result");
+ });
+ }
+ it("omits search-only history while preserving ordinary function calls", async () => {
+ const searchOnly = await mistralRequest(searches());
+ expect(searchOnly.messages).toEqual([]);
+ const mixed = await mistralRequest([
+ ...searches(),
+ { type: "thinking", thinking: "retained reasoning" },
+ { type: "toolCall", id: "tool_1", name: "read", arguments: { path: "file" } },
+ ]);
+ const message = mixed.messages.find(item => item.role === "assistant");
+ expect(message?.tool_calls).toEqual([
+ expect.objectContaining({ id: expect.any(String), type: "function", function: { name: "read", arguments: '{"path":"file"}' } }),
+ ]);
+ expect(JSON.stringify(message?.content)).toContain("retained reasoning");
+ expect(mixed.messages.filter(item => item.role === "tool")).toHaveLength(1);
+ });
+ });
+
+ describe("in-process assistant frames", () => {
+ for (const block of searches()) {
+ it(`round-trips ${block.phase} and the following text index`, () => {
+ const output = assistant([block, { type: "text", text: "answer" }]);
+ const frames = encode([
+ { type: "start", partial: output },
+ { type: "hosted_search_update", contentIndex: 0, partial: output },
+ { type: "text_start", contentIndex: 1, partial: output },
+ { type: "text_end", contentIndex: 1, content: "answer", partial: output },
+ ]);
+ 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", () => {
+ const block = searches()[2]!;
+ const output = assistant([block]);
+ const encoder = new AssistantMessageFrameEncoder();
+ const start = encoder.encode({ type: "start", partial: output })!;
+ const first = encoder.encode({ type: "hosted_search_update", contentIndex: 0, partial: output })!;
+ expect(first).toBeDefined();
+ if (block.phase !== "web_search_call") throw new Error("unexpected fixture");
+ block.status = "completed";
+ block.wire!.status = "completed";
+ (block.wire!.action as { query: string }).query = "updated query";
+ const last = encoder.encode({ type: "hosted_search_update", contentIndex: 0, partial: output })!;
+ expect(reduceAssistantMessageFrames([start, first])?.content[0]).toMatchObject({ status: "in_progress", wire: { action: { query: "local query" } } });
+ const frames = [start, first, last, last];
+ const reduced = reduceAssistantMessageFrames(frames)!;
+ expect(reduced.content).toEqual([block]);
+ (reduced.content[0] as typeof block).wire!.status = "mutated";
+ expect(reduceAssistantMessageFrames(frames)?.content).toEqual([block]);
+ });
+ it("preserves multiple search rounds, pair IDs, and ordinary block deltas", () => {
+ const output = assistant([...searches(), { type: "text", text: "" }]);
+ const encoder = new AssistantMessageFrameEncoder();
+ const events: AssistantMessageEvent[] = [
+ { type: "start", partial: output },
+ ...[0, 1, 2].map(contentIndex => ({ type: "hosted_search_update" as const, contentIndex, partial: output })),
+ { type: "text_start", contentIndex: 3, partial: output },
+ { type: "text_delta", contentIndex: 3, delta: "answer", partial: output },
+ { type: "text_end", contentIndex: 3, content: "answer", partial: output },
+ ];
+ const frames = events.map(event => encoder.encode(event)).filter((frame): frame is AssistantMessageFrame => frame !== undefined);
+ expect(reduceAssistantMessageFrames(frames)?.content).toEqual([...searches(), { type: "text", text: "answer" }]);
+ });
+ it("rejects wrong block types, identities, and gaps instead of corrupting content", () => {
+ const output = assistant([searches()[2]!]);
+ const start = { type: "start" as const, partial: assistant([]) };
+ const frame: AssistantMessageFrame = { type: "hosted_search_update", contentIndex: 0, content: searches()[2]! };
+ expect(() => reduceAssistantMessageFrames([start, { ...frame, contentIndex: 1 } as AssistantMessageFrame])).toThrow(/gap/);
+ expect(() => reduceAssistantMessageFrames([start, { type: "text_start", contentIndex: 0, content: { type: "text", text: "safe" } }, frame])).toThrow();
+ expect(() => reduceAssistantMessageFrames([start, frame, { ...frame, content: { ...searches()[2]!, blockId: "other" } } as AssistantMessageFrame])).toThrow();
+ const encoder = new AssistantMessageFrameEncoder();
+ encoder.encode({ type: "start", partial: output });
+ encoder.encode({ type: "hosted_search_update", contentIndex: 0, partial: output });
+ output.content[0] = { ...searches()[2]!, blockId: "other" };
+ expect(() => encoder.encode({ type: "hosted_search_update", contentIndex: 0, partial: output })).toThrow();
+ output.content[0] = { type: "text", text: "safe" };
+ expect(() => encoder.encode({ type: "hosted_search_update", contentIndex: 0, partial: output })).toThrow();
+ });
+ it("does not persist parser scratch buffers or fabricate tool fields", () => {
+ const streamingBlock = { ...searches()[0]!, index: 0, inputJson: "scratch", partialJson: "scratch" };
+ const output = assistant([streamingBlock]);
+ const frames = encode([{ type: "start", partial: output }, { type: "hosted_search_update", contentIndex: 0, partial: output }]);
+ const reduced = reduceAssistantMessageFrames(frames)!;
+ expect(reduced.content[0]).toEqual(searches()[0]);
+ expect(reduced.content[0]).not.toHaveProperty("arguments");
+ });
+ it("preserves error-result wire and legacy fallback semantics", () => {
+ const blocks: HostedSearchContent[] = [
+ { type: "hostedSearch", phase: "web_search_tool_result", blockId: "s", isError: true, wire: { type: "web_search_tool_result_error", tool_use_id: "s", content: "unavailable" } },
+ { type: "hostedSearch", phase: "web_search_call", blockId: "legacy" },
+ ];
+ const output = assistant(blocks);
+ const frames = encode([
+ { type: "start", partial: output },
+ { type: "hosted_search_update", contentIndex: 0, partial: output },
+ { type: "hosted_search_update", contentIndex: 1, partial: output },
+ ]);
+ expect(reduceAssistantMessageFrames(frames)?.content).toEqual(blocks);
+ });
+ it("retains thinking and tool frame behavior after a search block", () => {
+ const search = searches()[2]!;
+ const thinking = { type: "thinking" as const, thinking: "", thinkingSignature: "sig" };
+ const toolCall = { type: "toolCall" as const, id: "tool", name: "read", arguments: {} };
+ const output = assistant([search, thinking, toolCall]);
+ const frames = encode([
+ { type: "start", partial: output },
+ { type: "hosted_search_update", contentIndex: 0, partial: output },
+ { type: "thinking_start", contentIndex: 1, partial: output },
+ { type: "thinking_delta", contentIndex: 1, delta: "reason", partial: output },
+ { type: "thinking_end", contentIndex: 1, content: "reason", partial: output },
+ { type: "toolcall_start", contentIndex: 2, partial: output },
+ { type: "toolcall_delta", contentIndex: 2, delta: '{"path":"file"}', partial: output },
+ { type: "toolcall_end", contentIndex: 2, toolCall: { ...toolCall, arguments: { path: "file" } }, partial: output },
+ ]);
+ expect(reduceAssistantMessageFrames(frames)?.content).toEqual([
+ search, { ...thinking, thinking: "reason" }, { ...toolCall, arguments: { path: "file" } },
+ ]);
+ });
+ });
+
+ describe("usage anchors", () => {
+ const response = assistant([{ type: "text", text: "answer" }], 10, 100);
+ const update: Message = { role: "system", content: "new instruction", timestamp: 20 };
+ it("invalidates usage when a newer message is inserted before the response", () => {
+ const messages = [update, response];
+ expect(getLastAssistantUsageInfo(messages)).toBeUndefined();
+ expect(estimateContextTokens(messages)).toMatchObject({ lastUsageIndex: null, tokens: estimateMessageTokens(update) + estimateMessageTokens(response) });
+ });
+ it("keeps usage when the system update is trailing, then counts that update once", () => {
+ expect(estimateContextTokens([response, update])).toEqual({ lastUsageIndex: 0, usageTokens: 100, trailingTokens: estimateMessageTokens(update), tokens: 100 + estimateMessageTokens(update) });
+ });
+ it("keeps an earlier valid anchor when the later response predates an inserted update", () => {
+ const later = assistant(searches(), 15, 300);
+ expect(getLastAssistantUsageInfo([response, update, later])?.index).toBe(0);
+ expect(estimateContextTokens([response, update, later]).tokens).toBe(100 + estimateMessageTokens(update) + estimateMessageTokens(later));
+ expect(getLastAssistantUsageInfo([response, update, { ...later, timestamp: 21 }])?.index).toBe(2);
+ });
+ for (const timestamp of [undefined, null, "20", NaN, Infinity, -Infinity]) {
+ it(`rejects malformed timestamp ${String(timestamp)} without poisoning usage selection`, () => {
+ const malformed = { role: "user", content: "private", timestamp } as unknown as Message;
+ for (const messages of [[malformed, response], [response, malformed], [malformed, assistant([], 30, 0)]]) {
+ expect(() => getLastAssistantUsageInfo(messages)).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }));
+ expect(() => estimateContextTokens(messages)).toThrow(LocalRequestError);
+ }
+ });
+ }
+ it("accepts explicit zero timestamps and ties without inventing wall-clock values", () => {
+ const original = assistant([], 0, 100);
+ const messages: Message[] = [{ role: "system", content: "initial", timestamp: 0 }, original];
+ expect(getLastAssistantUsageInfo(messages)?.index).toBe(1);
+ expect(estimateContextTokens(messages).tokens).toBe(100);
+ expect(original.timestamp).toBe(0);
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/hosted-search-error-results.test.ts b/packages/agent-runtime/src/hosted-search-error-results.test.ts
new file mode 100644
index 000000000..b56a3401a
--- /dev/null
+++ b/packages/agent-runtime/src/hosted-search-error-results.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from "vitest";
+import {
+ hostedSearchReplayProjection,
+ normalizeContext,
+ normalizeHostedSearchContent,
+ type AssistantMessage,
+ type HostedSearchContent,
+ type Model,
+} from "@earendil-works/pi-ai";
+import { estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
+import { streamSimple } from "@earendil-works/pi-ai/api/anthropic-messages";
+
+const model: Model<"anthropic-messages"> = {
+ id: "offline-anthropic", name: "Offline", api: "anthropic-messages", provider: "anthropic",
+ baseUrl: "http://127.0.0.1", reasoning: false, input: ["text"],
+ contextWindow: 100_000, maxTokens: 1024, webSearch: true,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+};
+const request: HostedSearchContent = {
+ type: "hostedSearch", phase: "server_tool_use", blockId: "search-1",
+ name: "web_search", input: { query: "offline fixture" },
+};
+function message(result: HostedSearchContent): AssistantMessage {
+ return {
+ role: "assistant", content: [request, result], api: model.api, provider: model.provider,
+ model: model.id, timestamp: 2, stopReason: "stop",
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ };
+}
+
+// Both representations are already supported by the adapter; neither result
+// is an ordinary tool call and neither is allowed to acquire fake fields.
+const results: Extract<HostedSearchContent, { phase: "web_search_tool_result" }>[] = [
+ {
+ type: "hostedSearch", phase: "web_search_tool_result", blockId: "search-1", isError: true,
+ wire: { type: "web_search_tool_result_error", tool_use_id: "search-1",
+ content: { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" } },
+ },
+ {
+ type: "hostedSearch", phase: "web_search_tool_result", blockId: "search-1",
+ wire: { type: "web_search_tool_result", tool_use_id: "search-1",
+ content: { type: "web_search_tool_result_error", error_code: "unavailable" } },
+ },
+];
+
+describe("typed Anthropic search error results", () => {
+ for (const result of results) {
+ it(`estimates and replays ${result.wire?.type} without tool fields`, async () => {
+ const before = JSON.stringify(result);
+ const normalized = normalizeHostedSearchContent(result);
+ expect(normalized).not.toHaveProperty("name");
+ expect(normalized).not.toHaveProperty("arguments");
+ const projection = hostedSearchReplayProjection(result, { api: model.api });
+ expect(projection).toEqual(result.wire);
+ const assistant = message(result);
+ const expectedChars = [request, result].reduce((sum, block) => sum + JSON.stringify(hostedSearchReplayProjection(block)).length, 0);
+ expect(estimateMessageTokens(assistant, model)).toBe(Math.ceil(expectedChars / 4));
+ let fetches = 0;
+ const events = [
+ { type: "message_start", message: { id: "response-1", model: model.id, usage: { input_tokens: 1, output_tokens: 0 } } },
+ { type: "content_block_start", index: 0, content_block: hostedSearchReplayProjection(request) },
+ { type: "content_block_stop", index: 0 },
+ { type: "content_block_start", index: 1, content_block: projection },
+ { type: "content_block_stop", index: 1 },
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
+ { type: "message_stop" },
+ ];
+ const stream = streamSimple(model, normalizeContext({ messages: [assistant] }), {
+ apiKey: "offline-fixture", maxRetries: 0,
+ fetch: async (_input, init) => {
+ fetches++;
+ const body = JSON.parse(String(init?.body));
+ expect(body.messages[0].content).toEqual([hostedSearchReplayProjection(request), projection]);
+ expect(JSON.stringify(body)).not.toMatch(/hostedSearch|blockId|isError/);
+ return new Response(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), {
+ headers: { "content-type": "text/event-stream" },
+ });
+ },
+ });
+ const emitted = [];
+ for await (const event of stream) emitted.push(event);
+ const output = await stream.result();
+ expect(fetches).toBe(1);
+ expect(output.stopReason).toBe("stop");
+ expect(output.errorDetails).toBeUndefined();
+ const restored = output.content.find((block) => block.type === "hostedSearch" && block.phase === "web_search_tool_result");
+ expect(restored).toBeDefined();
+ expect(hostedSearchReplayProjection(restored)).toEqual(projection);
+ expect(emitted.some((event) => event.type === "hosted_search_update")).toBe(true);
+ expect(JSON.stringify(result)).toBe(before);
+ });
+ }
+});
+
+
+it("keeps only URL-bearing search citations in the formal search citation field", async () => {
+ const valid = { type: "web_search_result_location", url: "https://example.invalid/source", title: "Source", cited_text: "result" };
+ const citations = [
+ { type: "char_location", document_index: 0, start_char_index: 0, end_char_index: 1 },
+ { type: "web_search_result_location", title: "missing URL" },
+ { type: "web_search_result_location", url: 123 },
+ { type: "web_search_result_location", url: "", title: "empty URL" },
+ valid,
+ ];
+ const events = [
+ { type: "message_start", message: { id: "citation-response", model: model.id, usage: { input_tokens: 1, output_tokens: 0 } } },
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
+ ...citations.map((citation) => ({ type: "content_block_delta", index: 0, delta: { type: "citations_delta", citation } })),
+ { type: "content_block_stop", index: 0 },
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
+ { type: "message_stop" },
+ ];
+ const stream = streamSimple(model, normalizeContext({ messages: [{ role: "user", content: "offline citations", timestamp: 1 }] }), {
+ apiKey: "offline-fixture", maxRetries: 0,
+ fetch: async () => new Response(events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), {
+ headers: { "content-type": "text/event-stream" },
+ }),
+ });
+ for await (const _event of stream) { /* Drain the real adapter stream. */ }
+ const output = await stream.result();
+ expect(output.stopReason).toBe("stop");
+ expect(output.hostedSearchCitations).toEqual([valid]);
+});
diff --git a/packages/agent-runtime/src/hosted-search-estimation.test.ts b/packages/agent-runtime/src/hosted-search-estimation.test.ts
new file mode 100644
index 000000000..7e50ac700
--- /dev/null
+++ b/packages/agent-runtime/src/hosted-search-estimation.test.ts
@@ -0,0 +1,228 @@
+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";
+
+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 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 } };
+}
+function assistant(content: unknown[], api: Api = "openai-responses", tokens = 0, timestamp = 2): AssistantMessage {
+ return { role: "assistant", content, api, provider: model(api).provider, model: "test-model", timestamp, stopReason: "stop", usage: { input: tokens, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: tokens, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } } as AssistantMessage;
+}
+function search(api: Api, size = 1): unknown[] {
+ return api === "anthropic-messages" ? [
+ { type: "hostedSearch", phase: "server_tool_use", blockId: "srv_1", name: "web_search", input: { query: "q" } },
+ { type: "hostedSearch", phase: "web_search_tool_result", blockId: "srv_1", wire: { type: "web_search_tool_result", tool_use_id: "srv_1", content: [{ type: "web_search_result", encrypted_content: "x".repeat(size) }] } },
+ ] : [{ 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) } } }];
+}
+function sse(api: Api): string {
+ return api === "anthropic-messages"
+ ? 'event: message_start\ndata: {"type":"message_start","message":{"id":"m","model":"test-model","usage":{"input_tokens":1,"output_tokens":0}}}\n\nevent: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}\n\nevent: message_stop\ndata: {"type":"message_stop"}\n\n'
+ : 'event: response.completed\ndata: {"type":"response.completed","response":{"id":"r","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}\n\n';
+}
+async function run(api: typeof apis[number], content: unknown[], options: Record<string, unknown> = {}) {
+ const adapter = await import(`@earendil-works/pi-ai/api/${api}`);
+ let fetches = 0;
+ let body: Record<string, unknown> | undefined;
+ const stream = adapter.streamSimple(model(api), { messages: [assistant(content, api)] }, {
+ apiKey: "test", maxRetries: 0,
+ fetch: async (_input: unknown, init?: RequestInit) => {
+ fetches++;
+ body = JSON.parse(String(init?.body));
+ return new Response(sse(api), { headers: { "content-type": "text/event-stream" } });
+ }, ...options,
+ });
+ const result = await stream.result();
+ return { result, fetches, body };
+}
+
+describe("real dependency hosted-search estimation and requests", () => {
+ it("preserves text/thinking/tool/image numeric baselines", () => {
+ const message = assistant([{ type: "text", text: "12345678" }, { type: "thinking", thinking: "1234" }, { type: "toolCall", id: "t", name: "run", arguments: { a: 1 } }]);
+ expect(estimateMessageTokens(message)).toBe(6);
+ expect(compaction.estimateTokens(message)).toBe(6);
+ expect(estimateMessageTokens({ role: "user", content: [{ type: "image", data: "", mimeType: "image/png" }], timestamp: 1 })).toBe(1200);
+ expect(compaction.estimateTokens({ role: "custom", content: "12345" })).toBe(2);
+ expect(compaction.estimateTokens({ role: "bashExecution", command: "1234", output: "5678" })).toBe(2);
+ expect(compaction.estimateTokens({ role: "branchSummary", summary: "12345" })).toBe(2);
+ expect(compaction.estimateTokens({ role: "compactionSummary", summary: "12345" })).toBe(2);
+ });
+ for (const api of apis) {
+ it(`${api}: estimates nameless search blocks with zero usage and growing content`, () => {
+ const small = assistant(search(api), api);
+ const large = assistant(search(api, 4000), api);
+ expect(estimateMessageTokens(small)).toBeGreaterThan(0);
+ expect(estimateMessageTokens(large) - estimateMessageTokens(small)).toBeGreaterThan(990);
+ expect(compaction.estimateTokens(large)).toBe(estimateMessageTokens(large));
+ expect(estimateContextTokens([large]).tokens).toBe(estimateMessageTokens(large));
+ expect(compaction.estimateContextTokens([large])).toEqual(estimateContextTokens([large]));
+ });
+ it(`${api}: shares valid usage and stale-prefix rules`, () => {
+ const msg = assistant(search(api, 400), api, 123);
+ const newerPrefix = { role: "user" as const, content: "new prefix", timestamp: 10 };
+ expect(estimateContextTokens([msg]).tokens).toBe(123);
+ expect(compaction.estimateContextTokens([msg]).tokens).toBe(123);
+ expect(compaction.estimateContextTokens([newerPrefix, msg])).toEqual(estimateContextTokens([newerPrefix, msg]));
+ const tail = assistant(search(api, 200), api, 0, 20);
+ expect(estimateContextTokens([msg, tail]).tokens).toBe(123 + estimateMessageTokens(tail));
+ for (const stopReason of ["aborted", "error"] as const) {
+ const failed = { ...msg, stopReason };
+ expect(estimateContextTokens([failed]).lastUsageIndex).toBeNull();
+ expect(compaction.estimateContextTokens([failed])).toEqual(estimateContextTokens([failed]));
+ }
+ });
+ it(`${api}: streamSimple replays zero-usage search history through mock fetch`, async () => {
+ const { result, fetches, body } = await run(api, search(api));
+ expect(result.stopReason).toBe("stop");
+ expect(fetches).toBe(1);
+ expect(JSON.stringify(body)).toContain(api === "anthropic-messages" ? "encrypted_content" : "web_search_call");
+ });
+ it(`${api}: rejects unknown phases locally before fetch`, async () => {
+ const { result, fetches } = await run(api, [{ type: "hostedSearch", phase: "unknown", blockId: "invalid" }]);
+ expect(fetches).toBe(0);
+ expect(result.stopReason).toBe("error");
+ expect(result.errorDetails).toMatchObject({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" });
+ expect(result.errorMessage).not.toContain("invalid");
+ });
+ it(`${api}: does not label network TypeError as local`, async () => {
+ const { result } = await run(api, [{ type: "text", text: "ok" }], { fetch: async () => { throw new TypeError("socket unavailable"); } });
+ expect(result.stopReason).toBe("error");
+ expect(result.errorDetails).toBeUndefined();
+ });
+ it(`${api}: retains phase/causeName for preparation failures before fetch`, async () => {
+ const { result, fetches } = await run(api, search(api), { onPayload: () => { throw new TypeError("private payload text"); } });
+ expect(fetches).toBe(0);
+ expect(result.errorDetails).toEqual({ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation", message: "Local request preparation failed", causeName: "TypeError" });
+ expect(result.errorMessage).not.toContain("private");
+ });
+ it(`${api}: does not label HTTP or response parsing failures as local`, async () => {
+ for (const response of [
+ new Response('{"error":{"message":"unavailable"}}', { status: 503, headers: { "content-type": "application/json" } }),
+ new Response('event: message_start\ndata: not-json\n\nevent: response.completed\ndata: not-json\n\n', { headers: { "content-type": "text/event-stream" } }),
+ ]) {
+ const { result } = await run(api, [{ type: "text", text: "ok" }], { fetch: async () => response });
+ expect(result.stopReason).toBe("error");
+ expect(result.errorDetails).toBeUndefined();
+ }
+ });
+ it(`${api}: keeps cancellation aborted without local metadata`, async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const { result, fetches } = await run(api, [{ type: "hostedSearch", phase: "unknown" }], { signal: controller.signal });
+ expect(fetches).toBe(0);
+ expect(result.stopReason).toBe("aborted");
+ expect(result.errorDetails).toBeUndefined();
+ });
+ it(`${api}: valid usage cannot hide invalid blocks; direct stream fails before fetch`, async () => {
+ const adapter = await import(`@earendil-works/pi-ai/api/${api}`);
+ const invalid = assistant([{ type: "hostedSearch", phase: "unknown", blockId: "secret" }], api, 100);
+ expect(() => estimateContextTokens([invalid])).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR" }));
+ expect(() => compaction.estimateContextTokens([invalid])).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR" }));
+ let fetches = 0;
+ const result = await adapter.stream(model(api), { messages: [invalid] }, { apiKey: "test", fetch: async () => { fetches++; throw new Error("must not fetch"); } }).result();
+ expect(fetches).toBe(0);
+ expect(result.errorDetails?.phase).toBe("context-validation");
+ });
+ it(`${api}: preserves actual buildBaseOptions estimation failures before fetch`, async () => {
+ const adapter = await import(`@earendil-works/pi-ai/api/${api}`);
+ let fetches = 0;
+ const result = await adapter.streamSimple(model(api), { messages: [{ role: "user", content: null, timestamp: 1 }] }, {
+ apiKey: "test", fetch: async () => { fetches++; throw new Error("must not fetch"); },
+ }).result();
+ expect(fetches).toBe(0);
+ expect(result.errorDetails).toMatchObject({ code: "LOCAL_REQUEST_ERROR", phase: "context-estimation", causeName: "TypeError" });
+ });
+ }
+ it("does not treat unknown blocks as tool calls or silently return zero", () => {
+ expect(() => compaction.estimateTokens({ role: "future", content: [] })).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR" }));
+ for (const content of [[{ type: "future", name: "fake", arguments: {} }], [{ type: "hostedSearch", phase: "unknown", name: "fake", arguments: {} }]]) {
+ expect(() => estimateMessageTokens(assistant(content))).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR" }));
+ expect(() => compaction.estimateTokens(assistant(content))).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR" }));
+ }
+ });
+ it("replays Responses wire only for the same model and estimates it once", () => {
+ const content = search("openai-responses", 100);
+ const msg = assistant(content);
+ const context = normalizeContext({ messages: [msg] });
+ const same = convertResponsesMessages(model("openai-responses"), context, new Set(), {});
+ const other = convertResponsesMessages({ ...model("openai-responses"), id: "other" }, context, new Set(), {});
+ expect(same).toHaveLength(1);
+ expect(other).toHaveLength(0);
+ expect(estimateMessageTokens(msg, { ...model("openai-responses"), id: "other" })).toBe(0);
+ expect(estimateMessageTokens(msg)).toBe(Math.ceil(JSON.stringify(same[0]).length / 4));
+ const decorated = { ...(content[0] as object), query: "ignored".repeat(1000), results: [{ url: "ignored".repeat(1000) }] };
+ expect(estimateMessageTokens(assistant([decorated]))).toBe(estimateMessageTokens(msg));
+ });
+ it("declares search content and events without fake name/arguments", () => {
+ const block: HostedSearchContent = { type: "hostedSearch", phase: "web_search_call", blockId: "legacy" };
+ const event: AssistantMessageEvent = { type: "hosted_search_update", contentIndex: 0, partial: assistant([block]) };
+ expect(event.partial.content[0]).not.toHaveProperty("name");
+ expect(event.partial.content[0]).not.toHaveProperty("arguments");
+ const replay = convertResponsesMessages(model("openai-responses"), normalizeContext({ messages: [assistant([block])] }), new Set());
+ expect(replay).toEqual([{ type: "web_search_call", id: "legacy", status: "completed" }]);
+ expect(estimateMessageTokens(assistant([block]))).toBe(Math.ceil(JSON.stringify(replay[0]).length / 4));
+ });
+ it("matches Anthropic replay estimates across models and search toggles", async () => {
+ const adapter = await import("@earendil-works/pi-ai/api/anthropic-messages");
+ for (const webSearch of [true, false]) {
+ const msg = assistant(search("anthropic-messages", 400), "anthropic-messages");
+ let body: { messages: { role: string; content: unknown[] }[]; tools?: { type: string }[] } | undefined;
+ await adapter.streamSimple({ ...model("anthropic-messages"), id: "other", webSearch }, normalizeContext({ messages: [msg] }), {
+ apiKey: "test", fetch: async (_input, init) => {
+ body = JSON.parse(String(init?.body));
+ return new Response(sse("anthropic-messages"), { headers: { "content-type": "text/event-stream" } });
+ },
+ }).result();
+ const blocks = body?.messages.find(m => m.role === "assistant")?.content ?? [];
+ expect(blocks).toHaveLength(2);
+ expect(estimateMessageTokens(msg)).toBe(Math.ceil(blocks.reduce<number>((sum, block) => sum + JSON.stringify(block).length, 0) / 4));
+ expect(body?.tools?.some(tool => tool.type.startsWith("web_search")) ?? false).toBe(webSearch);
+ }
+ });
+ it("normalizes legacy missing input and wire IDs but rejects invalid data", () => {
+ expect(normalizeHostedSearchContent({ type: "hostedSearch", phase: "server_tool_use", blockId: "s", name: "web_search" })).toMatchObject({ input: {} });
+ expect(normalizeHostedSearchContent({ type: "hostedSearch", phase: "web_search_call", wire: { type: "web_search_call", id: "w" } })).toMatchObject({ blockId: "w" });
+ const cycle: Record<string, unknown> = {};
+ cycle.self = cycle;
+ for (const block of [
+ { type: "hostedSearch", phase: "web_search_tool_result", blockId: "s" },
+ { type: "hostedSearch", phase: "web_search_call", blockId: "s", wire: [] },
+ { type: "hostedSearch", phase: "web_search_call", blockId: "s", wire: { type: "other", id: "s" } },
+ { type: "hostedSearch", phase: "server_tool_use", blockId: "s", name: "web_search", input: cycle },
+ ]) expect(() => estimateMessageTokens(assistant([block]))).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }));
+ });
+ it("recognizes only explicit local markers and excludes cause from messages", () => {
+ const cause = new TypeError("private request");
+ const error = new LocalRequestError("context-estimation", { cause });
+ expect(error.cause).toBe(cause);
+ expect(error.message).not.toContain("private");
+ expect(localRequestErrorDetails(error)).toMatchObject({ code: "LOCAL_REQUEST_ERROR", phase: "context-estimation", causeName: "TypeError" });
+ expect(localRequestErrorDetails({ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation" })).toBeDefined();
+ expect(localRequestErrorDetails(cause)).toBeUndefined();
+ expect(localRequestErrorDetails({ code: "LOCAL_REQUEST_ERROR", phase: "network" })).toBeUndefined();
+ });
+ it("pi-agent-core preserves streamed and thrown local error details", async () => {
+ const { Agent } = await import("@earendil-works/pi-agent-core");
+ const adapter = await import("@earendil-works/pi-ai/api/openai-responses");
+ for (const streamFn of [
+ () => { throw new LocalRequestError("context-estimation", { cause: new TypeError("private") }); },
+ () => adapter.streamSimple(model("openai-responses"), normalizeContext({ messages: [assistant([{ type: "hostedSearch", phase: "unknown" }])] }), {
+ apiKey: "test", maxRetries: 0, fetch: async () => { throw new Error("must not fetch"); },
+ }),
+ ]) {
+ const agent = new Agent({ initialState: { model: model("openai-responses") }, streamFn });
+ await agent.prompt("local only");
+ const last = agent.state.messages.at(-1) as AssistantMessage;
+ expect(last.stopReason).toBe("error");
+ expect(last.errorDetails?.code).toBe("LOCAL_REQUEST_ERROR");
+ expect(last.errorMessage).not.toContain("private");
+ }
+ });
+});
diff --git a/packages/agent-runtime/src/hosted-search-replay.test.ts b/packages/agent-runtime/src/hosted-search-replay.test.ts
new file mode 100644
index 000000000..aaad90233
--- /dev/null
+++ b/packages/agent-runtime/src/hosted-search-replay.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import type { HostedSearch } from "@pi-desktop/shared";
+import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
+
+function stored(replay: HostedSearch["replay"]): HostedSearch {
+ return { status: "completed", rounds: [], replay };
+}
+
+describe("stored hosted-search replay boundary", () => {
+ it("keeps display-only old records readable without manufacturing replay", () => {
+ expect(restoreHostedSearchReplay(undefined)).toEqual([]);
+ expect(restoreHostedSearchReplay(stored(undefined))).toEqual([]);
+ });
+
+ it("restores old search items without name or arguments and does not mutate storage", () => {
+ const search = stored([{
+ type: "hostedSearch",
+ phase: "web_search_call",
+ blockId: "ws_fixture",
+ wire: { type: "web_search_call", id: "ws_fixture", status: "completed", action: { type: "search", query: "fixture" } },
+ }]);
+ const snapshot = structuredClone(search);
+ const result = restoreHostedSearchReplay(search);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ type: "hostedSearch", phase: "web_search_call" });
+ expect(result[0]).not.toHaveProperty("name");
+ expect(result[0]).not.toHaveProperty("arguments");
+ expect(search).toEqual(snapshot);
+ expect(result[0]).not.toBe(search.replay?.[0]);
+ });
+
+ it("retains paired server search input and opaque result content in order", () => {
+ const search = stored([
+ { type: "hostedSearch", phase: "server_tool_use", blockId: "srv_fixture", name: "web_search", input: { query: "fixture" } },
+ { type: "hostedSearch", phase: "web_search_tool_result", blockId: "srv_fixture", wire: { type: "web_search_tool_result", tool_use_id: "srv_fixture", content: [{ type: "web_search_result", encrypted_content: "opaque-fixture" }] } },
+ ]);
+ expect(restoreHostedSearchReplay(search)).toMatchObject(search.replay!);
+ });
+
+ it("classifies a malformed stored replay container before array operations", () => {
+ const invalid: HostedSearch = JSON.parse('{"status":"completed","rounds":[],"replay":{}}');
+ expect(() => restoreHostedSearchReplay(invalid)).toThrow(
+ expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }),
+ );
+ });
+
+ it("reports a structured local error rather than dropping a corrupt replay phase", () => {
+ expect(() => restoreHostedSearchReplay(stored([
+ { type: "hostedSearch", phase: "unsupported", blockId: "fixture" },
+ ]))).toThrow(expect.objectContaining({ code: "LOCAL_REQUEST_ERROR", phase: "context-validation" }));
+ });
+});
diff --git a/packages/agent-runtime/src/hosted-search-replay.ts b/packages/agent-runtime/src/hosted-search-replay.ts
new file mode 100644
index 000000000..924c68c0a
--- /dev/null
+++ b/packages/agent-runtime/src/hosted-search-replay.ts
@@ -0,0 +1,17 @@
+import type { HostedSearchContent } from "@earendil-works/pi-ai";
+import { normalizeHostedSearchContent } from "@earendil-works/pi-ai/utils/hosted-search";
+import { LocalRequestError } from "@earendil-works/pi-ai/utils/local-request-error";
+import type { HostedSearch } from "@pi-desktop/shared";
+
+/**
+ * 持久化类型保持向后兼容;只在进入模型上下文的边界收敛为正式搜索类型。
+ * 旧记录没有 replay 时仍可展示。有 replay 但结构损坏时必须给出本地错误,
+ * 不能靠类型断言或静默过滤丢掉 grounding 数据后继续发请求。
+ */
+export function restoreHostedSearchReplay(
+ search: HostedSearch | undefined,
+): HostedSearchContent[] {
+ if (search?.replay === undefined) return [];
+ if (!Array.isArray(search.replay)) throw new LocalRequestError("context-validation");
+ return search.replay.map((block) => normalizeHostedSearchContent(block));
+}
diff --git a/packages/agent-runtime/src/local-request-errors.ts b/packages/agent-runtime/src/local-request-errors.ts
new file mode 100644
index 000000000..5ac01e8b4
--- /dev/null
+++ b/packages/agent-runtime/src/local-request-errors.ts
@@ -0,0 +1,89 @@
+/**
+ * Structural compatibility with pi-ai's local request errors and wire metadata.
+ *
+ * Provenance is exactly `code` plus a known `phase`: pi-ai's own reader accepts
+ * nothing else, and the `message` it reports comes from its fixed table rather
+ * than from the payload. The same rule holds here — a local failure's own text
+ * can carry prompt, path or credential material, so it is never copied out.
+ */
+export type LocalRequestPhase =
+ | "context-validation"
+ | "context-estimation"
+ | "request-preparation";
+
+export type LocalRequestErrorDetails = {
+ code: "LOCAL_REQUEST_ERROR";
+ phase: LocalRequestPhase;
+ message: string;
+ causeName?: string;
+};
+
+const LOCAL_MESSAGES: Record<LocalRequestPhase, string> = {
+ "context-validation": "Local request context validation failed.",
+ "context-estimation": "Local request context estimation failed.",
+ "request-preparation": "Local request preparation failed.",
+};
+
+// Error names are mutable free text too. Only known diagnostic names may cross
+// the UI boundary; custom names and all messages/stacks stay on the local cause.
+const SAFE_CAUSE_NAMES = new Set([
+ "Error", "TypeError", "RangeError", "ReferenceError", "SyntaxError",
+ "URIError", "EvalError", "AggregateError", "AbortError", "LocalRequestError",
+]);
+
+function record(value: unknown): Record<string, unknown> | undefined {
+ return value !== null && typeof value === "object"
+ ? value as Record<string, unknown>
+ : undefined;
+}
+
+function isLocalRequestPhase(value: unknown): value is LocalRequestPhase {
+ return (
+ value === "context-validation" ||
+ value === "context-estimation" ||
+ value === "request-preparation"
+ );
+}
+
+/**
+ * pi-ai's own acceptance rule, no wider: `code` plus a known `phase`. `message`
+ * is deliberately not part of it (upstream synthesizes that field too), so
+ * phase-only details are still explicit provenance instead of something to be
+ * second-guessed. Everything else in the payload is ignored, not interpreted.
+ */
+function readDetails(value: unknown): LocalRequestErrorDetails | undefined {
+ const detail = record(value);
+ if (
+ detail?.code !== "LOCAL_REQUEST_ERROR" ||
+ !isLocalRequestPhase(detail.phase)
+ ) return undefined;
+ // Upstream carries the wrapped failure as `cause` (an Error) on the raw
+ // marker and as the flat `causeName` once normalized; both name one original.
+ const causeName = detail.causeName ?? record(detail.cause)?.name;
+ return {
+ code: "LOCAL_REQUEST_ERROR",
+ phase: detail.phase,
+ message: LOCAL_MESSAGES[detail.phase],
+ ...(typeof causeName === "string" && SAFE_CAUSE_NAMES.has(causeName)
+ ? { causeName } : {}),
+ };
+}
+
+/**
+ * Never infer local origin from error wording, constructor names or TypeError.
+ * Accept only pi-ai's explicit code/phase marker, either on the original error
+ * or on the AssistantMessage.errorDetails the adapters attach. The cause
+ * traversal is bounded and cycle-safe so a wrapped marker is still found without
+ * ever interpreting an arbitrary provider response body.
+ */
+export function readLocalRequestErrorDetails(error: unknown): LocalRequestErrorDetails | undefined {
+ let current = record(error);
+ const seen = new Set<object>();
+ for (let depth = 0; current && depth < 6 && !seen.has(current); depth += 1) {
+ seen.add(current);
+ const details = readDetails(current.errorDetails) ?? readDetails(current);
+ if (details) return details;
+ current = record(current.cause);
+ }
+ return undefined;
+}
diff --git a/packages/agent-runtime/src/output-cap.test.ts b/packages/agent-runtime/src/output-cap.test.ts
index c3215e96d..1240981cf 100644
--- a/packages/agent-runtime/src/output-cap.test.ts
+++ b/packages/agent-runtime/src/output-cap.test.ts
@@ -64,6 +64,193 @@ describe("estimateOutputCapInputTokens", () => {
});
});
+describe("hosted search output budget", () => {
+ const context = (text: string): OutputCapContext => ({
+ messages: [{
+ role: "assistant",
+ content: [{
+ type: "hostedSearch",
+ phase: "web_search_tool_result",
+ blockId: "search_fixture",
+ wire: {
+ type: "web_search_tool_result",
+ tool_use_id: "search_fixture",
+ content: [{ type: "web_search_result", title: text }],
+ },
+ }],
+ }],
+ });
+
+ it("scales with hosted search replay rather than charging a fixed image budget", () => {
+ const small = estimateOutputCapInputTokens(context("a".repeat(100)));
+ const large = estimateOutputCapInputTokens(context("a".repeat(10_100)));
+ expect(small).toBeGreaterThan(0);
+ expect(large - small).toBe(2500);
+ });
+
+ it("applies CJK correction to hosted search replay", () => {
+ const ascii = estimateOutputCapInputTokens(context("a".repeat(1000)));
+ const cjk = estimateOutputCapInputTokens(context("中".repeat(1000)));
+ expect(cjk - ascii).toBe(750);
+ });
+});
+
+describe("hosted search target model threading", () => {
+ /** A Responses target model, identity included as the adapters stamp it. */
+ const RESPONSES_MODEL = {
+ contextWindow: 262_144,
+ maxTokens: 32_768,
+ api: "openai-responses",
+ provider: "openai",
+ id: "gpt-test",
+ };
+
+ const searchCall = (size: number) => ({
+ type: "hostedSearch",
+ phase: "web_search_call",
+ blockId: "search_fixture",
+ wire: {
+ type: "web_search_call",
+ id: "search_fixture",
+ status: "completed",
+ action: { type: "search", query: "a".repeat(size) },
+ },
+ });
+
+ const responsesContext = (
+ model: string,
+ size: number,
+ ): OutputCapContext => ({
+ messages: [
+ {
+ role: "assistant",
+ api: "openai-responses",
+ provider: "openai",
+ model,
+ content: [searchCall(size)],
+ },
+ ],
+ });
+
+ it("charges same-model Responses search and grows with the payload", () => {
+ const small = estimateOutputCapInputTokens(
+ responsesContext("gpt-test", 100),
+ RESPONSES_MODEL,
+ );
+ const large = estimateOutputCapInputTokens(
+ responsesContext("gpt-test", 10_100),
+ RESPONSES_MODEL,
+ );
+ expect(small).toBeGreaterThan(0);
+ expect(large - small).toBe(2_500);
+ });
+
+ it("charges nothing for Responses search the target model discards", () => {
+ // The Responses adapter replays a `web_search_call` only when the
+ // assistant message came from the target model; the wire request carries
+ // nothing for any other id, so the estimate must not either.
+ expect(
+ estimateOutputCapInputTokens(
+ responsesContext("other-model", 10_000),
+ RESPONSES_MODEL,
+ ),
+ ).toBe(0);
+ });
+
+ it("keeps the conservative estimate when no target identity is known", () => {
+ // A caller holding window facts only (no `api`) cannot know which search
+ // items the provider replays; charging them keeps the clamp safe.
+ expect(
+ estimateOutputCapInputTokens(
+ responsesContext("other-model", 400),
+ LARGE_WINDOW_MODEL,
+ ),
+ ).toBeGreaterThan(0);
+ });
+
+ it("keeps Anthropic search replay across models", () => {
+ const target = {
+ contextWindow: 200_000,
+ maxTokens: 8_192,
+ api: "anthropic-messages",
+ provider: "anthropic",
+ id: "claude-test",
+ };
+ const estimate = estimateOutputCapInputTokens(
+ {
+ messages: [
+ {
+ role: "assistant",
+ api: "anthropic-messages",
+ provider: "anthropic",
+ model: "claude-other",
+ content: [
+ {
+ type: "hostedSearch",
+ phase: "web_search_tool_result",
+ blockId: "search_fixture",
+ wire: {
+ type: "web_search_tool_result",
+ tool_use_id: "search_fixture",
+ content: [
+ { type: "web_search_result", title: "a".repeat(400) },
+ ],
+ },
+ },
+ ],
+ },
+ ],
+ },
+ target,
+ );
+ // The encrypted Anthropic results replay regardless of the message's model
+ // id, so they stay in the estimate.
+ expect(estimate).toBeGreaterThan(0);
+ });
+
+ it("leaves text, thinking and tool blocks unaffected by the target", () => {
+ const context: OutputCapContext = {
+ messages: [
+ {
+ role: "assistant",
+ api: "openai-responses",
+ provider: "openai",
+ model: "gpt-test",
+ content: [
+ { type: "text", text: "a".repeat(400) },
+ { type: "thinking", thinking: "中".repeat(100) },
+ { type: "toolCall", name: "run", arguments: { a: 1 } },
+ ],
+ },
+ ],
+ };
+ // 400 text chars (/4 = 100) + 100 CJK thinking chars (baseline 25, CJK
+ // correction 75) + the serialized tool call (10 chars).
+ expect(estimateOutputCapInputTokens(context, RESPONSES_MODEL)).toBe(203);
+ expect(estimateOutputCapInputTokens(context)).toBe(203);
+ });
+
+ it("stops charging cross-model search against the output budget", () => {
+ const requested = 32_768;
+ // 2M chars of same-model search dwarfs the window and collapses the
+ // budget; the same payload from another model never reaches the wire.
+ expect(
+ clampOutputToContext(
+ RESPONSES_MODEL,
+ responsesContext("gpt-test", 2_000_000),
+ requested,
+ ),
+ ).toBe(1);
+ expect(
+ clampOutputToContext(
+ RESPONSES_MODEL,
+ responsesContext("other-model", 2_000_000),
+ requested,
+ ),
+ ).toBe(requested);
+ });
+});
+
describe("clampOutputToContext", () => {
it("keeps the requested budget when the input leaves enough room", () => {
expect(
diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.ts
index 6b10f673f..ccc46f05f 100644
--- a/packages/agent-runtime/src/output-cap.ts
+++ b/packages/agent-runtime/src/output-cap.ts
@@ -16,23 +16,70 @@
* that scales with the window instead of pi-ai's fixed 4096. It is applied
* in `runtime.ts` and `subagent-model-binding.ts` before either adapter
* branch runs, so the clamp holds for `streamSimple` and `stream` alike.
+ *
+ * Hosted search is charged through the adapter's own replay projection for the
+ * target model, so a search item the provider discards (a Responses
+ * `web_search_call` from another model) no longer inflates the estimate while
+ * same-model search history keeps counting. A caller that has no target model
+ * passes none and keeps the conservative block-protocol estimate.
*/
+import type { Api } from "@earendil-works/pi-ai";
+import {
+ hostedSearchReplayProjection,
+ type HostedSearchReplayOptions,
+} from "@earendil-works/pi-ai/utils/hosted-search";
+
/** Structural view of the request context; assignable from pi-ai's `Context`. */
export type OutputCapContext = {
systemPrompt?: string;
- messages: Array<{ role: string; content: unknown }>;
+ messages: OutputCapMessage[];
tools?: Array<unknown>;
};
+/**
+ * Structural view of one context message. The replay identity (`api`,
+ * `provider`, `model`) is what pi-ai's adapters stamp on assistant messages;
+ * it is absent on every other role and on records written before hosted
+ * search existed.
+ */
+export type OutputCapMessage = {
+ role: string;
+ content: unknown;
+ api?: Api;
+ provider?: string;
+ model?: string;
+};
+
+/**
+ * The target-model facts the hosted-search replay projection needs: `api`
+ * selects the projection, `provider`/`id` decide whether a Responses
+ * `web_search_call` belongs to the model being asked (the provider discards a
+ * cross-model search item). These are exactly the fields the adapter compares,
+ * so the estimate charges the items the request really carries.
+ */
+export type OutputCapReplayTarget = {
+ api?: Api;
+ provider?: string;
+ id?: string;
+};
+
/** Structural view of the active model. */
-export type OutputCapModel = {
+export type OutputCapModel = OutputCapReplayTarget & {
contextWindow: number;
/** Published limit, when a user override may have enlarged contextWindow. */
catalogContextWindow?: number;
maxTokens: number;
};
+/**
+ * Accepted target argument for the estimator. A caller may hold the full
+ * model or only its window facts (a catalog entry, a caller test); only the
+ * replay identity is read, and a window-only model keeps the conservative
+ * estimate instead of being rejected.
+ */
+export type OutputCapEstimateModel = OutputCapReplayTarget | OutputCapModel;
+
function positiveWindow(value: number | undefined): number | undefined {
if (!Number.isFinite(value) || (value ?? 0) <= 0) return undefined;
return Math.max(1, Math.round(value!));
@@ -83,7 +130,10 @@ function stringifyForEstimate(value: unknown): string {
}
/** Token estimate for one message's content (text/thinking/tool/image). */
-function estimateMessageTokens(content: unknown): {
+function estimateMessageTokens(
+ content: unknown,
+ replayOptions: HostedSearchReplayOptions | undefined,
+): {
baseline: number;
cjkChars: number;
} {
@@ -112,6 +162,17 @@ function estimateMessageTokens(content: unknown): {
const payload = stringifyForEstimate(b.arguments ?? b.input);
chars += b.name.length + payload.length;
cjkChars += countCjkChars(b.name);
+ } else if (b.type === "hostedSearch") {
+ // 与适配器共用回放投影;搜索结果不是图片,也不是普通工具参数。
+ // 投影会校验结构,失败必须保留为本地错误,不能按零成本继续请求。
+ // 只有目标模型不会回放的条目(跨模型的 Responses 搜索)才计零成本,
+ // 判据来自适配器本身,不是这里的猜测。
+ const replay = hostedSearchReplayProjection(b, replayOptions);
+ const payload = JSON.stringify(replay);
+ if (payload !== undefined) {
+ chars += payload.length;
+ cjkChars += countCjkChars(payload);
+ }
} else {
chars += ESTIMATED_CHARS_PER_IMAGE;
}
@@ -119,19 +180,50 @@ function estimateMessageTokens(content: unknown): {
return { baseline: Math.ceil(chars / CHARS_PER_TOKEN), cjkChars };
}
+/**
+ * Replay options for one message, mirroring the adapter exactly: with a known
+ * target `api` a Responses `web_search_call` is replayed only for the model
+ * that produced it, while Anthropic search blocks keep their existing
+ * cross-model semantics (the projection ignores `isSameModel` there).
+ *
+ * Without a target `api` there is no adapter behaviour to mirror, so a caller
+ * holding only window facts keeps the conservative block-protocol estimate:
+ * every search block is charged instead of silently dropped.
+ */
+function replayOptionsFor(
+ message: OutputCapMessage,
+ target: OutputCapReplayTarget | undefined,
+): HostedSearchReplayOptions | undefined {
+ if (target?.api === undefined) return undefined;
+ return {
+ api: target.api,
+ isSameModel:
+ message.api === target.api &&
+ message.provider === target.provider &&
+ message.model === target.id,
+ };
+}
+
/**
* Estimate the input tokens of a request. Mirrors pi-ai's internal estimator
* (chars/4, 1200 tokens per image, serialized tool schemas) and adds the
* missing CJK correction: a CJK char costs ~1 token while the baseline
* charges 0.25, so the shortfall is added back.
+ *
+ * `model` is the request's target model; pass it whenever it is known so
+ * hosted-search history is charged the way the adapter replays it.
*/
export function estimateOutputCapInputTokens(
context: OutputCapContext,
+ model?: OutputCapEstimateModel,
): number {
let baseline = 0;
let cjkChars = 0;
for (const message of context.messages) {
- const estimated = estimateMessageTokens(message.content);
+ const estimated = estimateMessageTokens(
+ message.content,
+ replayOptionsFor(message, model),
+ );
baseline += estimated.baseline;
cjkChars += estimated.cjkChars;
}
@@ -169,7 +261,7 @@ export function clampOutputToContext(
// Unknown window: there is nothing context-based to clamp against; keep the
// configured budget (mirrors pi-ai's `contextWindow <= 0` behavior).
if (contextWindow <= 0) return desired;
- const inputTokens = estimateOutputCapInputTokens(context);
+ const inputTokens = estimateOutputCapInputTokens(context, model);
const reserve = Math.max(
OUTPUT_SAFETY_FLOOR_TOKENS,
Math.ceil(contextWindow * OUTPUT_SAFETY_WINDOW_RATIO),
diff --git a/packages/agent-runtime/src/provider-retry.test.ts b/packages/agent-runtime/src/provider-retry.test.ts
index 29ce8bc72..15e1583dd 100644
--- a/packages/agent-runtime/src/provider-retry.test.ts
+++ b/packages/agent-runtime/src/provider-retry.test.ts
@@ -89,6 +89,213 @@ function successfulStream(): ReturnType<typeof createAssistantMessageEventStream
return stream;
}
+describe("local request failures", () => {
+ const errorDetails = {
+ code: "LOCAL_REQUEST_ERROR" as const,
+ phase: "context-validation" as const,
+ message: "Local request validation failed.",
+ causeName: "TypeError",
+ };
+
+ it.each([false, true])("never claims, retries or fetches a local event (started=%s)", async (started) => {
+ const failure = Object.assign(assistantMessage({ errorMessage: "fetch failed" }), { errorDetails });
+ const fetch = vi.fn();
+ const createStream = vi.fn(() => {
+ const inner = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ if (started) inner.push({ type: "start", partial: failure });
+ inner.push({ type: "error", reason: "error", error: failure });
+ inner.end(failure);
+ });
+ return inner;
+ });
+ // Even a permissive controller must not get to claim a local failure.
+ const claim = vi.fn(() => undefined as number | undefined).mockReturnValueOnce(1);
+ const sleep = vi.fn(async () => undefined);
+ const onRetry = vi.fn();
+ const stream = createProviderRetryStream(model, context, { fetch }, createStream, {
+ claim, sleep, onRetry, headers: () => undefined, status: () => 429,
+ failure: () => describeProviderFetchFailure(new TypeError("fetch failed")),
+ });
+ const events = [];
+ for await (const event of stream) events.push(event);
+ const result = await stream.result();
+ expect(createStream).toHaveBeenCalledTimes(1);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(claim).not.toHaveBeenCalled();
+ expect(sleep).not.toHaveBeenCalled();
+ expect(onRetry).not.toHaveBeenCalled();
+ expect(result).toBe(failure);
+ expect(events.at(-1)).toMatchObject({ type: "error", error: { errorDetails } });
+ expect(classifyProviderError(result, 429)).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "context-validation", causeName: "TypeError" },
+ });
+ });
+
+ it("retains setup error metadata and its original cause without serializing private data", async () => {
+ const cause = new TypeError("private prompt api_key=test-secret");
+ const error = Object.assign(new Error("private payload", { cause }), {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ });
+ const claim = vi.fn();
+ const fetch = vi.fn();
+ const createStream = vi.fn(() => { throw error; });
+ const stream = createProviderRetryStream(model, context, { fetch }, createStream, {
+ claim, headers: () => undefined,
+ });
+ const result = await stream.result();
+ expect(result).toHaveProperty("errorDetails", {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ message: expect.any(String), causeName: "TypeError",
+ });
+ expect(result).toHaveProperty("cause", error);
+ expect(error.cause).toBe(cause);
+ expect(JSON.stringify(result)).not.toMatch(/private|test-secret|stack/);
+ expect(classifyProviderError(result)).toMatchObject({ code: "INTERNAL", retriable: false });
+ expect(createStream).toHaveBeenCalledTimes(1);
+ expect(claim).not.toHaveBeenCalled();
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("still retries an ordinary TypeError fetch rejection with no local metadata", async () => {
+ const fetch = vi.fn().mockRejectedValueOnce(new TypeError("fetch failed"))
+ .mockResolvedValueOnce(new Response("ok"));
+ const claim = vi.fn((error: ClassifiedAgentError) => error.retriable ? 1 : undefined);
+ const sleep = vi.fn(async () => undefined);
+ const stream = createProviderRetryStream(model, context, { fetch }, (options) => {
+ const inner = createAssistantMessageEventStream();
+ void options.fetch!("https://provider.invalid", {}).then(() => {
+ const message = assistantMessage({ stopReason: "stop", errorMessage: undefined });
+ inner.push({ type: "done", reason: "stop", message });
+ inner.end(message);
+ }, (error) => {
+ const message = assistantMessage({ errorMessage: error.message });
+ inner.push({ type: "error", reason: "error", error: message });
+ inner.end(message);
+ });
+ return inner;
+ }, { claim, sleep, headers: () => undefined });
+ expect((await stream.result()).stopReason).toBe("stop");
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(claim).toHaveBeenCalledWith(expect.objectContaining({ code: "NETWORK_ERROR", retriable: true }), "request");
+ expect(sleep).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps an already cancelled request from starting or claiming a retry", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const createStream = vi.fn(() => failedStream());
+ const claim = vi.fn();
+ const stream = createProviderRetryStream(model, context, { signal: controller.signal }, createStream, {
+ claim, headers: () => undefined,
+ });
+ const result = await stream.result();
+ expect(result.stopReason).toBe("aborted");
+ expect(classifyProviderError(result)).toMatchObject({ code: "TURN_ABORTED", retriable: false });
+ expect(createStream).not.toHaveBeenCalled();
+ expect(claim).not.toHaveBeenCalled();
+ });
+
+ it("keeps a phase-only local marker terminal under a stale 429", async () => {
+ // The captured status belongs to an earlier response. The later failure is
+ // explicit local provenance, so it must not be relabelled as a rate limit and
+ // must not claim the retry the stale status alone would allow.
+ const failure = Object.assign(assistantMessage({ errorMessage: "fetch failed" }), {
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR", phase: "context-estimation", causeName: "TypeError",
+ },
+ });
+ const claim = vi.fn(() => undefined as number | undefined).mockReturnValueOnce(1);
+ const sleep = vi.fn(async () => undefined);
+ const createStream = vi.fn(() => {
+ const inner = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ inner.push({ type: "error", reason: "error", error: failure });
+ inner.end(failure);
+ });
+ return inner;
+ });
+ const stream = createProviderRetryStream(model, context, {}, createStream, {
+ claim, sleep, headers: () => undefined, status: () => 429,
+ });
+ const events = [];
+ for await (const event of stream) events.push(event);
+ const result = await stream.result();
+
+ expect(createStream).toHaveBeenCalledTimes(1);
+ expect(claim).not.toHaveBeenCalled();
+ expect(sleep).not.toHaveBeenCalled();
+ expect(result).toBe(failure);
+ expect(result.errorMessage).toBe("fetch failed");
+ expect(events.at(-1)).toMatchObject({
+ type: "error",
+ error: { errorMessage: "fetch failed" },
+ });
+ expect(classifyProviderError(result, 429)).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
+ });
+ });
+
+ it("neither retries nor relabels a synchronous local throw under a stale 429", async () => {
+ const error = Object.assign(new Error("Local request preparation failed."), {
+ name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
+ phase: "request-preparation", cause: new TypeError("private prompt"),
+ });
+ const claim = vi.fn(() => 1 as number | undefined);
+ const sleep = vi.fn(async () => undefined);
+ const createStream = vi.fn(() => { throw error; });
+ const stream = createProviderRetryStream(model, context, {}, createStream, {
+ claim, sleep, headers: () => ({ "retry-after": "1" }), status: () => 429,
+ });
+ const events: string[] = [];
+ for await (const event of stream) events.push(event.type);
+ const result = await stream.result();
+
+ expect(events).toEqual(["error"]);
+ expect(createStream).toHaveBeenCalledTimes(1);
+ expect(claim).not.toHaveBeenCalled();
+ expect(sleep).not.toHaveBeenCalled();
+ expect(result).toHaveProperty("errorDetails", {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ message: expect.any(String), causeName: "TypeError",
+ });
+ expect(JSON.stringify(result)).not.toMatch(/private/);
+ expect(classifyProviderError(result, 429)).toMatchObject({
+ code: "INTERNAL", retriable: false,
+ });
+ });
+
+ it("keeps a locally wrapped Stop as cancellation, not as a local failure", async () => {
+ // pi-ai records the wrapped AbortError only in the marker's cause, and this
+ // path has no aborted signal to read, so the cause name is all there is.
+ const thrown = Object.assign(new Error("Local request preparation failed."), {
+ name: "LocalRequestError", code: "LOCAL_REQUEST_ERROR",
+ phase: "request-preparation",
+ cause: Object.assign(new Error("The operation was aborted"), { name: "AbortError" }),
+ });
+ const claim = vi.fn(() => 1 as number | undefined);
+ const sleep = vi.fn(async () => undefined);
+ const createStream = vi.fn(() => { throw thrown; });
+ const stream = createProviderRetryStream(model, context, {}, createStream, {
+ claim, sleep, headers: () => undefined,
+ });
+ const result = await stream.result();
+
+ expect(createStream).toHaveBeenCalledTimes(1);
+ expect(claim).not.toHaveBeenCalled();
+ expect(sleep).not.toHaveBeenCalled();
+ expect(result).toHaveProperty("errorDetails", {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation",
+ message: expect.any(String), causeName: "AbortError",
+ });
+ expect(classifyProviderError(result)).toMatchObject({
+ code: "TURN_ABORTED", retriable: false,
+ });
+ });
+});
+
describe("provider rate-limit retry", () => {
it("uses a captured 429 status when the provider body is generic", () => {
expect(classifyProviderError("upstream unavailable", 429)).toMatchObject({
diff --git a/packages/agent-runtime/src/provider-retry.ts b/packages/agent-runtime/src/provider-retry.ts
index 0685b14d1..90d78b0a8 100644
--- a/packages/agent-runtime/src/provider-retry.ts
+++ b/packages/agent-runtime/src/provider-retry.ts
@@ -14,6 +14,7 @@ import {
classifyAgentError,
type ClassifiedAgentError,
} from "./agent-errors.js";
+import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import {
describeProviderFetchFailure,
type ProviderFetchFailure,
@@ -367,6 +368,8 @@ export function captureProviderResponse(
}
function normalizeRateLimitMessage(message: AssistantMessage): AssistantMessage {
+ // A previous HTTP response is not evidence about a later local failure.
+ if (readLocalRequestErrorDetails(message)) return message;
const errorMessage = message.errorMessage ?? "";
if (/^\s*429\b/.test(errorMessage)) return message;
return {
@@ -380,7 +383,8 @@ function setupErrorMessage(
error: unknown,
aborted: boolean,
): AssistantMessage {
- return {
+ const local = readLocalRequestErrorDetails(error);
+ const message: AssistantMessage = {
role: "assistant",
content: [],
api: model.api,
@@ -395,9 +399,14 @@ function setupErrorMessage(
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: aborted ? "aborted" : "error",
- errorMessage: error instanceof Error ? error.message : String(error),
+ errorMessage: local
+ ? (aborted ? "Request aborted" : local.message)
+ : error instanceof Error ? error.message : String(error),
+ ...(!aborted && local ? { errorDetails: local } : {}),
timestamp: Date.now(),
};
+ // Preserve the original exception for local diagnostics, not JSON/UI events.
+ return local ? Object.defineProperty(message, "cause", { value: error }) : message;
}
type StreamFactory = (
@@ -447,23 +456,20 @@ export function createProviderRetryStream(
event.type === "error" &&
event.reason === "error"
) {
- const errorMessage =
- typeof event.error.errorMessage === "string"
- ? event.error.errorMessage
- : event.error;
// Fold in the cause the fetch wrapper captured for this attempt: the
// message pi-ai hands over is already flattened, so without it the
// retry indicator and the terminal error read `fetch failed` with no
// errno (issue #234).
const error = withProviderFetchFailure(
- classifyProviderError(errorMessage, controller.status?.()),
+ classifyProviderError(event.error, controller.status?.()),
controller.failure?.(),
);
if (!limitRepairTried && isOpaqueBadRequest(error)) {
opaqueLimitRejection = error;
break;
}
- const attempt = controller.claim(error, "request");
+ const attempt = error.details?.origin === "local"
+ ? undefined : controller.claim(error, "request");
if (attempt !== undefined) {
retry = { error, attempt };
break;
diff --git a/packages/agent-runtime/src/reasoning-replay.ts b/packages/agent-runtime/src/reasoning-replay.ts
index 05a239d3c..4d8e614db 100644
--- a/packages/agent-runtime/src/reasoning-replay.ts
+++ b/packages/agent-runtime/src/reasoning-replay.ts
@@ -83,7 +83,7 @@ function assistantThinkingText(message: AssistantMessage): {
const text: string[] = [];
let thinkingSignature: string | undefined;
for (const block of message.content) {
- if (!isRecord(block)) continue;
+ if (block === null || typeof block !== "object") continue;
if (block.type === "thinking" && typeof block.thinking === "string") {
const value = block.thinking.trim();
if (value) {
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index cc0346e2b..c7ff7917a 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it, vi } from "vitest";
-import { estimateTokens, type Agent } from "@earendil-works/pi-agent-core";
+import { estimateContextTokens as estimateAgentContextTokens, estimateTokens, type Agent } from "@earendil-works/pi-agent-core";
+import {
+ getCurrentTools,
+ getCurrentSystemMessage,
+ toToolDeclaration,
+} from "@earendil-works/pi-ai";
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 {
COMPACTION_FALLBACK_MARKER,
@@ -232,6 +238,92 @@ function runtimeMatches(
});
}
+describe("system transcript reconstruction", () => {
+ it("keeps provider usage valid when rebuilding an unchanged prefix", async () => {
+ const runtime = createRuntime();
+ const internals = runtime as any;
+ const agent = internals.agent as Agent;
+ const system = { ...agent.state.messages[0], timestamp: 1_000 };
+ const assistant = { ...assistantMessage({ content: [{ type: "text", text: "done" }] }), timestamp: 2_000 };
+ agent.state.messages = [system, assistant] as any;
+ vi.spyOn(internals, "liveSessionContext").mockReturnValue({ messages: [assistant] });
+
+ const rebuilt = internals.rebuiltAgentContext();
+
+ expect(estimateTranscriptTokens(rebuilt.messages).usageTokens).toBe(2);
+ expect(rebuilt.messages[0]).toBe(system);
+ expect(getCurrentTools(rebuilt.messages)).toEqual(agent.state.tools.map(toToolDeclaration));
+ expect(internals.rebuiltAgentContext().messages[0]).toBe(system);
+ await runtime.dispose();
+ });
+
+ it("does not flatten sections or erase tool deltas when the prompt is unchanged", async () => {
+ const runtime = createRuntime();
+ const internals = runtime as any;
+ const agent = internals.agent as Agent;
+ const messages = [
+ { ...agent.state.messages[0], timestamp: 1_000, sections: { rules: "Keep these rules." } },
+ { role: "system", content: "", timestamp: 1_500, toolsRemoved: [{ name: agent.state.tools[0]!.name }] },
+ ];
+ agent.state.messages = messages as any;
+
+ internals.setAgentSystemPrompt(agent.state.systemPrompt);
+
+ expect(agent.state.messages).toEqual(messages);
+ expect(agent.state.messages[0]).toBe(messages[0]);
+ await runtime.dispose();
+ });
+
+ it("keeps a fresh restore prefix stable without claiming it predates history", async () => {
+ const before = Date.now();
+ const runtime = createRuntime({ history: [
+ { id: "old-user", role: "user", content: "Earlier task", createdAt: new Date(before - 2_000).toISOString(), status: "complete" },
+ { id: "old-assistant", role: "assistant", content: "Earlier answer", createdAt: new Date(before - 1_000).toISOString(), status: "complete" },
+ ] });
+ const internals = runtime as any;
+ const prefix = internals.agent.state.messages[0];
+ expect(prefix.timestamp).toBeGreaterThanOrEqual(before);
+ const rebuilt = internals.rebuiltAgentContext();
+ expect(rebuilt.messages[0]).toBe(prefix);
+ expect(getCurrentTools(rebuilt.messages)).toEqual(rebuilt.tools.map(toToolDeclaration));
+ await runtime.dispose();
+ });
+
+ it.each([
+ ["pendingSilentTurnRerun", "rerunSilentTurn", "no_output_recovery"],
+ ["pendingProgressTurnRerun", "rerunProgressOnlyTurn", "progress_only_recovery"],
+ ])("preserves structured system state through %s and its cleanup", async (pending, method, marker) => {
+ const runtime = createRuntime();
+ const internals = runtime as any;
+ const agent = internals.agent as Agent;
+ agent.state.messages[0] = { ...agent.state.messages[0], sections: { rules: "SECTION_MARKER" } } as any;
+ const before = agent.state.systemPrompt;
+ const tools = getCurrentTools(agent.state.messages);
+ agent.state.messages.push({ role: "user", content: "question", timestamp: Date.now() });
+ agent.state.messages.push(assistantMessage({ content: [] }) as any);
+ vi.spyOn(internals, "waitForIdleAndSteering").mockResolvedValue(undefined);
+ const response = assistantMessage({ content: [{ type: "text", text: "Recovered answer" }] });
+ vi.spyOn(agent, "continue").mockImplementation(async () => {
+ expect(agent.state.systemPrompt).toContain(marker);
+ expect(agent.state.systemPrompt.split("SECTION_MARKER")).toHaveLength(2);
+ expect(getCurrentSystemMessage(agent.state.messages)?.sections).toEqual({ rules: "SECTION_MARKER" });
+ expect(getCurrentTools(agent.state.messages)).toEqual(tools);
+ response.timestamp = agent.state.messages[0]!.timestamp + 10;
+ agent.state.messages.push(response as any);
+ });
+ internals[pending] = true;
+
+ await internals[method]();
+
+ expect(agent.continue).toHaveBeenCalledOnce();
+ expect(agent.state.systemPrompt).toBe(before);
+ expect(getCurrentSystemMessage(agent.state.messages)?.sections).toEqual({ rules: "SECTION_MARKER" });
+ expect(getCurrentTools(agent.state.messages)).toEqual(tools);
+ expect(estimateTranscriptTokens(agent.state.messages as any).usageTokens).toBe(0);
+ await runtime.dispose();
+ });
+});
+
describe("custom system prompt files (issue #542)", () => {
const persona = "You are Custom, a specialized assistant.";
const appendix = "MARKER-XYZ-123 Always end with the marker.";
@@ -2011,6 +2103,10 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {
expect(next.context.tools.some((tool: any) => tool.name === "BrowserPreview")).toBe(
true,
);
+ // Tool deltas append new declarations; catalog order is not semantic.
+ expect([...getCurrentTools(next.context.messages)].sort((a, b) => a.name.localeCompare(b.name))).toEqual(
+ next.context.tools.map(toToolDeclaration).sort((a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name)),
+ );
await runtime.dispose();
});
@@ -2036,6 +2132,7 @@ describe("DesktopAgentRuntime deferred tool catalog", () => {
expect(agent.state.tools.some((tool: any) => tool.name === "BrowserPreview")).toBe(
false,
);
+ expect(getCurrentTools(agent.state.messages)).toEqual(agent.state.tools.map(toToolDeclaration));
});
});
@@ -3765,6 +3862,70 @@ describe("DesktopAgentRuntime assistant thinking events", () => {
await runtime.dispose();
});
+ it.each(["context-validation", "context-estimation", "request-preparation"])(
+ "terminates a local %s failure without retry or overflow recovery",
+ async (phase) => {
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const internal = runtime as any;
+ internal.providerResponseStatus = 429;
+ internal.infiniteProviderRetry = true;
+ const claim = vi.spyOn(internal, "claimProviderRetry");
+ const message = {
+ ...assistantMessage({ content: [], stopReason: "error" }),
+ errorMessage: "context length exceeded; fetch failed; private request body",
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR",
+ phase,
+ message: "private request body",
+ causeName: "TypeError",
+ },
+ };
+ await internal.handleAgentEvent({ type: "message_start", message });
+ await internal.handleAgentEvent({ type: "message_end", message });
+ const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);
+ const failure = events.find((event) => event.type === "error");
+ expect(failure?.error).toMatchObject({
+ code: "INTERNAL",
+ retriable: false,
+ details: { origin: "local", phase, causeName: "TypeError" },
+ });
+ expect(failure?.error.details).not.toHaveProperty("providerStatus");
+ expect(JSON.stringify(events)).not.toContain("private request body");
+ expect(events.filter((event) => event.type === "error")).toHaveLength(1);
+ expect(events.find((event) => event.type === "message_end")?.message.status).toBe("error");
+ expect(claim).not.toHaveBeenCalled();
+ expect(internal.pendingProviderRetry).toBeUndefined();
+ expect(internal.pendingOverflow).toBe(false);
+ expect(internal.providerTransientRetryAttempt).toBe(0);
+ expect(internal.providerRateLimitRetryAttempt).toBe(0);
+ await runtime.dispose();
+ },
+ );
+
+ it("preserves cancellation carried by a local preparation error", async () => {
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const internal = runtime as any;
+ const message = {
+ ...assistantMessage({ content: [], stopReason: "error" }),
+ errorMessage: "local preparation cancelled",
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR",
+ phase: "request-preparation",
+ message: "cancelled",
+ causeName: "AbortError",
+ },
+ };
+ await internal.handleAgentEvent({ type: "message_start", message });
+ await internal.handleAgentEvent({ type: "message_end", message });
+ const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);
+ expect(events.find((event) => event.type === "message_end")?.message.status).toBe("aborted");
+ expect(events.some((event) => event.type === "error")).toBe(false);
+ expect(internal.pendingProviderRetry).toBeUndefined();
+ await runtime.dispose();
+ });
+
it("turns a provider model failure into an error message and event", async () => {
const onEvent = vi.fn();
const runtime = createRuntime({ onEvent });
@@ -4706,8 +4867,14 @@ describe("DesktopAgentRuntime compaction restore", () => {
const budget = (runtime as any).contextBudget(
(runtime as any).agent.state.messages,
);
- expect(budget.tokens).toBeLessThan(1_000);
- expect(budget.tokens).not.toBe(250_000);
+ // System sections and tool declarations now participate in the estimate;
+ // the invariant is that the old response's 250k usage is not reused.
+ const estimate = estimateAgentContextTokens((runtime as any).agent.state.messages);
+ expect(estimate.usageTokens).toBe(0);
+ expect(estimate.lastUsageIndex).toBeNull();
+ expect(budget.tokens).toBe(estimate.tokens);
+ expect(budget.tokens).toBeGreaterThan(0);
+ expect(budget.tokens).toBeLessThan(250_000);
await runtime.dispose();
});
});
@@ -6017,11 +6184,18 @@ describe("DesktopAgentRuntime inline context compaction", () => {
: overBudget()) as never,
);
const generateCompaction = vi.spyOn(runtime as any, "generateCompaction");
+ const agent = (runtime as any).agent as Agent;
+ const prefix = { ...agent.state.messages[0], sections: { rules: "Keep checkpoint rules" } };
+ agent.state.messages[0] = prefix as any;
await (runtime as any).prepareNextTurn(nextTurn);
// The point of this family: the window is bought back without paying for a
// summary, so no provider request is made at all.
+ expect(agent.state.messages[0]).toBe(prefix);
+ expect(getCurrentTools(agent.state.messages)).toEqual(agent.state.tools.map(toToolDeclaration));
+ expect(getCurrentSystemMessage(agent.state.messages)?.sections).toEqual({ rules: "Keep checkpoint rules" });
+ expect((runtime as any).rebuiltAgentContext().messages[0]).toBe(prefix);
expect(generateCompaction).not.toHaveBeenCalled();
const compaction = host.call.mock.calls.find(
([method]) => method === "session.appendCompaction",
@@ -8588,7 +8762,7 @@ describe("DesktopAgentRuntime hosted web search rounds (ADR 0297)", () => {
blockId: "srvtoolu_01",
wire: {
type: "web_search_tool_result",
- encrypted_content: "enc-1",
+ content: [{ type: "web_search_result", encrypted_content: "enc-1", title: "News", url: "https://example.test/news" }],
},
},
],
@@ -8611,7 +8785,11 @@ describe("DesktopAgentRuntime hosted web search rounds (ADR 0297)", () => {
type: "hostedSearch",
phase: "web_search_tool_result",
blockId: "srvtoolu_01",
- wire: { type: "web_search_tool_result", encrypted_content: "enc-1" },
+ isError: false,
+ wire: {
+ type: "web_search_tool_result",
+ content: [{ type: "web_search_result", encrypted_content: "enc-1", title: "News", url: "https://example.test/news" }],
+ },
},
{ type: "text", text: "here is the news" },
]);
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 1877654ac..d9a19eb80 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1,3 +1,5 @@
+import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
+import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { randomUUID } from "node:crypto";
@@ -124,6 +126,13 @@ import {
usageToPi,
} from "./agent-messages.js";
import { buildSessionContext } from "./session-context.js";
+import {
+ initialSystemTranscript,
+ rebuildSystemTranscript,
+ replaceSystemPrompt,
+ syncSystemTools,
+ systemPromptContent,
+} from "./system-transcript.js";
import {
dedupeToolCallMessages,
reportDuplicateToolCallDrop,
@@ -1816,8 +1825,11 @@ Delegation rules:
// Park what this request is expected to cost, so the usage report that
// settles it can be measured against it (`contextBudget` corrects the
// same shape).
+ // The target model travels with the estimate: hosted search only
+ // costs what this model's adapter will actually replay.
this.inFlightContextEstimate = estimateContextTokens(
context.messages ?? [],
+ m,
);
// A new model request starts a new transport streak: the evidence that
// justified a rebuild does not carry into the next request (issue #234).
@@ -1934,11 +1946,10 @@ Delegation rules:
this.prepareNextTurn(context, signal),
afterToolCall: async (context) => this.afterToolCall(context),
initialState: {
- systemPrompt: this.composeSystemPrompt(),
model,
tools,
thinkingLevel: agentThinkingLevel(this.thinkingLevel),
- messages: this.liveSessionContext().messages,
+ messages: initialSystemTranscript(this.composeSystemPrompt(), tools, this.liveSessionContext().messages),
},
// Plan transitions must be the only tool call in an assistant batch.
// Sequential execution also makes the host-confirmed mode change visible
@@ -2006,7 +2017,7 @@ Delegation rules:
this.rebuildToolCatalog();
this.restoreDeferredToolsFromContext();
this.setAgentSystemPrompt(this.composeSystemPrompt());
- this.agent.state.tools = this.activeTools();
+ this.setAgentTools(this.activeTools());
this.setPlanningState(planningState, details);
}
@@ -2029,11 +2040,7 @@ Delegation rules:
(this.agent.state as unknown as { systemPrompt: string }).systemPrompt = prompt;
return;
}
- const messages = this.agent.state.messages.filter((message) => message.role !== "system");
- this.agent.state.messages = [
- { role: "system", content: prompt, timestamp: Date.now() },
- ...messages,
- ];
+ this.agent.state.messages = replaceSystemPrompt(this.agent.state.messages, prompt);
}
private setAgentMessages(messages: AgentMessage[]): void {
@@ -2041,11 +2048,23 @@ Delegation rules:
this.agent.state.messages = messages;
return;
}
- const systemPrompt = this.agent.state.systemPrompt;
- this.agent.state.messages = [
- { role: "system", content: systemPrompt, timestamp: Date.now() },
- ...messages.filter((message) => message.role !== "system"),
- ];
+ this.agent.state.messages = syncSystemTools(
+ rebuildSystemTranscript(this.agent.state.messages, messages),
+ this.agent.state.tools,
+ );
+ }
+
+ private setAgentTools(tools: AgentTool[]): void {
+ this.agent.state.tools = tools;
+ if (this.agentUsesTranscriptSystemMessages()) {
+ this.agent.state.messages = syncSystemTools(this.agent.state.messages, tools);
+ }
+ }
+
+ private agentSystemPromptContent(): string {
+ return this.agentUsesTranscriptSystemMessages()
+ ? systemPromptContent(this.agent.state.messages)
+ : this.agent.state.systemPrompt;
}
private composeSystemPrompt(): string {
@@ -2084,7 +2103,7 @@ Delegation rules:
if (this.subagents.length === 0) return;
if (!this.agent) return;
if (this.composedSystemPrompt === undefined) return;
- if (this.agent.state.systemPrompt !== this.composedSystemPrompt) {
+ if (this.agentSystemPromptContent() !== this.composedSystemPrompt) {
// A transient variant (the delegation nudge) owns the live prompt. Its
// own cleanup restores the composed text, and applies this refresh then,
// so a chain that settled mid-nudge is still listed on the next turn.
@@ -2355,7 +2374,7 @@ Delegation rules:
await runner.load();
if (this.disposed) return;
this.rebuildToolCatalog();
- this.agent.state.tools = this.activeTools();
+ this.setAgentTools(this.activeTools());
}
/** Run a registered extension slash command in this session (spec 16 §8). */
@@ -2499,7 +2518,7 @@ Delegation rules:
if (wanted.has(name)) runtime.activeDeferredToolNames.add(name);
else runtime.activeDeferredToolNames.delete(name);
}
- runtime.agent.state.tools = runtime.activeTools();
+ runtime.setAgentTools(runtime.activeTools());
},
getSessionName: () => runtime.extensionSessionName,
setSessionName: async (name) => {
@@ -2659,15 +2678,7 @@ Delegation rules:
: {}),
});
}
- const replay = m.hostedSearch?.replay;
- if (Array.isArray(replay)) {
- for (const block of replay) {
- if (!block || typeof block !== "object" || block.type !== "hostedSearch") {
- continue;
- }
- content.push(block as unknown as AssistantMessage["content"][number]);
- }
- }
+ content.push(...restoreHostedSearchReplay(m.hostedSearch));
if (m.content?.trim()) {
content.push({ type: "text" as const, text: m.content });
}
@@ -5003,7 +5014,7 @@ Delegation rules:
private resetDeferredToolsForPrompt(): void {
this.activeDeferredToolNames.clear();
this.restoreDeferredToolsFromContext();
- this.agent.state.tools = this.activeTools();
+ this.setAgentTools(this.activeTools());
}
/**
@@ -5398,7 +5409,7 @@ Delegation rules:
error: ReturnType<typeof classifyAgentError>,
phase: "request" | "stream",
): number | undefined {
- if (!error.retriable) return undefined;
+ if (!error.retriable || error.details?.origin === "local") return undefined;
const infinite = this.infiniteProviderRetry;
if (error.code === "PROVIDER_RATE_LIMITED") {
if (
@@ -5435,6 +5446,9 @@ Delegation rules:
providerWaitMs?: number,
streamMs?: number,
): ReturnType<typeof classifyAgentError> {
+ // Local preparation never reached the provider: keep its phase and cause
+ // instead of attaching stale HTTP status or a synthetic stream phase.
+ if (error.details?.origin === "local") return error;
const explained = withProviderFetchFailure(error, this.providerFetchFailure);
const existingDetails = explained.details ?? {};
const retryAttempt = error.code === "PROVIDER_RATE_LIMITED"
@@ -5630,7 +5644,7 @@ Delegation rules:
while (messages.at(-1)?.role === "assistant") messages.pop();
this.setAgentMessages(messages);
- const promptBefore = this.agent.state.systemPrompt;
+ const promptBefore = this.agentSystemPromptContent();
const promptWithNudge = `${promptBefore}\n\n${SILENT_TURN_NUDGE}`;
this.setAgentSystemPrompt(promptWithNudge);
this.silentTurnRerunInProgress = true;
@@ -5641,7 +5655,7 @@ Delegation rules:
await this.agent.continue();
await this.waitForIdleAndSteering();
} finally {
- if (this.agent.state.systemPrompt === promptWithNudge) {
+ if (this.agentSystemPromptContent() === promptWithNudge) {
this.setAgentSystemPrompt(promptBefore);
}
this.applyPendingResumablePrompt();
@@ -5738,7 +5752,7 @@ Delegation rules:
while (messages.at(-1)?.role === "assistant") messages.pop();
this.setAgentMessages(messages);
- const promptBefore = this.agent.state.systemPrompt;
+ const promptBefore = this.agentSystemPromptContent();
const promptWithNudge = `${promptBefore}\n\n${PROGRESS_TURN_NUDGE}`;
this.setAgentSystemPrompt(promptWithNudge);
this.progressTurnRerunInProgress = true;
@@ -5750,7 +5764,7 @@ Delegation rules:
await this.agent.continue();
await this.waitForIdleAndSteering();
} finally {
- if (this.agent.state.systemPrompt === promptWithNudge) {
+ if (this.agentSystemPromptContent() === promptWithNudge) {
this.setAgentSystemPrompt(promptBefore);
}
this.applyPendingResumablePrompt();
@@ -5768,7 +5782,7 @@ Delegation rules:
this.compactionEnabled = compactionEnabled(settings);
this.pendingModelCompaction = false;
this.rebuildToolCatalog();
- this.agent.state.tools = this.activeTools();
+ this.setAgentTools(this.activeTools());
}
private contextBudget(messages: AgentMessage[]): ContextBudget {
@@ -5780,7 +5794,11 @@ Delegation rules:
// is bounded by `CONTEXT_CALIBRATION_FACTOR_MIN`.
return {
...budget,
- tokens: this.contextCalibration.correct(estimateContextTokens(messages)),
+ // Same target model as `contextBudgetFor` above: the calibration input
+ // must describe the request this runtime will actually send.
+ tokens: this.contextCalibration.correct(
+ estimateContextTokens(messages, this.model),
+ ),
};
}
@@ -5937,7 +5955,7 @@ Delegation rules:
const messages = this.liveSessionContext().messages;
const tools = this.activeTools();
this.setAgentMessages(messages);
- this.agent.state.tools = tools;
+ this.setAgentTools(tools);
return {
messages: this.agent.state.messages,
tools,
@@ -6772,15 +6790,11 @@ Delegation rules:
* Search state transitions are low frequency, so a full frame costs less
* than teaching every delta path about the field.
*/
- private applyHostedSearch(message: unknown): void {
+ private applyHostedSearch(message: AssistantMessage): void {
if (!this.currentAssistant) return;
- const record = message as {
- content?: unknown;
- hostedSearchCitations?: unknown;
- };
const next = hostedSearchFromMessage({
- content: record?.content,
- citations: record?.hostedSearchCitations,
+ content: message.content,
+ citations: message.hostedSearchCitations,
});
if (!next) return;
const previous = this.currentAssistant.hostedSearch;
@@ -6934,15 +6948,14 @@ Delegation rules:
// pi-agent-core encodes stream failures in the final message
// (stopReason "error"/"aborted" + errorMessage) and resolves the
// prompt normally, so this is where provider/model errors surface.
- const stopReason = (event.message as any).stopReason as
- | string
- | undefined;
- const overflow = isContextOverflow(
- event.message as AssistantMessage,
+ const stopReason = event.message.stopReason;
+ const localError = readLocalRequestErrorDetails(event.message);
+ const overflow = !localError && isContextOverflow(
+ event.message,
effectiveModelContextWindow(this.model) || DEFAULT_CONTEXT_WINDOW,
);
- const failed = stopReason === "error" || overflow;
- const aborted = stopReason === "aborted";
+ const aborted = stopReason === "aborted" || localError?.causeName === "AbortError";
+ const failed = !aborted && (stopReason === "error" || overflow);
const errorMessage =
failed &&
typeof (event.message as any).errorMessage === "string" &&
@@ -6961,7 +6974,7 @@ Delegation rules:
retriable: false,
}
: errorMessage
- ? classifyProviderError(errorMessage, this.providerResponseStatus)
+ ? classifyProviderError(event.message, this.providerResponseStatus)
: undefined;
const nextText = content.hasText
? content.text
@@ -6989,8 +7002,8 @@ Delegation rules:
// failed attempt cannot pair with a later usage report.
this.recordContextCalibration(usage, failed || aborted);
const hostedSearch = hostedSearchFromMessage({
- content: (event.message as any).content,
- citations: (event.message as any).hostedSearchCitations,
+ content: event.message.content,
+ citations: event.message.hostedSearchCitations,
});
if (hostedSearch) {
const terminal = failed || aborted ? "failed" : "completed";
@@ -7117,7 +7130,8 @@ Delegation rules:
const diagnosticError = classifiedError;
const retryProviderAttempt =
!overflow &&
- diagnosticError !== undefined
+ diagnosticError !== undefined &&
+ diagnosticError.details?.origin !== "local"
? this.claimProviderRetry(diagnosticError, "stream")
: undefined;
if (
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index fcff5a285..63d81da17 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -11,6 +11,7 @@ import type { ModelAuth } from "@earendil-works/pi-ai";
import { ParentHostProxy } from "./parent-host-proxy.js";
import { visionFromModelConfig } from "./model-capabilities.js";
import { classifyAgentError } from "./agent-errors.js";
+import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import {
DesktopAgentRuntime,
type PluginToolDef,
@@ -695,10 +696,15 @@ readNdjsonLines(process.stdin, async (line) => {
const result = await handle(msg.method, msg.params ?? {});
respond(msg.id, result);
} catch (err: any) {
+ // Restore validation can fail before a runtime/stream exists. Preserve its
+ // safe provenance in the existing RPC error data instead of flattening it.
+ const local = readLocalRequestErrorDetails(err) ? classifyAgentError(err) : undefined;
respond(msg.id, undefined, {
code: err.rpcCode ?? -32000,
- message: err instanceof Error ? err.message : String(err),
- data: { errorCode: err.errorCode ?? "INTERNAL" },
+ message: local?.message ?? (err instanceof Error ? err.message : String(err)),
+ data: local
+ ? { errorCode: local.code, retriable: local.retriable, details: local.details }
+ : { errorCode: err.errorCode ?? "INTERNAL" },
});
}
});
diff --git a/packages/agent-runtime/src/subagent-context.test.ts b/packages/agent-runtime/src/subagent-context.test.ts
index d361f4461..fa3b04dc1 100644
--- a/packages/agent-runtime/src/subagent-context.test.ts
+++ b/packages/agent-runtime/src/subagent-context.test.ts
@@ -353,6 +353,24 @@ describe("prepareDelegateTurnContext", () => {
});
describe("degradedDelegateMessages", () => {
+ it("charges retained search only when the target adapter replays it", () => {
+ const target: Model<Api> = { ...smallModel(), api: "openai-responses" };
+ const brief = userMessage("Keep the useful answer.");
+ const search: AssistantMessage = {
+ ...assistantText("useful answer"), api: target.api,
+ content: [
+ { type: "hostedSearch", phase: "web_search_call", blockId: "ws", wire: {
+ type: "web_search_call", id: "ws", status: "completed", action: { type: "search", query: "x".repeat(20_000) },
+ } },
+ { type: "text", text: "useful answer" },
+ ],
+ };
+ const messages = [brief, search];
+ expect(degradedDelegateMessages(messages, "brief", target)).toEqual([brief]);
+ expect(degradedDelegateMessages(messages, "brief", { ...target, id: "other-model" })).toEqual(messages);
+ expect(degradedDelegateMessages(messages, "brief", { contextWindow: target.contextWindow, maxTokens: target.maxTokens })).toEqual([brief]);
+ });
+
it("keeps the brief plus the most recent complete exchanges that still fit", () => {
const brief = userMessage("Survey the module.");
const exchange = (id: string, text: string): AgentMessage[] => [
diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.ts
index 42d1fd2fe..e4df24c06 100644
--- a/packages/agent-runtime/src/subagent-context.ts
+++ b/packages/agent-runtime/src/subagent-context.ts
@@ -42,6 +42,7 @@ import {
retainedUserMessageBudget,
type ContextBudget,
type ContextBudgetModel,
+ type ContextBudgetModelInput,
} from "./context-budget.js";
import {
COMPACTION_SUMMARY_RETRY_POLICY,
@@ -281,7 +282,7 @@ async function compactDelegateContext(
export function degradedDelegateMessages(
messages: AgentMessage[],
taskBrief: string,
- model: ContextBudgetModel,
+ model: ContextBudgetModelInput,
): AgentMessage[] | undefined {
const limits = contextBudgetLimitsFor(model);
const briefIndex = messages.findIndex((message) => message.role === "user");
@@ -289,7 +290,8 @@ export function degradedDelegateMessages(
briefIndex >= 0
? (messages[briefIndex] as UserMessage)
: { role: "user", content: taskBrief, timestamp: Date.now() };
- const briefTokens = estimateTokens(brief);
+ const target = "api" in model ? model : undefined;
+ const briefTokens = estimateTokens(brief, target);
if (briefTokens >= limits.hardLimit) return undefined;
const pool = messages.slice(briefIndex + 1);
@@ -298,7 +300,7 @@ export function degradedDelegateMessages(
for (let index = pool.length - 1; index >= 0; index -= 1) {
const message = pool[index];
if (!isDelegateContextMessage(message)) continue;
- const cost = estimateTokens(message);
+ const cost = estimateTokens(message, target);
if (tokens + cost >= limits.hardLimit) break;
suffix.unshift(message);
tokens += cost;
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index 842e9e256..589963161 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -381,6 +381,124 @@ describe("SubagentRun reporting", () => {
});
describe("SubagentRun provider rate-limit recovery", () => {
+ it("does not switch models or continue after an explicitly local failure", async () => {
+ const { run } = createRun({ fallbackModels: [{
+ key: "fallback/model", provider: { ...provider, id: "fallback", modelId: "model" },
+ }] });
+ const failure = {
+ ...assistantMessage({ content: [], stopReason: "error" }),
+ errorMessage: "local preparation failed",
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR", phase: "request-preparation", message: "failed",
+ },
+ };
+ const continueRun = vi.fn(async () => undefined);
+ run.agent = {
+ state: { messages: [failure] },
+ prompt: vi.fn(async () => {
+ run.handleEvent({ type: "message_start", message: failure });
+ run.handleEvent({ type: "message_end", message: failure });
+ }),
+ waitForIdle: vi.fn(async () => undefined), continue: continueRun, abort: vi.fn(),
+ };
+ // Isolate fallback from the retry check covered below.
+ vi.spyOn(run, "claimProviderRetry").mockReturnValue(undefined);
+ const result = await run.run();
+ expect(continueRun).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ status: "failed", error: { code: "INTERNAL" } });
+ expect(run.provider.id).toBe("local");
+ });
+
+ it("keeps local message metadata terminal even with infinite retries and stale 429 state", () => {
+ const { run, events } = createRun({ infiniteProviderRetry: true });
+ const failure = {
+ ...assistantMessage({ content: [], stopReason: "error" }),
+ errorMessage: "fetch failed: private prompt api_key=test-secret",
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR", phase: "context-estimation",
+ message: "private payload", causeName: "TypeError",
+ },
+ };
+ run.retryState.status = 429;
+ const claim = vi.spyOn(run, "claimProviderRetry");
+ run.handleEvent({ type: "message_start", message: failure });
+ run.handleEvent({ type: "message_end", message: failure });
+ expect(claim).not.toHaveBeenCalled();
+ expect(run.pendingProviderRetry).toBeUndefined();
+ expect(run.providerTransientRetryAttempt).toBe(0);
+ expect(run.providerRateLimitRetryAttempt).toBe(0);
+ expect(run.streamError).toMatchObject({ code: "INTERNAL" });
+ expect(events.at(-1)?.event).toMatchObject({
+ type: "message_end",
+ message: {
+ status: "error", isError: true,
+ error: {
+ code: "INTERNAL", retriable: false,
+ details: { origin: "local", phase: "context-estimation", causeName: "TypeError" },
+ },
+ },
+ });
+ expect(JSON.stringify(events)).not.toMatch(/private|test-secret|stack/);
+ });
+
+ it("reads a local AbortError marker as an abort without retrying or an error row", async () => {
+ // pi-ai wraps an AbortError that fired before the parent signal flipped in
+ // a local marker; the preserved cause name is the only trace of the Stop,
+ // so the run has to report the same abort the session runtime would.
+ const controller = new AbortController();
+ const { run, events } = createRun({
+ signal: controller.signal,
+ infiniteProviderRetry: true,
+ fallbackModels: [{
+ key: "fallback/model",
+ provider: { ...provider, id: "fallback", modelId: "model" },
+ }],
+ });
+ const failure = {
+ ...assistantMessage({ content: [], stopReason: "error" }),
+ errorMessage: "local request preparation failed",
+ errorDetails: {
+ code: "LOCAL_REQUEST_ERROR",
+ phase: "request-preparation",
+ causeName: "AbortError",
+ },
+ };
+ const continueRun = vi.fn(async () => undefined);
+ run.agent = {
+ state: { messages: [failure] },
+ prompt: vi.fn(async () => {
+ run.handleEvent({ type: "message_start", message: failure });
+ run.handleEvent({ type: "message_end", message: failure });
+ }),
+ waitForIdle: vi.fn(async () => undefined),
+ continue: continueRun,
+ abort: vi.fn(),
+ };
+ const claim = vi.spyOn(run, "claimProviderRetry");
+
+ const result = await run.run();
+
+ // The synthetic message reports the abort while the parent signal is still
+ // open, so nothing but the marker can explain the terminal status.
+ expect(controller.signal.aborted).toBe(false);
+ expect(result.status).toBe("aborted");
+ expect(result.error).toBeUndefined();
+ expect(claim).not.toHaveBeenCalled();
+ expect(run.pendingProviderRetry).toBeUndefined();
+ expect(run.streamError).toBeUndefined();
+ expect(continueRun).not.toHaveBeenCalled();
+ expect(run.provider.id).toBe("local");
+ expect(events.map((event) => event.event.type)).toEqual([
+ "message_start",
+ "message_end",
+ ]);
+ const row = (events[1].event as { message: Record<string, unknown> }).message;
+ expect(row.status).toBe("aborted");
+ expect(row.isError).toBeUndefined();
+ expect(row.error).toBeUndefined();
+ });
+
+
it("retries ten 429s silently and reuses one assistant row", async () => {
const { run, events } = createRun();
const failure = {
@@ -808,7 +926,11 @@ describe("SubagentRun retries before fallback", () => {
};
run.agent = {
state,
- prompt: async () => { state.messages = [{ role: "user", content: "task" }]; await attempt(); },
+ prompt: async () => {
+ const user: Message = { role: "user", content: "task", timestamp: 1 };
+ state.messages = [user];
+ await attempt();
+ },
continue: attempt,
waitForIdle: async () => {},
abort: () => {},
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 60390bc79..ed46b8441 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -46,6 +46,7 @@ import {
type UiMessage,
} from "@pi-desktop/shared";
import { classifyAgentError } from "./agent-errors.js";
+import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import { withProviderFetchFailure } from "./provider-transport-recovery.js";
import {
assistantContent,
@@ -218,6 +219,11 @@ export class SubagentRun {
private toolCalls = 0;
private usage?: MessageUsage;
private streamError?: { code: string; message: string };
+ /** Set when a settled message reads as a cancel — `stopReason: "aborted"`, or
+ * a local marker whose preserved cause name is `AbortError`. pi-ai can wrap
+ * an abort that fired before the parent signal flipped, so this is the only
+ * trace of the Stop and the run has to report `aborted` from it. */
+ private turnAborted = false;
private contextCompactions = 0;
private contextDegraded = false;
/** Set when the turn-boundary guard throws because even the degraded
@@ -300,6 +306,14 @@ export class SubagentRun {
if (signal?.aborted) {
return this.result("aborted", "The delegated task was aborted.");
}
+
+ // A cancel the settled message itself reported outranks any failure text:
+ // pi-ai can wrap an AbortError that fired before the parent signal flipped,
+ // and the marker's preserved cause name is the only trace of the Stop. The
+ // session runtime reads that same marker as an aborted turn.
+ if (this.turnAborted) {
+ return this.result("aborted", "The delegated task was aborted.");
+ }
if (caughtError) {
if (caughtError.code === "TURN_ABORTED") {
return this.result("aborted", "The delegated task was aborted.");
@@ -397,12 +411,15 @@ export class SubagentRun {
/** Continue the same agent at the failed request; never replay completed tools. */
private useNextModel(): boolean {
- if (this.runSignal().aborted || !this.streamError || this.streamError.code === "TURN_ABORTED") return false;
+ // An aborted turn never continues, whether the signal flipped yet or the
+ // cancel was only visible on the settled message.
+ if (this.runSignal().aborted || this.turnAborted || !this.streamError || this.streamError.code === "TURN_ABORTED") return false;
if (!this.opts.fallbackModels?.length) return false;
const failed = this.agent.state.messages.at(-1);
// Only a provider's terminal assistant error permits fallback. Host/tool
// failures, cancellation, and unexpected internal exceptions do not.
if (failed?.role !== "assistant" || failed.stopReason !== "error") return false;
+ if (readLocalRequestErrorDetails(failed)) return false;
this.recordModelFailure(`${this.provider.id}/${this.provider.modelId}`, this.streamError);
// What an alternative would actually carry: the current context minus the
// failed assistant row (ADR 0299 decision 6 re-evaluates it against each
@@ -702,7 +719,16 @@ export class SubagentRun {
const message = event.message as AssistantMessage;
const content = assistantContent(message.content);
const stopReason = message.stopReason as string | undefined;
- const failed = stopReason === "error";
+ // Read the cancel off the settled message, the same way the session
+ // runtime does: pi-ai wraps an AbortError that fired before the signal
+ // flipped in a local marker whose preserved cause name is the only
+ // trace of the Stop. An abort is not a failure, so it neither retries
+ // nor produces an error row; other local errors stay terminal below.
+ const localError = readLocalRequestErrorDetails(message);
+ const aborted =
+ stopReason === "aborted" || localError?.causeName === "AbortError";
+ if (aborted) this.turnAborted = true;
+ const failed = !aborted && stopReason === "error";
let classifiedError: ReturnType<typeof classifyAgentError> | undefined;
let retryAttempt: number | undefined;
if (failed) {
@@ -714,26 +740,22 @@ export class SubagentRun {
// actionable code instead of classifying it as a provider error.
this.streamError = overflow;
} else {
- const raw =
- typeof (message as { errorMessage?: unknown }).errorMessage === "string"
- ? ((message as { errorMessage?: string }).errorMessage as string)
- : "provider stream failed";
classifiedError = withProviderFetchFailure(
- classifyProviderError(raw, this.retryState.status),
+ classifyProviderError(message, this.retryState.status),
this.retryState.failure,
);
- retryAttempt = this.claimProviderRetry(classifiedError, "stream");
+ retryAttempt = classifiedError.details?.origin === "local"
+ ? undefined : this.claimProviderRetry(classifiedError, "stream");
if (retryAttempt !== undefined) {
this.pendingProviderRetry = classifiedError;
} else {
- this.streamError = {
- code: classifiedError.code,
- message: classifiedError.message,
- };
+ this.streamError = classifiedError.details?.origin === "local"
+ ? classifiedError
+ : { code: classifiedError.code, message: classifiedError.message };
}
}
}
- if (!failed && stopReason !== "aborted") {
+ if (!failed && !aborted) {
this.providerTransientRetryAttempt = 0;
this.providerRateLimitRetryAttempt = 0;
}
@@ -767,10 +789,11 @@ export class SubagentRun {
...(content.hasThinking && content.thinking
? { thinking: content.thinking }
: {}),
- status: failed ? "error" : stopReason === "aborted" ? "aborted" : "complete",
+ status: failed ? "error" : aborted ? "aborted" : "complete",
...(messageUsage ? { usage: messageUsage } : {}),
...(failed ? { isError: true } : {}),
- ...(isCertificateVerificationError(classifiedError?.details?.networkCode)
+ ...(classifiedError?.details?.origin === "local" ||
+ isCertificateVerificationError(classifiedError?.details?.networkCode)
? { error: classifiedError } : {}),
};
this.currentAssistant = undefined;
diff --git a/packages/agent-runtime/src/system-transcript.test.ts b/packages/agent-runtime/src/system-transcript.test.ts
new file mode 100644
index 000000000..0b5bf732e
--- /dev/null
+++ b/packages/agent-runtime/src/system-transcript.test.ts
@@ -0,0 +1,188 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Agent, convertToLlm, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
+import {
+ createAssistantMessageEventStream,
+ getCurrentSystemMessage,
+ getCurrentSystemPrompt,
+ getCurrentTools,
+ toToolDeclaration,
+ Type,
+ type AssistantMessage,
+ type SystemMessage,
+ type Tool,
+} from "@earendil-works/pi-ai";
+import { estimateContextTokens as estimateTranscriptTokens } from "@earendil-works/pi-ai/utils/estimate";
+import {
+ initialSystemTranscript,
+ rebuildSystemTranscript,
+ replaceSystemPrompt,
+ syncSystemTools,
+ systemPromptContent,
+} from "./system-transcript.js";
+
+const read: Tool = { name: "Read", description: "Read text", parameters: Type.Object({ path: Type.String() }) };
+const edit: Tool = { ...read, name: "Edit", description: "Edit text" };
+const initial: SystemMessage = {
+ role: "system", content: "Base instructions", timestamp: 1_000,
+ sections: { rules: "Keep these rules", obsolete: "Remove these rules" },
+ toolsAdded: [read, edit],
+};
+const delta: SystemMessage = {
+ role: "system", content: "Additional instructions", timestamp: 1_500,
+ sections: { rules: "Updated rules", obsolete: null },
+ toolsRemoved: [{ name: "Edit" }],
+};
+const assistant: AssistantMessage = {
+ role: "assistant", content: [{ type: "text", text: "done" }],
+ api: "openai-completions", provider: "local", model: "local-model", stopReason: "stop", timestamp: 2_000,
+ usage: {
+ input: 990, output: 10, cacheRead: 0, cacheWrite: 0, totalTokens: 1_000,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+};
+const user: AgentMessage = { role: "user", content: "continue", timestamp: 2_100 };
+
+function estimateContextTokens(messages: AgentMessage[]) {
+ return estimateTranscriptTokens(convertToLlm(messages));
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("system transcript helpers", () => {
+ it("replays sections and tool removals without giving an unchanged prefix a new timestamp", () => {
+ const previous = [initial, delta, assistant, user];
+ const rebuilt = rebuildSystemTranscript(previous, [assistant, user]);
+ expect(getCurrentSystemPrompt(rebuilt)).toBe(getCurrentSystemPrompt(previous));
+ expect(rebuilt[0]).toMatchObject({
+ content: "Base instructions\n\nAdditional instructions", timestamp: 1_500,
+ sections: { rules: "Updated rules" }, toolsAdded: [read],
+ });
+ expect(getCurrentSystemMessage(rebuilt)?.sections).not.toHaveProperty("obsolete");
+ expect(getCurrentTools(rebuilt)).toEqual([read]);
+ expect(estimateContextTokens(rebuilt).usageTokens).toBe(1_000);
+ expect(rebuildSystemTranscript(rebuilt, [assistant, user])[0]).toBe(rebuilt[0]);
+ });
+
+ it("does not resurrect usage predating a folded system delta", () => {
+ const newer = { ...delta, timestamp: 3_000 };
+ const rebuilt = rebuildSystemTranscript([initial, assistant, newer], [assistant]);
+ expect(rebuilt[0]?.timestamp).toBe(3_000);
+ expect(estimateContextTokens(rebuilt).lastUsageIndex).toBeNull();
+ });
+
+ it("keeps a complete recovery transcript and its deltas in place", () => {
+ const previous = [initial, assistant, delta, user, { ...assistant, stopReason: "error" as const }];
+ const retained = previous.slice(0, -1);
+ expect(rebuildSystemTranscript(previous, retained)).toBe(retained);
+ expect(syncSystemTools(retained, [read])).toBe(retained);
+ });
+
+ it("preserves object identity when setting either the same content or rendered prompt", () => {
+ const messages = [initial, delta, assistant];
+ expect(replaceSystemPrompt(messages, getCurrentSystemPrompt(messages))).toBe(messages);
+ expect(replaceSystemPrompt(messages, systemPromptContent(messages))).toBe(messages);
+ });
+
+ it("invalidates usage only on a real content change and preserves structured sections and tools", () => {
+ vi.spyOn(Date, "now").mockReturnValue(5_000);
+ const changed = replaceSystemPrompt([initial, delta, assistant], "Replacement instructions");
+ expect(changed[0]).toMatchObject({ content: "Replacement instructions", timestamp: 5_000, sections: { rules: "Updated rules" } });
+ expect(getCurrentTools(changed)).toEqual([read]);
+ expect(estimateContextTokens(changed).lastUsageIndex).toBeNull();
+ expect(replaceSystemPrompt(changed, "Replacement instructions")).toBe(changed);
+ expect(initial.content).toBe("Base instructions");
+ const response = { ...assistant, timestamp: 6_000 };
+ expect(estimateContextTokens(rebuildSystemTranscript(changed, [assistant, response])).usageTokens).toBe(1_000);
+ });
+
+ it("can clear content without clearing sections or tool declarations", () => {
+ const changed = replaceSystemPrompt([initial, delta, assistant], "");
+ expect(systemPromptContent(changed)).toBe("");
+ expect(getCurrentSystemMessage(changed)?.sections).toEqual({ rules: "Updated rules" });
+ expect(getCurrentTools(changed)).toEqual([read]);
+ });
+
+ it("restores a recovery prompt without flattening sections or backdating its response", () => {
+ vi.spyOn(Date, "now").mockReturnValue(5_000);
+ const messages = [initial, delta, assistant, user];
+ const before = systemPromptContent(messages);
+ const nudged = replaceSystemPrompt(messages, `${before}\n\nRecovery nudge`);
+ const response = { ...assistant, timestamp: 6_000 };
+ const restored = replaceSystemPrompt([...nudged, response], before);
+ expect(getCurrentSystemPrompt(restored)).toBe(getCurrentSystemPrompt(messages));
+ expect(getCurrentSystemMessage(restored)?.sections).toEqual({ rules: "Updated rules" });
+ expect(restored[0]?.timestamp).toBeGreaterThan(response.timestamp);
+ expect(estimateContextTokens(restored).usageTokens).toBe(0);
+ });
+
+ it("records tool additions, removals, and same-name schema replacements with fresh semantic time", () => {
+ vi.spyOn(Date, "now").mockReturnValue(5_000);
+ const replacement = { ...read, parameters: Type.Object({ file: Type.String() }) };
+ const messages = [initial, assistant];
+ const changed = syncSystemTools(messages, [replacement]);
+ expect(changed[1]).toMatchObject({ timestamp: 5_000, toolsAdded: [replacement], toolsRemoved: [{ name: "Read" }, { name: "Edit" }] });
+ expect(getCurrentTools(changed)).toEqual([replacement]);
+ expect(estimateContextTokens(changed).usageTokens).toBe(0);
+ expect(syncSystemTools(changed, [replacement])).toBe(changed);
+ const response = { ...assistant, timestamp: 6_000 };
+ expect(estimateContextTokens(rebuildSystemTranscript(changed, [assistant, response])).usageTokens).toBe(1_000);
+ const cleared = syncSystemTools(changed, []);
+ expect(getCurrentTools(rebuildSystemTranscript(cleared, [assistant]))).toEqual([]);
+ });
+
+ it("ignores executable-only tool changes instead of invalidating usage", () => {
+ const messages = [initial, assistant];
+ const executable = { ...read, label: "Read", execute: vi.fn() };
+ expect(syncSystemTools(messages, [executable, edit])).toBe(messages);
+ expect(estimateContextTokens(messages).usageTokens).toBe(1_000);
+ });
+
+ it("advances semantic time even if the clock shares a millisecond or moves backwards", () => {
+ vi.spyOn(Date, "now").mockReturnValue(2_000);
+ expect(replaceSystemPrompt([initial, assistant], "changed")[0]?.timestamp).toBe(2_001);
+ vi.spyOn(Date, "now").mockReturnValue(500);
+ expect(syncSystemTools([initial, assistant], [read])[1]?.timestamp).toBe(2_001);
+ });
+
+ it("initializes restored history conservatively without inventing an old timestamp", () => {
+ vi.spyOn(Date, "now").mockReturnValue(5_000);
+ const messages = initialSystemTranscript("Current config", [read], [assistant]);
+ expect(messages[0]).toMatchObject({ content: "Current config", toolsAdded: [read], timestamp: 5_000 });
+ expect(estimateContextTokens(messages).usageTokens).toBe(0);
+ const rebuilt = rebuildSystemTranscript(messages, [assistant]);
+ expect(rebuilt[0]).toBe(messages[0]);
+ expect(estimateContextTokens(rebuilt).usageTokens).toBe(0);
+ });
+
+ it("preserves the empty transcript when there is no system state", () => {
+ const messages: AgentMessage[] = [];
+ expect(initialSystemTranscript("", [], messages)).toBe(messages);
+ expect(rebuildSystemTranscript([], messages)).toBe(messages);
+ expect(syncSystemTools(messages, [])).toBe(messages);
+ expect(replaceSystemPrompt(messages, "")).toBe(messages);
+ });
+
+ it("does not trigger duplicate tool deltas in the real pi agent loop after a rebuild", async () => {
+ const tool: AgentTool = {
+ ...read, label: "Read", execute: async () => ({ content: [{ type: "text", text: "text" }], details: {} }),
+ };
+ const requests: AgentMessage[][] = [];
+ const agent = new Agent({
+ initialState: { tools: [tool], messages: [initial, delta, user] },
+ streamFn: async (_model, context) => {
+ requests.push(context.messages);
+ const stream = createAssistantMessageEventStream();
+ stream.push({ type: "done", reason: "stop", message: assistant });
+ return stream;
+ },
+ });
+ agent.state.messages = syncSystemTools(rebuildSystemTranscript(agent.state.messages, [user]), [tool]);
+ const prefix = agent.state.messages[0];
+ await agent.continue();
+ expect(agent.state.errorMessage).toBeUndefined();
+ expect(requests).toHaveLength(1);
+ expect(requests[0]?.filter((message) => message.role === "system")).toEqual([prefix]);
+ expect(getCurrentTools(requests[0]!)).toEqual([toToolDeclaration(tool)]);
+ expect(agent.state.messages.filter((message) => message.role === "system")).toEqual([prefix]);
+ });
+});
diff --git a/packages/agent-runtime/src/system-transcript.ts b/packages/agent-runtime/src/system-transcript.ts
new file mode 100644
index 000000000..28bd5028b
--- /dev/null
+++ b/packages/agent-runtime/src/system-transcript.ts
@@ -0,0 +1,94 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import {
+ contentText,
+ createInitialSystemMessage,
+ getCurrentSystemMessage,
+ getCurrentSystemPrompt,
+ getCurrentTools,
+ getToolStateChanges,
+ type SystemMessage,
+ type Tool,
+ toToolDeclaration,
+} from "@earendil-works/pi-ai";
+
+function systemMessages(messages: readonly AgentMessage[]): SystemMessage[] {
+ return messages.filter((message): message is SystemMessage => message.role === "system");
+}
+
+function nextSystemTimestamp(messages: readonly AgentMessage[]): number {
+ // 同一毫秒内也必须晚于旧响应;时钟回拨时只前移,不伪造早于 usage 的时间。
+ return messages.reduce((timestamp, message) => Math.max(timestamp, message.timestamp + 1), Date.now());
+}
+
+function currentSystemMessage(messages: readonly AgentMessage[]): SystemMessage | undefined {
+ const systems = systemMessages(messages);
+ if (systems.length < 2) return systems[0];
+ const current = getCurrentSystemMessage(systems)!;
+ // 上游折叠器保留第一条的时间,但 sections/工具删除可能来自较晚的 delta。
+ // 快照的语义时间必须覆盖所有贡献者,否则旧 usage 会被错误地重新激活。
+ return {
+ ...current,
+ timestamp: systems.reduce((timestamp, message) => Math.max(timestamp, message.timestamp), systems[0]!.timestamp),
+ };
+}
+
+/** The unrendered content, without flattening named sections into the prompt. */
+export function systemPromptContent(messages: readonly AgentMessage[]): string {
+ return contentText(getCurrentSystemMessage(messages)?.content ?? "");
+}
+
+export function initialSystemTranscript(
+ prompt: string,
+ tools: readonly Tool[],
+ messages: AgentMessage[],
+): AgentMessage[] {
+ const system = createInitialSystemMessage(prompt, tools.map(toToolDeclaration));
+ // 持久化历史不记录 system 状态,重启后无法证明新配置与旧请求相同。
+ // 保守使用实际初始化时间;不能沿用上游初始值 0 来让历史 usage 假装有效。
+ return system
+ ? [{ ...system, timestamp: nextSystemTimestamp(messages) }, ...messages]
+ : messages;
+}
+
+export function replaceSystemPrompt(messages: AgentMessage[], prompt: string): AgentMessage[] {
+ const current = currentSystemMessage(messages);
+ if (prompt === getCurrentSystemPrompt(messages) || prompt === contentText(current?.content ?? "")) {
+ return messages;
+ }
+ // prompt 只替换内容;命名 sections 与最终工具状态仍由上游 replay 负责。
+ // recovery 读写未渲染内容,避免把 sections 再嵌入 content 造成重复。
+ return [
+ { ...current, role: "system", content: prompt, timestamp: nextSystemTimestamp(messages) },
+ ...messages.filter((message) => message.role !== "system"),
+ ];
+}
+
+export function rebuildSystemTranscript(
+ previous: readonly AgentMessage[],
+ messages: AgentMessage[],
+): AgentMessage[] {
+ // recovery 传入完整 live transcript 的切片,保留其位置、对象及 delta,不重复加前缀。
+ if (messages.some((message) => message.role === "system")) return messages;
+ // durable projection 不含 system;用上游 replay 还原有效 sections 和工具集合,
+ // 而不是将渲染后的 systemPrompt 当成新消息。折叠不产生新的语义时间。
+ const system = currentSystemMessage(previous);
+ return system ? [system, ...messages] : messages;
+}
+
+export function syncSystemTools(messages: AgentMessage[], tools: readonly Tool[]): AgentMessage[] {
+ const changes = getToolStateChanges(getCurrentTools(messages), tools);
+ if (changes.toolsAdded.length === 0 && changes.toolsRemoved.length === 0) return messages;
+ // 真正的工具变化成为较新的前缀,旧 usage 因此失效。保留删除/同名替换的 delta,
+ // 并让声明集合与可执行 catalog 一致,避免 agent-loop 下一轮再次自动追加同一变化。
+ return [
+ ...systemMessages(messages),
+ {
+ role: "system",
+ content: "",
+ ...(changes.toolsAdded.length ? { toolsAdded: changes.toolsAdded } : {}),
+ ...(changes.toolsRemoved.length ? { toolsRemoved: changes.toolsRemoved } : {}),
+ timestamp: nextSystemTimestamp(messages),
+ },
+ ...messages.filter((message) => message.role !== "system"),
+ ];
+}
diff --git a/packages/host-runtime/src/sidecar-local-error.test.ts b/packages/host-runtime/src/sidecar-local-error.test.ts
new file mode 100644
index 000000000..846cea97b
--- /dev/null
+++ b/packages/host-runtime/src/sidecar-local-error.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, expect, it } from "vitest";
+import { AgentSidecar } from "./agent-sidecar.js";
+
+const sidecars: AgentSidecar[] = [];
+afterEach(async () => {
+ await Promise.all(sidecars.splice(0).map((sidecar) => sidecar.dispose()));
+});
+
+// The bundled runtime tests exercise the sender. This real stdio boundary
+// independently protects the production Host decoder from dropping provenance.
+it.each(["context-validation", "context-estimation", "request-preparation"])(
+ "preserves %s error attribution through the production sidecar receiver",
+ async (phase) => {
+ const data = {
+ errorCode: "INTERNAL",
+ retriable: false,
+ details: { origin: "local", phase, causeName: "TypeError" },
+ };
+ const source = `
+ const rl = require('node:readline').createInterface({ input: process.stdin });
+ rl.on('line', line => {
+ const request = JSON.parse(line);
+ if (request.method === 'ping') {
+ console.log(JSON.stringify({ id: request.id, result: { ok: true } }));
+ return;
+ }
+ console.log(JSON.stringify({ id: request.id, error: {
+ code: -32000, message: 'Local request preparation failed',
+ data: ${JSON.stringify(data)}
+ } }));
+ });`;
+ const sidecar = new AgentSidecar({
+ launch: { command: process.execPath, args: ["-e", source] },
+ onStderr: () => {},
+ });
+ sidecars.push(sidecar);
+
+ await expect(sidecar.call("probe", {})).rejects.toMatchObject({
+ code: -32000,
+ errorCode: "INTERNAL",
+ message: "Local request preparation failed",
+ data,
+ });
+ expect(await sidecar.call("ping", {})).toEqual({ ok: true });
+ },
+);
diff --git a/patches/@[email protected] b/patches/@[email protected]
index 4ce450490..fc421f5cc 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -1,7 +1,8 @@
diff --git a/dist/agent-loop.js b/dist/agent-loop.js
+index 9da16513e8d11e4bb3d7109b6f0ae4c35a3abdbd..e71adc7c61a6b9587e84d37dd04a9ce2f5834bfc 100644
--- a/dist/agent-loop.js
+++ b/dist/agent-loop.js
-@@ -256,6 +256,12 @@
+@@ -256,6 +256,12 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc
case "toolcall_start":
case "toolcall_delta":
case "toolcall_end":
@@ -14,3 +15,378 @@ diff --git a/dist/agent-loop.js b/dist/agent-loop.js
if (partialMessage) {
partialMessage = event.partial;
context.messages[context.messages.length - 1] = partialMessage;
+diff --git a/dist/agent.js b/dist/agent.js
+index 209c9d3a6ed4819c0fc1591892e43caf52c941bf..d5459c927e6117a77211f940253d1fdc64b751a6 100644
+--- a/dist/agent.js
++++ b/dist/agent.js
+@@ -1,3 +1,4 @@
++import { localRequestErrorDetails } from "@earendil-works/pi-ai";
+ import { createInitialSystemMessage, getCurrentSystemMessage, getCurrentSystemPrompt, toToolDeclaration, } from "@earendil-works/pi-ai";
+ import { runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";
+ import { getDefaultStreamFn } from "./stream-fn.js";
+@@ -356,6 +357,7 @@ export class Agent {
+ }
+ }
+ async handleRunFailure(error, aborted) {
++ const errorDetails = aborted ? undefined : localRequestErrorDetails(error);
+ const failureMessage = {
+ role: "assistant",
+ content: [{ type: "text", text: "" }],
+@@ -364,7 +366,8 @@ export class Agent {
+ model: this._state.model.id,
+ usage: EMPTY_USAGE,
+ stopReason: aborted ? "aborted" : "error",
+- errorMessage: error instanceof Error ? error.message : String(error),
++ errorMessage: errorDetails?.message ?? (error instanceof Error ? error.message : String(error)),
++ ...(errorDetails ? { errorDetails } : {}),
+ 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 85c89e80b879973e125a053f71f4044febd01744..995a28d5eedbf65227d3bd3b8ef62f3814679d68 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 d430a3f966cc9624cc2e78638fd207a83a75b312..1682577b73f847324aa89f4455b27e14bace36dd 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 f7c6a26ac39539cfb578d79c79c071bfd9fbdcd9..a5de5589fcc9395ea2cb031453359c468f6579a0 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 736c315ec001a7d3b526ac019d08e59b43711205..4517456d3a141e45f03269b47ef2123edaa94b90 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 2fa0e3570797cedf43e2b1e2f1052bc4b62e6d9c..1a22a7d33caf1e46f7ad8930e5dd0000b2a86c9b 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 f34eede37d69d0ceaad068d6a01812a1ca5fee7d..fc0191d71ee32aec8260a31a38fa7952b2e4a64b 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 01ffaa587dbf91bce9a8ade5fb5ed09e174267e3..73970f394690526941efce6714f1647499e81fb3 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/patches/@[email protected] b/patches/@[email protected]
index 672505126..1ceaff238 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -1,7 +1,45 @@
diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
+index d462f30bd8e5ebcbaf3cf3e0563cb0915d0d1aea..9d89a90bf1c4f79d6299e32094678711263a5132 100644
--- a/dist/api/anthropic-messages.js
+++ b/dist/api/anthropic-messages.js
-@@ -474,6 +474,39 @@
+@@ -1,3 +1,6 @@
++import { hostedSearchReplayProjection, validateHostedSearchMessages } from "../utils/hosted-search.js";
++import { asLocalRequestError, localRequestErrorDetails } from "../utils/local-request-error.js";
++import { withLocalRequestErrors } from "../utils/local-request-stream.js";
+ import Anthropic from "@anthropic-ai/sdk";
+ import { calculateCost } from "../models.js";
+ import { appendAssistantMessageDiagnostic } from "../utils/diagnostics.js";
+@@ -332,8 +335,6 @@ async function* iterateAnthropicEvents(response, signal) {
+ }
+ export const stream = (model, context, options) => {
+ const stream = new AssistantMessageEventStream();
+- const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);
+- const currentTools = getCurrentTools(normalizedContext.messages);
+ (async () => {
+ const providerThinkingLevel = model.compat?.supportsMidConvoEffort ? (options?.effort ?? "high") : undefined;
+ const output = {
+@@ -354,7 +355,11 @@ export const stream = (model, context, options) => {
+ stopReason: "pending",
+ timestamp: Date.now(),
+ };
++ let preparingRequest = true;
+ try {
++ const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);
++ validateHostedSearchMessages(normalizedContext.messages);
++ const currentTools = getCurrentTools(normalizedContext.messages);
+ let client;
+ let isOAuth;
+ let usageModel = model;
+@@ -390,6 +395,8 @@ export const stream = (model, context, options) => {
+ ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
+ maxRetries: 0,
+ };
++ JSON.stringify(params);
++ preparingRequest = false;
+ const response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {
+ maxRetries: options?.maxRetries,
+ maxRetryDelayMs: options?.maxRetryDelayMs,
+@@ -474,6 +481,39 @@ export const stream = (model, context, options) => {
output.content.push(block);
stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
}
@@ -41,7 +79,7 @@ diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
}
else if (event.type === "content_block_delta") {
if (event.delta.type === "text_delta") {
-@@ -515,6 +548,18 @@
+@@ -515,6 +555,18 @@ export const stream = (model, context, options) => {
partial: output,
});
}
@@ -60,37 +98,77 @@ diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
}
else if (event.delta.type === "signature_delta") {
const index = blocks.findIndex((b) => b.index === event.index);
-@@ -522,6 +567,16 @@
- if (block && block.type === "thinking") {
- block.thinkingSignature = block.thinkingSignature || "";
+@@ -524,6 +576,18 @@ export const stream = (model, context, options) => {
block.thinkingSignature += event.delta.signature;
-+ }
-+ }
+ }
+ }
+ // Hosted web search (PI-Desktop): citations arrive as deltas
+ // on the text block that follows the search result. Collect
+ // them on the message for the application to render.
+ else if (event.delta.type === "citations_delta") {
+ const citation = event.delta.citation;
-+ if (citation && typeof citation === "object") {
++ // Document citations are not hosted-search URL citations.
++ if (citation && typeof citation === "object" && typeof citation.url === "string" && citation.url.length > 0 &&
++ (citation.title === undefined || typeof citation.title === "string")) {
+ output.hostedSearchCitations = output.hostedSearchCitations ?? [];
+ output.hostedSearchCitations.push(citation);
- }
- }
++ }
++ }
}
-@@ -557,6 +612,12 @@
- toolCall: block,
+ else if (event.type === "content_block_stop") {
+ const index = blocks.findIndex((b) => b.index === event.index);
+@@ -558,6 +622,12 @@ export const stream = (model, context, options) => {
partial: output,
});
-+ }
+ }
+ // Hosted search blocks carry no streaming scratch
+ // state; closing one just drops the index marker.
+ else if (block.type === "hostedSearch") {
+ delete block.index;
+ delete block.inputJson;
- }
++ }
}
}
-@@ -868,6 +929,15 @@
+ else if (event.type === "message_delta") {
+@@ -625,13 +695,18 @@ export const stream = (model, context, options) => {
+ stream.end();
+ }
+ catch (error) {
++ if (preparingRequest && !options?.signal?.aborted)
++ error = asLocalRequestError(error, "request-preparation");
++ const errorDetails = options?.signal?.aborted ? undefined : localRequestErrorDetails(error);
++ if (errorDetails)
++ output.errorDetails = errorDetails;
+ for (const block of output.content) {
+ delete block.index;
+ // partialJson is only a streaming scratch buffer; never persist it.
+ delete block.partialJson;
+ }
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
+- output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
++ output.errorMessage = errorDetails?.message ?? (error instanceof Error ? error.message : JSON.stringify(error));
+ stream.push({ type: "error", reason: output.stopReason, error: output });
+ stream.end();
+ }
+@@ -659,7 +734,7 @@ function mapThinkingLevelToEffort(model, level) {
+ return "high";
+ }
+ }
+-export const streamSimple = (model, context, options) => {
++export const streamSimple = (model, context, options) => withLocalRequestErrors(model, options, () => {
+ assertRequestAuth(model.provider, options?.apiKey, options?.headers);
+ const base = {
+ ...buildBaseOptions(model, context, options, options?.apiKey),
+@@ -691,7 +766,7 @@ export const streamSimple = (model, context, options) => {
+ thinkingEnabled: true,
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),
+ });
+-};
++});
+ function isOAuthToken(apiKey) {
+ return apiKey.includes("sk-ant-oat");
+ }
+@@ -868,6 +943,15 @@ function buildParams(model, context, isOAuthToken, options) {
params.tools = convertTools(tools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl);
}
}
@@ -106,7 +184,7 @@ diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
// Managed effort models always use adaptive thinking so prefix mismatches can
// be dropped instead of surfacing as persistent 400 responses.
if (model.compat?.supportsMidConvoEffort === true) {
-@@ -1072,6 +1142,30 @@
+@@ -1072,6 +1156,15 @@ function convertMessages(transformedMessages, isOAuthToken, cacheControl, allowE
input: block.arguments ?? {},
});
}
@@ -114,33 +192,94 @@ diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
+ // pair in place, in their original order. `server_tool_use`
+ // carries the query; the result block carries the encrypted
+ // content Anthropic requires verbatim on later turns.
-+ else if (block.type === "hostedSearch" && block.phase === "server_tool_use") {
-+ blocks.push({
-+ type: "server_tool_use",
-+ id: block.blockId,
-+ name: block.name,
-+ input: block.input ?? {},
-+ });
-+ }
-+ else if (block.type === "hostedSearch" && block.phase === "web_search_tool_result") {
-+ const wire = block.wire;
-+ if (wire && typeof wire === "object") {
-+ const replay = { ...wire };
-+ delete replay.type;
-+ blocks.push({
-+ type: block.isError ? "web_search_tool_result_error" : "web_search_tool_result",
-+ tool_use_id: block.blockId,
-+ ...replay,
-+ });
-+ }
++ else if (block.type === "hostedSearch") {
++ const projection = hostedSearchReplayProjection(block, { api: "anthropic-messages" });
++ if (projection !== undefined)
++ blocks.push(projection);
+ }
}
if (blocks.length === 0)
continue;
diff --git a/dist/api/azure-openai-responses.js b/dist/api/azure-openai-responses.js
+index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d09ef5644b 100644
--- a/dist/api/azure-openai-responses.js
+++ b/dist/api/azure-openai-responses.js
-@@ -235,6 +235,12 @@
+@@ -1,3 +1,5 @@
++import { asLocalRequestError, localRequestErrorDetails } from "../utils/local-request-error.js";
++import { withLocalRequestErrors } from "../utils/local-request-stream.js";
+ import { AzureOpenAI } from "openai";
+ import { clampThinkingLevel } from "../models.js";
+ import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
+@@ -45,10 +47,8 @@ function formatAzureOpenAIError(error) {
+ */
+ export const stream = (model, context, options) => {
+ const stream = new AssistantMessageEventStream();
+- const normalizedContext = resolveTranscript(context, model.compat?.supportsMidConvoSystemMessages);
+ // Start async processing
+ (async () => {
+- const deploymentName = resolveDeploymentName(model, options);
+ const output = {
+ role: "assistant",
+ content: [],
+@@ -66,7 +66,10 @@ export const stream = (model, context, options) => {
+ stopReason: "pending",
+ timestamp: Date.now(),
+ };
++ let preparingRequest = true;
+ try {
++ const normalizedContext = resolveTranscript(context, model.compat?.supportsMidConvoSystemMessages);
++ const deploymentName = resolveDeploymentName(model, options);
+ // Create Azure OpenAI client
+ const apiKey = options?.apiKey;
+ if (!apiKey) {
+@@ -84,6 +87,8 @@ export const stream = (model, context, options) => {
+ ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
+ maxRetries: 0,
+ };
++ JSON.stringify(params);
++ preparingRequest = false;
+ const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
+ maxRetries: options?.maxRetries,
+ maxRetryDelayMs: options?.maxRetryDelayMs,
+@@ -105,6 +110,11 @@ export const stream = (model, context, options) => {
+ stream.end();
+ }
+ catch (error) {
++ if (preparingRequest && !options?.signal?.aborted)
++ error = asLocalRequestError(error, "request-preparation");
++ const errorDetails = options?.signal?.aborted ? undefined : localRequestErrorDetails(error);
++ if (errorDetails)
++ output.errorDetails = errorDetails;
+ for (const block of output.content) {
+ delete block.index;
+ // Streaming scratch buffers are only used during parsing; never persist them.
+@@ -112,14 +122,14 @@ export const stream = (model, context, options) => {
+ delete block.customInput;
+ }
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
+- output.errorMessage = formatAzureOpenAIError(error);
++ output.errorMessage = errorDetails?.message ?? formatAzureOpenAIError(error);
+ stream.push({ type: "error", reason: output.stopReason, error: output });
+ stream.end();
+ }
+ })();
+ return stream;
+ };
+-export const streamSimple = (model, context, options) => {
++export const streamSimple = (model, context, options) => withLocalRequestErrors(model, options, () => {
+ const apiKey = options?.apiKey;
+ if (!apiKey) {
+ throw new Error(`No API key for provider: ${model.provider}`);
+@@ -134,7 +144,7 @@ export const streamSimple = (model, context, options) => {
+ ...base,
+ reasoningEffort,
+ });
+-};
++});
+ function normalizeAzureBaseUrl(baseUrl) {
+ const trimmed = baseUrl.trim().replace(/\/+$/, "");
+ let url;
+@@ -235,6 +245,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
if (options?.toolChoice !== undefined) {
params.tool_choice = options.toolChoice;
}
@@ -153,7 +292,7 @@ diff --git a/dist/api/azure-openai-responses.js b/dist/api/azure-openai-response
if (model.reasoning) {
if (options?.reasoningEffort || options?.reasoningSummary) {
const effort = options?.reasoningEffort
-@@ -252,6 +258,12 @@
+@@ -252,6 +268,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
};
}
}
@@ -166,10 +305,25 @@ diff --git a/dist/api/azure-openai-responses.js b/dist/api/azure-openai-response
// Last so custom keys override the named request fields.
if (options?.samplingParams) {
Object.assign(params, options.samplingParams);
+diff --git a/dist/api/mistral-conversations.js b/dist/api/mistral-conversations.js
+index 3106c5d470dc3610c05d8ee153026df20f86f66e..8b209bb46809c394ffebfd11d5dfd2731c204310 100644
+--- a/dist/api/mistral-conversations.js
++++ b/dist/api/mistral-conversations.js
+@@ -645,6 +645,9 @@ function toChatMessages(messages, supportsImages) {
+ }
+ continue;
+ }
++ // Mistral 不回放托管搜索;只把真正的客户端工具调用转换为 function。
++ if (block.type !== "toolCall")
++ continue;
+ toolCalls.push({
+ id: block.id,
+ type: "function",
diff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js
+index fd459fddd20380242bbe37ec16e260097c9e4236..7d4c90a1aee35efaa05548c4797929111de4db70 100644
--- a/dist/api/openai-completions.js
+++ b/dist/api/openai-completions.js
-@@ -1039,21 +1039,27 @@
+@@ -1039,21 +1039,27 @@ export function convertMessages(model, context, compat, options) {
if (preservedReasoningDetails) {
assistantMsg.reasoning_details = preservedReasoningDetails;
}
@@ -203,11 +357,10 @@ diff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js
}
params.push(assistantMsg);
}
-@@ -1120,6 +1126,41 @@
- continue;
+@@ -1121,6 +1127,41 @@ export function convertMessages(model, context, compat, options) {
}
lastRole = msg.role;
-+ }
+ }
+ // DeepSeek-style endpoints reject a history in which only some assistant
+ // messages carry a reasoning field, while all-or-none is accepted. Prefer
+ // the field already present on the history (reasoning_content,
@@ -242,25 +395,42 @@ diff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js
+ }
+ }
+ }
- }
++ }
return params;
}
+ function convertTools(tools, compat) {
diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-shared.js
+index 53597d2c3becdd2c03d4fd265c213a36b403f26b..8bb8ca1ea19d5e9daa584956e307ce59cd089d5d 100644
--- a/dist/api/openai-responses-shared.js
+++ b/dist/api/openai-responses-shared.js
-@@ -202,6 +202,11 @@
+@@ -1,3 +1,4 @@
++import { hostedSearchReplayProjection, validateHostedSearchMessages } from "../utils/hosted-search.js";
+ import { calculateCost } from "../models.js";
+ import { shortHash } from "../utils/hash.js";
+ import { parseStreamingJson } from "../utils/json-parse.js";
+@@ -62,6 +63,7 @@ function convertToolResultOutput(model, content) {
+ // =============================================================================
+ export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
+ const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);
++ validateHostedSearchMessages(normalizedContext.messages);
+ const messages = [];
+ const normalizeIdPart = (part) => {
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
+@@ -202,6 +204,13 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
phase: parsedSignature?.phase,
});
}
+ // Hosted web search (PI-Desktop): replay the search item in
+ // place so follow-up turns keep the search state.
-+ else if (block.type === "hostedSearch" && block.phase === "web_search_call" && isSameModel) {
-+ output.push({ ...(block.wire ?? { type: "web_search_call", id: block.blockId, status: "completed" }) });
++ else if (block.type === "hostedSearch") {
++ const projection = hostedSearchReplayProjection(block, { api: "openai-responses", isSameModel });
++ if (projection !== undefined)
++ output.push(projection);
+ }
else if (block.type === "toolCall") {
const toolCall = block;
const [callId, itemIdRaw] = toolCall.id.split("|");
-@@ -405,6 +410,28 @@
+@@ -405,6 +414,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
stream.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
return slot;
}
@@ -289,11 +459,10 @@ diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-sha
return undefined;
};
const getOrCreateSlot = (outputIndex, item) => {
-@@ -528,6 +555,27 @@
- delta: event.delta,
+@@ -529,6 +560,27 @@ export async function processResponsesStream(openaiStream, output, stream, model
partial: output,
});
-+ }
+ }
+ // Hosted web search (PI-Desktop): citation annotations arrive while
+ // the text streams. They are collected on the output message so the
+ // application can render sources without parsing text offsets.
@@ -314,10 +483,11 @@ diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-sha
+ if (item && typeof item === "object" && item.type === "web_search_call") {
+ getOrCreateSlot(event.output_index, item);
+ }
- }
++ }
else if (event.type === "response.refusal.delta") {
const slot = getSlot(event.output_index, "text");
-@@ -633,9 +681,25 @@
+ if (!slot)
+@@ -633,9 +685,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
});
outputSlots.delete(event.output_index);
}
@@ -344,9 +514,82 @@ diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-sha
else if (event.type === "error") {
throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
diff --git a/dist/api/openai-responses.js b/dist/api/openai-responses.js
+index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15bc29cdf4 100644
--- a/dist/api/openai-responses.js
+++ b/dist/api/openai-responses.js
-@@ -242,6 +242,12 @@
+@@ -1,3 +1,5 @@
++import { asLocalRequestError, localRequestErrorDetails } from "../utils/local-request-error.js";
++import { withLocalRequestErrors } from "../utils/local-request-stream.js";
+ import OpenAI from "openai";
+ import { clampThinkingLevel } from "../models.js";
+ import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";
+@@ -81,7 +83,6 @@ function getPromptCacheOptions(compat, cacheRetention) {
+ */
+ export const stream = (model, context, options) => {
+ const stream = new AssistantMessageEventStream();
+- const normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);
+ // Start async processing
+ (async () => {
+ const output = {
+@@ -101,7 +102,9 @@ export const stream = (model, context, options) => {
+ stopReason: "pending",
+ timestamp: Date.now(),
+ };
++ let preparingRequest = true;
+ try {
++ const normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);
+ // Create OpenAI client
+ const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
+@@ -119,6 +122,9 @@ export const stream = (model, context, options) => {
+ ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
+ maxRetries: 0,
+ };
++ // 在进入网络边界前验证可序列化性,不把网络 TypeError 当作本地错误。
++ JSON.stringify(params);
++ preparingRequest = false;
+ const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
+ maxRetries: options?.maxRetries,
+ maxRetryDelayMs: options?.maxRetryDelayMs,
+@@ -144,6 +150,11 @@ export const stream = (model, context, options) => {
+ stream.end();
+ }
+ catch (error) {
++ if (preparingRequest && !options?.signal?.aborted)
++ error = asLocalRequestError(error, "request-preparation");
++ const errorDetails = options?.signal?.aborted ? undefined : localRequestErrorDetails(error);
++ if (errorDetails)
++ output.errorDetails = errorDetails;
+ for (const block of output.content) {
+ delete block.index;
+ // Streaming scratch buffers are only used during parsing; never persist them.
+@@ -151,14 +162,14 @@ export const stream = (model, context, options) => {
+ delete block.customInput;
+ }
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
+- output.errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);
++ output.errorMessage = errorDetails?.message ?? formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);
+ stream.push({ type: "error", reason: output.stopReason, error: output });
+ stream.end();
+ }
+ })();
+ return stream;
+ };
+-export const streamSimple = (model, context, options) => {
++export const streamSimple = (model, context, options) => withLocalRequestErrors(model, options, () => {
+ getClientApiKey(model.provider, options?.apiKey, options?.headers);
+ const base = {
+ ...buildBaseOptions(model, context, options, options?.apiKey),
+@@ -170,7 +181,7 @@ export const streamSimple = (model, context, options) => {
+ ...base,
+ reasoningEffort,
+ });
+-};
++});
+ function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId) {
+ const compat = getCompat(model);
+ const headers = { "User-Agent": getPiUserAgent(), ...model.headers };
+@@ -242,6 +253,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar
supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,
});
}
@@ -359,7 +602,7 @@ diff --git a/dist/api/openai-responses.js b/dist/api/openai-responses.js
if (options?.toolChoice !== undefined) {
params.tool_choice = options.toolChoice;
}
-@@ -264,6 +270,12 @@
+@@ -264,6 +281,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar
if (model.provider === "xai")
params.include = ["reasoning.encrypted_content"];
}
@@ -372,13 +615,36 @@ diff --git a/dist/api/openai-responses.js b/dist/api/openai-responses.js
// Last so custom keys override the named request fields.
if (options?.samplingParams) {
Object.assign(params, options.samplingParams);
+diff --git a/dist/api/simple-options.js b/dist/api/simple-options.js
+index 216a45feebc02acef047d1ff133729fb0751b76c..23528b801d65e33d22eb1d63ea49945d24a5e658 100644
+--- a/dist/api/simple-options.js
++++ b/dist/api/simple-options.js
+@@ -4,7 +4,7 @@ const MIN_MAX_TOKENS = 1;
+ export function clampMaxTokensToContext(model, context, maxTokens) {
+ if (model.contextWindow <= 0)
+ return Math.max(MIN_MAX_TOKENS, maxTokens);
+- const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;
++ const available = model.contextWindow - estimateContextTokens(context, model).tokens - CONTEXT_SAFETY_TOKENS;
+ return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));
+ }
+ export function buildBaseOptions(model, context, options, apiKey) {
diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
+index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182ed7e81f2a 100644
--- a/dist/auth/oauth/anthropic.js
+++ b/dist/auth/oauth/anthropic.js
-@@ -140,21 +140,90 @@
+@@ -140,21 +140,90 @@ async function startCallbackServer(expectedState) {
});
});
}
+-async function postJson(url, body, signal) {
+- const response = await fetch(url, {
+- method: "POST",
+- headers: {
+- "Content-Type": "application/json",
+- Accept: "application/json",
+- },
+- body: JSON.stringify(body),
+- signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
+class AnthropicOAuthTokenError extends Error {
+ constructor(status, code, grantType) {
+ const recovery = grantType === "authorization_code"
@@ -422,23 +688,12 @@ diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
+ reject(signal.reason);
+ };
+ signal.addEventListener("abort", abort, { once: true });
-+ });
-+}
- async function postJson(url, body, signal) {
-- const response = await fetch(url, {
-- method: "POST",
-- headers: {
-- "Content-Type": "application/json",
-- Accept: "application/json",
-- },
-- body: JSON.stringify(body),
-- signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
-- });
+ });
- const responseBody = await response.text();
- if (!response.ok) {
- throw new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);
-- }
-- return responseBody;
++}
++async function postJson(url, body, signal) {
+ // Keep one deadline for all attempts, including response bodies and waits.
+ // The caller's signal can impose an earlier refresh deadline or cancellation.
+ const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30_000)]);
@@ -476,11 +731,12 @@ diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
+ if (delay >= deadline - performance.now())
+ throw failure; // Never shorten the server's requested wait.
+ await waitForTokenRetry(delay, requestSignal);
-+ }
+ }
+- return responseBody;
}
async function exchangeAuthorizationCode(code, state, verifier, redirectUri, signal) {
let responseBody;
-@@ -169,6 +238,8 @@
+@@ -169,6 +238,8 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig
}, signal);
}
catch (error) {
@@ -489,7 +745,7 @@ diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`);
}
let tokenData;
-@@ -176,7 +247,7 @@
+@@ -176,7 +247,7 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig
tokenData = JSON.parse(responseBody);
}
catch (error) {
@@ -498,7 +754,7 @@ diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
}
return {
type: "oauth",
-@@ -280,6 +351,8 @@
+@@ -280,6 +351,8 @@ async function refreshAnthropicToken(refreshToken, signal) {
}, signal);
}
catch (error) {
@@ -507,7 +763,7 @@ diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);
}
let data;
-@@ -287,7 +360,7 @@
+@@ -287,7 +360,7 @@ async function refreshAnthropicToken(refreshToken, signal) {
data = JSON.parse(responseBody);
}
catch (error) {
@@ -516,3 +772,616 @@ diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
}
return {
type: "oauth",
+diff --git a/dist/index.d.ts b/dist/index.d.ts
+index 5e8403dd62895d30eb7d8e3f95b87d6535221839..50f728e4427e1cadb9aded7e35f3e44611eefc85 100644
+--- a/dist/index.d.ts
++++ b/dist/index.d.ts
+@@ -34,4 +34,7 @@ export * from "./utils/transcript.ts";
+ export * from "./utils/typebox-helpers.ts";
+ export { uuidv7 } from "./utils/uuid.ts";
+ export * from "./utils/validation.ts";
++export { LocalRequestError, localRequestErrorDetails } from "./utils/local-request-error.ts";
++export type { LocalRequestErrorDetails, LocalRequestErrorPhase } from "./utils/local-request-error.ts";
++export * from "./utils/hosted-search.ts";
+ //# sourceMappingURL=index.d.ts.map
+\ No newline at end of file
+diff --git a/dist/index.js b/dist/index.js
+index cf46c043b854412d56c5d65230a509165229806e..0fe002385c3d9906709be1cce6867d0c30a3a151 100644
+--- a/dist/index.js
++++ b/dist/index.js
+@@ -21,4 +21,6 @@ export * from "./utils/transcript.js";
+ export * from "./utils/typebox-helpers.js";
+ export { uuidv7 } from "./utils/uuid.js";
+ export * from "./utils/validation.js";
++export { LocalRequestError, localRequestErrorDetails } from "./utils/local-request-error.js";
++export * from "./utils/hosted-search.js";
+ //# sourceMappingURL=index.js.map
+\ No newline at end of file
+diff --git a/dist/types.d.ts b/dist/types.d.ts
+index 49f2a3262e19aea105f95424cdec08444a7f5748..52215b53d50ed92ed0aeb7416ab71c1bdced2d49 100644
+--- a/dist/types.d.ts
++++ b/dist/types.d.ts
+@@ -267,6 +267,30 @@ export interface ToolCall {
+ /** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */
+ namespace?: string;
+ }
++export interface HostedSearchCitation {
++ url: string;
++ title?: string;
++}
++export type HostedSearchContent = {
++ type: "hostedSearch";
++ phase: "server_tool_use";
++ blockId: string;
++ name: string;
++ input: JsonObject;
++} | {
++ type: "hostedSearch";
++ phase: "web_search_tool_result";
++ blockId: string;
++ isError?: boolean;
++ wire: JsonObject;
++} | {
++ type: "hostedSearch";
++ phase: "web_search_call";
++ blockId: string;
++ status?: string;
++ /** Legacy records without wire replay the minimal completed search item. */
++ wire?: JsonObject;
++};
+ export interface Usage {
+ input: number;
+ output: number;
+@@ -352,7 +376,7 @@ export interface UserMessage {
+ }
+ export interface AssistantMessage {
+ role: "assistant";
+- content: (TextContent | ThinkingContent | ToolCall)[];
++ content: (TextContent | ThinkingContent | ToolCall | HostedSearchContent)[];
+ api: Api;
+ provider: ProviderId;
+ model: string;
+@@ -365,6 +389,8 @@ export interface AssistantMessage {
+ stopReason: StopReason;
+ deferred?: DeferredHandle;
+ errorMessage?: string;
++ errorDetails?: import("./utils/local-request-error.ts").LocalRequestErrorDetails;
++ hostedSearchCitations?: HostedSearchCitation[];
+ rawStopReason?: string;
+ /**
+ * Provider indication of whether the model explicitly ended its turn.
+@@ -512,6 +538,10 @@ export type AssistantMessageEvent = {
+ contentIndex: number;
+ toolCall: ToolCall;
+ partial: AssistantMessage;
++} | {
++ type: "hosted_search_update";
++ contentIndex: number;
++ partial: AssistantMessage;
+ } | {
+ type: "done";
+ reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;
+@@ -789,6 +819,8 @@ export interface Model<TApi extends Api> {
+ provider: ProviderId;
+ baseUrl: string;
+ reasoning: boolean;
++ /** Opt in to hosted search on the existing Anthropic/Responses adapters. */
++ webSearch?: boolean;
+ /**
+ * Maps pi thinking levels to provider/model-specific values.
+ * Missing keys use provider defaults. null marks a level as unsupported.
+diff --git a/dist/utils/assistant-message-frame.d.ts b/dist/utils/assistant-message-frame.d.ts
+index 08207197acab532d0f5f596363700a2d15a687d8..0584f6898e1d842c4414869b9080505b63c3a7b7 100644
+--- a/dist/utils/assistant-message-frame.d.ts
++++ b/dist/utils/assistant-message-frame.d.ts
+@@ -1,4 +1,4 @@
+-import type { AssistantMessage, AssistantMessageEvent, TextContent, ThinkingContent, ToolCall } from "../types.ts";
++import type { AssistantMessage, AssistantMessageEvent, HostedSearchContent, TextContent, ThinkingContent, ToolCall } from "../types.ts";
+ /**
+ * Compact, replayable assistant-message progress. Terminal settlement is
+ * intentionally excluded and must be persisted separately.
+@@ -53,6 +53,11 @@ export type AssistantMessageFrame = {
+ arguments: ToolCall["arguments"];
+ thoughtSignature?: string;
+ namespace?: string;
++} | {
++ type: "hosted_search_update";
++ contentIndex: number;
++ /** Complete detached snapshot, replacing the same search block on later updates. */
++ content: HostedSearchContent;
+ };
+ /**
+ * Encodes one assistant stream. `partial` remains a shared live accumulator;
+diff --git a/dist/utils/assistant-message-frame.js b/dist/utils/assistant-message-frame.js
+index c0e00197b2bdd4c815106daa036d844c07aca800..2641d3b3115273f4b693d73ce39f8c62f30afe37 100644
+--- a/dist/utils/assistant-message-frame.js
++++ b/dist/utils/assistant-message-frame.js
+@@ -1,3 +1,4 @@
++import { normalizeHostedSearchContent } from "./hosted-search.js";
+ import { parseStreamingJson } from "./json-parse.js";
+ function cloneTextContent(content) {
+ return {
+@@ -24,6 +25,24 @@ function cloneToolCall(toolCall) {
+ ...(toolCall.namespace === undefined ? {} : { namespace: toolCall.namespace }),
+ };
+ }
++function cloneHostedSearchContent(content) {
++ const block = normalizeHostedSearchContent(content);
++ const base = { type: "hostedSearch", phase: block.phase, blockId: block.blockId };
++ // Deep-copy declared wire/input fields so mutable partials and parser buffers cannot alter old frames.
++ if (block.phase === "server_tool_use")
++ return { ...base, name: block.name, input: structuredClone(block.input) };
++ if (block.phase === "web_search_tool_result")
++ return { ...base, ...(content.isError === undefined ? {} : { isError: block.isError }), wire: structuredClone(block.wire) };
++ return {
++ ...base,
++ ...(block.status === undefined ? {} : { status: block.status }),
++ ...(block.wire == null ? {} : { wire: structuredClone(block.wire) }),
++ };
++}
++function assertSameHostedSearch(previous, current) {
++ if (previous.phase !== current.phase || previous.blockId !== current.blockId)
++ throw new Error("Hosted search update changes block identity");
++}
+ function cloneStartMessage(message) {
+ return {
+ role: "assistant",
+@@ -105,6 +124,19 @@ export class AssistantMessageFrameEncoder {
+ if (!this.started)
+ throw new Error(`Assistant message ${event.type} event appears before start`);
+ switch (event.type) {
++ case "hosted_search_update": {
++ const content = cloneHostedSearchContent(eventBlock(event));
++ const state = this.blocks.get(event.contentIndex);
++ if (state === undefined) {
++ this.startBlock(event.contentIndex, { kind: "hostedSearch", phase: content.phase, blockId: content.blockId });
++ }
++ else {
++ this.block(event.contentIndex, "hostedSearch");
++ assertSameHostedSearch(state, content);
++ }
++ // Search events are snapshots: completed wire data can arrive later without a synthetic end state.
++ return { type: "hosted_search_update", contentIndex: event.contentIndex, content };
++ }
+ case "text_start": {
+ const content = eventBlock(event);
+ if (content.type !== "text") {
+@@ -311,6 +343,20 @@ export function reduceAssistantMessageFrames(frames) {
+ continue;
+ }
+ switch (frame.type) {
++ case "hosted_search_update": {
++ const content = cloneHostedSearchContent(frame.content);
++ assertContentIndex(frame.contentIndex);
++ if (frame.contentIndex >= message.content.length) {
++ // Preserve the original content index; appendBlock still rejects actual gaps.
++ appendBlock(message, states, frame.contentIndex, content, { kind: "hostedSearch", ended: false });
++ }
++ else {
++ const { block } = activeBlock(message, states, frame.contentIndex, "hostedSearch", frame.type);
++ assertSameHostedSearch(block, content);
++ message.content[frame.contentIndex] = content;
++ }
++ break;
++ }
+ case "text_start":
+ if (frame.content.type !== "text") {
+ throw new Error(`text_start frame contains ${frame.content.type} content`);
+diff --git a/dist/utils/estimate.d.ts b/dist/utils/estimate.d.ts
+index 6dcca6eff16b95b83e047a6e27b65d9d7694bf2c..5ccaaf2358a0afeea3ce354e5799255ae8508f3d 100644
+--- a/dist/utils/estimate.d.ts
++++ b/dist/utils/estimate.d.ts
+@@ -1,4 +1,4 @@
+-import type { ImageContent, Message, TextContent, TranscriptContext, Usage } from "../types.ts";
++import type { Api, Model, ImageContent, Message, TextContent, TranscriptContext, Usage } from "../types.ts";
+ export interface ContextUsageEstimate {
+ /** Estimated total context tokens. */
+ tokens: number;
+@@ -12,6 +12,7 @@ export interface ContextUsageEstimate {
+ export declare function calculateContextTokens(usage: Usage): number;
+ export declare function estimateTextTokens(text: string): number;
+ export declare function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number;
+-export declare function estimateMessageTokens(message: Message): number;
+-export declare function estimateContextTokens(context: TranscriptContext | readonly Message[]): ContextUsageEstimate;
++export declare function estimateMessageTokens(message: Message, model?: Model<Api>): number;
++export declare function estimateContextTokens(context: TranscriptContext | readonly Message[], model?: Model<Api>): ContextUsageEstimate;
++export declare function getLastAssistantUsageInfo(messages: readonly { role: string; timestamp: number }[]): { usage: Usage; index: number } | undefined;
+ //# sourceMappingURL=estimate.d.ts.map
+\ No newline at end of file
+diff --git a/dist/utils/estimate.js b/dist/utils/estimate.js
+index d04ff22cbe8d7357404b938e228b8e3a2dbdcb1d..28564cc73798163f7590290123b7476573d5bee5 100644
+--- a/dist/utils/estimate.js
++++ b/dist/utils/estimate.js
+@@ -1,95 +1,114 @@
+ import { getSystemMessageText } from "./text.js";
++import { hostedSearchReplayProjection, validateHostedSearchMessages } from "./hosted-search.js";
++import { LocalRequestError, prepareLocalRequest } from "./local-request-error.js";
+ const CHARS_PER_TOKEN = 4;
+ const ESTIMATED_IMAGE_CHARS = 4800;
+ export function calculateContextTokens(usage) {
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
+ }
+-function safeJsonStringify(value) {
+- try {
+- return JSON.stringify(value) ?? "undefined";
+- }
+- catch {
+- return "[unserializable]";
+- }
++function jsonStringify(value) {
++ return JSON.stringify(value) ?? "undefined";
+ }
+ function estimateTextAndImageContentChars(content) {
+ if (typeof content === "string")
+ return content.length;
+ let chars = 0;
+- for (const block of content)
+- chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
++ for (const block of content) {
++ if (block.type === "text" && typeof block.text === "string")
++ chars += block.text.length;
++ else if (block.type === "image")
++ chars += ESTIMATED_IMAGE_CHARS;
++ else
++ throw new LocalRequestError("context-validation");
++ }
+ return chars;
+ }
+ export function estimateTextTokens(text) {
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
+ }
+ export function estimateTextAndImageContentTokens(content) {
+- return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
++ return prepareLocalRequest("context-estimation", () => Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN));
+ }
+-export function estimateMessageTokens(message) {
+- let chars = 0;
+- if (message.role === "system") {
+- return (estimateTextTokens(getSystemMessageText(message)) +
+- estimateToolsTokens(message.toolsAdded) +
+- estimateToolsTokens(message.toolsRemoved));
+- }
+- if (message.role === "user")
+- return estimateTextAndImageContentTokens(message.content);
+- if (message.role === "toolResult")
+- return estimateTextAndImageContentTokens(message.content);
+- for (const block of message.content) {
+- if (block.type === "text") {
+- chars += block.text.length;
+- }
+- else if (block.type === "thinking") {
+- chars += block.thinking.length;
++/** @param {import('../types.js').Message} message @param {import('../types.js').Model<import('../types.js').Api>} [model] */
++export function estimateMessageTokens(message, model) {
++ return prepareLocalRequest("context-estimation", () => {
++ let chars = 0;
++ switch (message.role) {
++ case "system":
++ return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);
++ case "user":
++ case "toolResult":
++ return estimateTextAndImageContentTokens(message.content);
++ case "assistant":
++ validateHostedSearchMessages([message]);
++ break;
++ default:
++ throw new LocalRequestError("context-validation");
+ }
+- else {
+- chars += block.name.length + safeJsonStringify(block.arguments).length;
++ for (const block of message.content) {
++ switch (block.type) {
++ case "text": chars += block.text.length; break;
++ case "thinking": chars += block.thinking.length; break;
++ case "toolCall": chars += block.name.length + jsonStringify(block.arguments).length; break;
++ case "hostedSearch": {
++ const projection = hostedSearchReplayProjection(block, model ? {
++ api: model.api,
++ isSameModel: message.api === model.api && message.provider === model.provider && message.model === model.id,
++ } : undefined);
++ if (projection !== undefined)
++ chars += jsonStringify(projection).length;
++ break;
++ }
++ default: throw new LocalRequestError("context-validation");
++ }
+ }
+- }
+- return Math.ceil(chars / CHARS_PER_TOKEN);
++ return Math.ceil(chars / CHARS_PER_TOKEN);
++ });
+ }
+-function getLastAssistantUsageInfo(messages) {
++export function getLastAssistantUsageInfo(messages) {
+ let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;
+ let usageInfo;
+ for (let i = 0; i < messages.length; i++) {
+ const message = messages[i];
++ // Missing/non-finite timestamps cannot establish a prefix or poison later usage with NaN.
++ // Never manufacture timestamps; valid zero and equal timestamps retain their semantics.
++ if (!Number.isFinite(message.timestamp))
++ throw new LocalRequestError("context-validation");
+ if (message.role === "assistant") {
+ const assistant = message;
+- // A newer prefix message was inserted after this response (for example, a
+- // compaction summary), so its usage cannot describe the current prefix.
++ // A newly inserted prefix (such as a compaction summary) invalidates older usage.
+ const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;
+- if (usageAppliesToPrefix &&
+- assistant.stopReason !== "aborted" &&
+- assistant.stopReason !== "error" &&
+- calculateContextTokens(assistant.usage) > 0) {
++ if (usageAppliesToPrefix && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" &&
++ assistant.usage && Number.isFinite(calculateContextTokens(assistant.usage)) && calculateContextTokens(assistant.usage) > 0) {
+ usageInfo = { usage: assistant.usage, index: i };
+ }
+ }
++ // A tail system update affects later candidates, not a preceding valid usage anchor.
+ latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);
+ }
+ return usageInfo;
+ }
+-export function estimateContextTokens(context) {
+- const messages = "messages" in context ? context.messages : context;
+- const usageInfo = getLastAssistantUsageInfo(messages);
+- if (usageInfo) {
+- const usageTokens = calculateContextTokens(usageInfo.usage);
+- let trailingTokens = 0;
+- for (let i = usageInfo.index + 1; i < messages.length; i++) {
+- trailingTokens += estimateMessageTokens(messages[i]);
++export function estimateContextTokens(context, model) {
++ return prepareLocalRequest("context-estimation", () => {
++ const messages = "messages" in context ? context.messages : context;
++ // A usage fast path must not conceal malformed search history.
++ validateHostedSearchMessages(messages);
++ const usageInfo = getLastAssistantUsageInfo(messages);
++ if (usageInfo) {
++ const usageTokens = calculateContextTokens(usageInfo.usage);
++ let trailingTokens = 0;
++ for (let i = usageInfo.index + 1; i < messages.length; i++)
++ trailingTokens += estimateMessageTokens(messages[i], model);
++ return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };
+ }
+- return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };
+- }
+- let tokens = 0;
+- for (const message of messages)
+- tokens += estimateMessageTokens(message);
+- return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
++ let tokens = 0;
++ for (const message of messages)
++ tokens += estimateMessageTokens(message, model);
++ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
++ });
+ }
+ function estimateToolsTokens(tools) {
+ if (!tools || tools.length === 0)
+ return 0;
+- return estimateTextTokens(safeJsonStringify(tools));
++ return estimateTextTokens(jsonStringify(tools));
+ }
+-//# sourceMappingURL=estimate.js.map
+\ No newline at end of file
+diff --git a/dist/utils/hosted-search.d.ts b/dist/utils/hosted-search.d.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..a76ae5269313931b8476e1f153e76792875ad54c
+--- /dev/null
++++ b/dist/utils/hosted-search.d.ts
+@@ -0,0 +1,10 @@
++import type { Api, HostedSearchContent, JsonObject, Message } from "../types.ts";
++export interface HostedSearchReplayOptions {
++ api: Api;
++ isSameModel?: boolean;
++}
++/** Validate and normalize legacy persisted shapes without manufacturing tool-call fields. */
++export declare function normalizeHostedSearchContent(value: unknown): HostedSearchContent;
++/** The exact provider replay block; undefined means this target does not replay it. */
++export declare function hostedSearchReplayProjection(value: unknown, options?: HostedSearchReplayOptions): JsonObject | undefined;
++export declare function validateHostedSearchMessages(messages: readonly Message[]): void;
+diff --git a/dist/utils/hosted-search.js b/dist/utils/hosted-search.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..b177a2608c5c4ba6d66d6a3fcaef5895e646933b
+--- /dev/null
++++ b/dist/utils/hosted-search.js
+@@ -0,0 +1,97 @@
++import { LocalRequestError, prepareLocalRequest } from "./local-request-error.js";
++const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
++const nonempty = (value) => typeof value === "string" && value.length > 0;
++function requireValid(valid) {
++ if (!valid)
++ throw new LocalRequestError("context-validation");
++}
++function validateJson(value, ancestors = new Set()) {
++ if (value === null || typeof value === "string" || typeof value === "boolean")
++ return;
++ if (typeof value === "number") {
++ requireValid(Number.isFinite(value));
++ return;
++ }
++ requireValid(typeof value === "object" && !ancestors.has(value));
++ requireValid(Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
++ ancestors.add(value);
++ for (const entry of Object.values(value))
++ validateJson(entry, ancestors);
++ ancestors.delete(value);
++}
++export function normalizeHostedSearchContent(value) {
++ return prepareLocalRequest("context-validation", () => {
++ requireValid(record(value) && value.type === "hostedSearch");
++ const wire = value.wire;
++ requireValid(wire == null || record(wire));
++ const blockId = value.blockId ?? wire?.id ?? wire?.tool_use_id;
++ requireValid(nonempty(blockId));
++ switch (value.phase) {
++ case "server_tool_use": {
++ requireValid(nonempty(value.name));
++ const input = value.input ?? {};
++ requireValid(record(input));
++ validateJson(input);
++ return { ...value, blockId, input };
++ }
++ case "web_search_tool_result":
++ requireValid(record(wire));
++ requireValid(wire.type === undefined || wire.type === "web_search_tool_result" || wire.type === "web_search_tool_result_error");
++ requireValid(wire.tool_use_id === undefined || nonempty(wire.tool_use_id));
++ requireValid(wire.content !== undefined);
++ requireValid(value.isError === undefined || typeof value.isError === "boolean");
++ validateJson(wire);
++ return { ...value, blockId, isError: value.isError ?? wire.type === "web_search_tool_result_error" };
++ case "web_search_call":
++ if (wire != null) {
++ requireValid(wire.type === "web_search_call" && nonempty(wire.id));
++ validateJson(wire);
++ }
++ requireValid(value.status === undefined || typeof value.status === "string");
++ return { ...value, blockId };
++ default:
++ throw new LocalRequestError("context-validation");
++ }
++ });
++}
++export function hostedSearchReplayProjection(value, options) {
++ const block = normalizeHostedSearchContent(value);
++ // One projection for estimation and replay avoids counting wire plus display summaries twice.
++ // Without a target, estimate conservatively; with one, preserve the adapter's model boundary.
++ const api = options?.api ?? (block.phase === "web_search_call" ? "openai-responses" : "anthropic-messages");
++ if (block.phase === "web_search_call") {
++ if ((api !== "openai-responses" && api !== "azure-openai-responses") || options?.isSameModel === false)
++ return undefined;
++ return { ...(block.wire ?? { type: "web_search_call", id: block.blockId, status: "completed" }) };
++ }
++ if (api !== "anthropic-messages")
++ return undefined;
++ if (block.phase === "server_tool_use")
++ return { type: "server_tool_use", id: block.blockId, name: block.name, input: block.input };
++ const { type: _type, ...wire } = block.wire;
++ return {
++ type: block.isError ? "web_search_tool_result_error" : "web_search_tool_result",
++ tool_use_id: block.blockId,
++ ...wire,
++ };
++}
++export function validateHostedSearchMessages(messages) {
++ for (const message of messages) {
++ if (message.role !== "assistant")
++ continue;
++ requireValid(Array.isArray(message.content));
++ for (const block of message.content) {
++ requireValid(record(block));
++ switch (block.type) {
++ case "hostedSearch": normalizeHostedSearchContent(block); break;
++ case "text": requireValid(typeof block.text === "string"); break;
++ case "thinking": requireValid(typeof block.thinking === "string"); break;
++ case "toolCall":
++ requireValid(nonempty(block.name) && nonempty(block.id) && record(block.arguments));
++ validateJson(block.arguments);
++ break;
++ default: throw new LocalRequestError("context-validation");
++ }
++ }
++ }
++}
+diff --git a/dist/utils/local-request-error.d.ts b/dist/utils/local-request-error.d.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..a72f65b33c64b89f118a59bd286e62624711fd90
+--- /dev/null
++++ b/dist/utils/local-request-error.d.ts
+@@ -0,0 +1,15 @@
++export type LocalRequestErrorPhase = "context-validation" | "context-estimation" | "request-preparation";
++export interface LocalRequestErrorDetails {
++ code: "LOCAL_REQUEST_ERROR";
++ phase: LocalRequestErrorPhase;
++ message: string;
++ causeName?: string;
++}
++export declare class LocalRequestError extends Error {
++ readonly code: "LOCAL_REQUEST_ERROR";
++ readonly phase: LocalRequestErrorPhase;
++ constructor(phase: LocalRequestErrorPhase, options?: ErrorOptions);
++}
++export declare function localRequestErrorDetails(error: unknown): LocalRequestErrorDetails | undefined;
++export declare function asLocalRequestError(error: unknown, phase: LocalRequestErrorPhase): unknown;
++export declare function prepareLocalRequest<T>(phase: LocalRequestErrorPhase, prepare: () => T): T;
+diff --git a/dist/utils/local-request-error.js b/dist/utils/local-request-error.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..4d276ddc8caee98dfeeeeaa9bcd234ad63dc414b
+--- /dev/null
++++ b/dist/utils/local-request-error.js
+@@ -0,0 +1,38 @@
++const messages = {
++ "context-validation": "Local request context validation failed",
++ "context-estimation": "Local request context estimation failed",
++ "request-preparation": "Local request preparation failed",
++};
++export class LocalRequestError extends Error {
++ code = "LOCAL_REQUEST_ERROR";
++ constructor(phase, options) {
++ // Expose only fixed descriptions; retain original data and underlying errors in cause.
++ super(messages[phase], options);
++ this.name = "LocalRequestError";
++ this.phase = phase;
++ }
++}
++export function localRequestErrorDetails(error) {
++ // Explicit markers work across packages/realms; never infer origin from TypeError, text, or absent responses.
++ if (!error || typeof error !== "object" || error.code !== "LOCAL_REQUEST_ERROR" ||
++ !Object.hasOwn(messages, error.phase))
++ return undefined;
++ return {
++ code: "LOCAL_REQUEST_ERROR",
++ phase: error.phase,
++ message: messages[error.phase],
++ ...(error.cause instanceof Error ? { causeName: error.cause.name } :
++ typeof error.causeName === "string" ? { causeName: error.causeName } : {}),
++ };
++}
++export function asLocalRequestError(error, phase) {
++ return localRequestErrorDetails(error) ? error : new LocalRequestError(phase, { cause: error });
++}
++export function prepareLocalRequest(phase, prepare) {
++ try {
++ return prepare();
++ }
++ catch (error) {
++ throw asLocalRequestError(error, phase);
++ }
++}
+diff --git a/dist/utils/local-request-stream.d.ts b/dist/utils/local-request-stream.d.ts
+new file mode 100644
+index 0000000000000000000000000000000000000000..879b78cbecb0cc2c4322049ed2c7d61f77be9375
+--- /dev/null
++++ b/dist/utils/local-request-stream.d.ts
+@@ -0,0 +1,3 @@
++import type { Api, AssistantMessageEventStream, Model } from "../types.ts";
++/** Guard synchronous adapter setup without classifying transport errors. */
++export declare function withLocalRequestErrors(model: Model<Api>, options: { signal?: AbortSignal } | undefined, prepare: () => AssistantMessageEventStream): AssistantMessageEventStream;
+diff --git a/dist/utils/local-request-stream.js b/dist/utils/local-request-stream.js
+new file mode 100644
+index 0000000000000000000000000000000000000000..5c63b882ae4cb618e964c5d2ce8d3c18e0fe4688
+--- /dev/null
++++ b/dist/utils/local-request-stream.js
+@@ -0,0 +1,24 @@
++import { AssistantMessageEventStream } from "./event-stream.js";
++import { asLocalRequestError, localRequestErrorDetails } from "./local-request-error.js";
++export function withLocalRequestErrors(model, options, prepare) {
++ try {
++ return prepare();
++ }
++ catch (error) {
++ // 只包围同步 setup/buildBaseOptions;网络及响应解析仍由原 adapter 处理。
++ const details = localRequestErrorDetails(asLocalRequestError(error, "request-preparation"));
++ const aborted = options?.signal?.aborted === true;
++ const message = {
++ role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id,
++ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
++ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
++ stopReason: aborted ? "aborted" : "error", timestamp: Date.now(),
++ errorMessage: aborted ? "Request was aborted" : details.message,
++ ...(aborted ? {} : { errorDetails: details }),
++ };
++ const stream = new AssistantMessageEventStream();
++ stream.push({ type: "error", reason: message.stopReason, error: message });
++ stream.end();
++ return stream;
++ }
++}
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 000000000..22c3f4176
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,279 @@
+diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js
+index 638646dacdbcb9c00bbc0de14f28abb700c8dc3f..8e8d0643d6e341a17243adae220bc9658a1eecb5 100644
+--- a/dist/core/agent-session.js
++++ b/dist/core/agent-session.js
+@@ -62,10 +62,10 @@ function withoutDeletedHeaders(headers) {
+ ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
+ : undefined;
+ }
+-function estimateMessagesTokens(messages) {
++function estimateMessagesTokens(messages, model) {
+ let tokens = 0;
+ for (const message of messages) {
+- tokens += estimateTokens(message);
++ tokens += estimateTokens(message, model);
+ }
+ return tokens;
+ }
+@@ -284,7 +284,7 @@ export class AgentSession {
+ const settings = this.settingsManager.getCompactionSettings(model);
+ if (!model ||
+ model.contextWindow <= 0 ||
+- !shouldCompact(estimateContextTokens(context.messages).tokens, model.contextWindow, settings)) {
++ !shouldCompact(estimateContextTokens(context.messages, model).tokens, model.contextWindow, settings)) {
+ return context;
+ }
+ await this._runAutoCompaction("threshold", false);
+@@ -1658,7 +1658,7 @@ export class AgentSession {
+ const newEntries = this.sessionManager.getEntries();
+ const sessionContext = this.sessionManager.buildSessionContext();
+ this.agent.state.messages = sessionContext.messages;
+- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
++ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages, requestModel);
+ // Get the saved compaction entry for the extension event
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
+ if (this._extensionRunner && savedCompactionEntry) {
+@@ -1820,7 +1820,7 @@ export class AgentSession {
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
+ if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
+ const messages = this.agent.state.messages;
+- const estimate = estimateContextTokens(messages);
++ const estimate = estimateContextTokens(messages, this.model ?? undefined);
+ // Without provider usage, estimate.tokens is the pure message-size estimate.
+ // Only usage-backed estimates need the stale pre-compaction check.
+ if (estimate.lastUsageIndex !== null) {
+@@ -1925,7 +1925,7 @@ export class AgentSession {
+ const newEntries = this.sessionManager.getEntries();
+ const sessionContext = this.sessionManager.buildSessionContext();
+ this.agent.state.messages = sessionContext.messages;
+- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
++ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages, requestModel);
+ // Get the saved compaction entry for the extension event
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
+ if (this._extensionRunner && savedCompactionEntry) {
+@@ -2852,7 +2852,7 @@ export class AgentSession {
+ return { tokens: null, contextWindow, percent: null };
+ }
+ }
+- const estimate = estimateContextTokens(this.messages);
++ const estimate = estimateContextTokens(this.messages, model);
+ const percent = (estimate.tokens / contextWindow) * 100;
+ return {
+ tokens: estimate.tokens,
+diff --git a/dist/core/bug-report.js b/dist/core/bug-report.js
+index bf7729fffd57d7168ae03945ea07631f76cc7325..794ec01736eec36bdb3141a223bcac7e05fad11c 100644
+--- a/dist/core/bug-report.js
++++ b/dist/core/bug-report.js
+@@ -232,12 +232,12 @@ Numbered list, as specific as the transcript allows.
+ Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.
+
+ Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;
+-function selectMessages(messages, tokenBudget) {
++function selectMessages(messages, tokenBudget, model) {
+ const selected = [];
+ let tokens = 0;
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index];
+- const next = estimateTokens(message);
++ const next = estimateTokens(message, model);
+ if (selected.length > 0 && tokens + next > tokenBudget)
+ break;
+ selected.push(message);
+@@ -249,7 +249,7 @@ function selectMessages(messages, tokenBudget) {
+ export async function generateBugReportSummary(options) {
+ const { model } = options;
+ const contextWindow = model.contextWindow > 0 ? model.contextWindow : 128_000;
+- const messages = selectMessages(options.messages, Math.floor(contextWindow * 0.6));
++ const messages = selectMessages(options.messages, Math.floor(contextWindow * 0.6), model);
+ const hint = options.hint?.trim();
+ const prompt = [
+ messages.length < options.messages.length
+diff --git a/dist/core/compaction/compaction.d.ts b/dist/core/compaction/compaction.d.ts
+index e6bfb766ea2659180c7182ee0307d0a015dd7e0b..a9a814d8701eb2ab0f535aa187923f87975a3c28 100644
+--- a/dist/core/compaction/compaction.d.ts
++++ b/dist/core/compaction/compaction.d.ts
+@@ -6,7 +6,7 @@
+ */
+ import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";
+ import { type RetryCallbacks, type RetryPolicy } from "@earendil-works/pi-ai";
+-import type { AssistantMessage, Model, SimpleStreamOptions, TranscriptContext, Usage } from "@earendil-works/pi-ai/compat";
++import type { Api, AssistantMessage, Model, SimpleStreamOptions, TranscriptContext, Usage } from "@earendil-works/pi-ai/compat";
+ import { type SessionEntry } from "../session-manager.ts";
+ import { type FileOperations } from "./utils.ts";
+ /** Details stored in CompactionEntry.details for file tracking */
+@@ -49,8 +49,9 @@ export interface ContextUsageEstimate {
+ /**
+ * Estimate context tokens from messages, using the last assistant usage when available.
+ * If there are messages after the last usage, estimate their tokens with estimateTokens.
++ * Pass `model` to scope hosted search replay projections to the estimation target.
+ */
+-export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
++export declare function estimateContextTokens(messages: AgentMessage[], model?: Model<Api>): ContextUsageEstimate;
+ /**
+ * Check if compaction should trigger based on context usage.
+ */
+@@ -58,8 +59,10 @@ export declare function shouldCompact(contextTokens: number, contextWindow: numb
+ /**
+ * Estimate token count for a message using chars/4 heuristic.
+ * This is conservative (overestimates tokens).
++ * Standard provider roles delegate to the pi-ai estimator; pass `model` to scope
++ * hosted search replay projections to the estimation target.
+ */
+-export declare function estimateTokens(message: AgentMessage): number;
++export declare function estimateTokens(message: AgentMessage, model?: Model<Api>): number;
+ /**
+ * Find the context-visible user-role message that starts the turn containing the given entry index.
+ * Returns -1 if no turn start found before the index.
+diff --git a/dist/core/compaction/compaction.js b/dist/core/compaction/compaction.js
+index 3141f9416d52f49cc1dac0ef94deb53a28db0173..cd8009dd728b6a916703caef2a8d886f4eb9cf60 100644
+--- a/dist/core/compaction/compaction.js
++++ b/dist/core/compaction/compaction.js
+@@ -4,8 +4,10 @@
+ * Pure functions for compaction logic. The session manager handles I/O,
+ * and after compaction the session is reloaded.
+ */
+-import { contentText, normalizeContext, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";
++import { contentText, LocalRequestError, normalizeContext, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";
+ import { completeSimple } from "@earendil-works/pi-ai/compat";
++import { estimateMessageTokens, getLastAssistantUsageInfo } from "@earendil-works/pi-ai/utils/estimate";
++import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";
+ import { convertToLlm } from "../messages.js";
+ import { buildSessionContext, sessionEntryToContextMessages, } from "../session-manager.js";
+ import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
+@@ -118,24 +120,19 @@ 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 from messages, using the last assistant usage when available.
+ * If there are messages after the last usage, estimate their tokens with estimateTokens.
++ * Provider-role estimation is delegated to pi-ai so hosted search replay projections and
++ * the prefix-timestamp usage anchor stay consistent with the provider request path.
+ */
+-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,
+@@ -147,7 +144,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,
+@@ -186,31 +183,22 @@ function estimateTextAndImageContentChars(content) {
+ /**
+ * Estimate token count for a message using chars/4 heuristic.
+ * This is conservative (overestimates tokens).
++ *
++ * Standard provider roles (system/user/assistant/toolResult) delegate to the pi-ai
++ * estimator so hosted search replay projections stay identical to the provider
++ * request path; custom session roles keep their local adapters below. `model`
++ * optionally scopes hosted search projection to the target model so a model
++ * switch cannot overcount replay blocks the target would drop.
+ */
+-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 + JSON.stringify(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);
+ }
+@@ -224,7 +212,7 @@ export function estimateTokens(message) {
+ return Math.ceil(chars / 4);
+ }
+ }
+- return 0;
++ throw new LocalRequestError("context-validation");
+ }
+ function isCutPointMessage(message) {
+ switch (message.role) {
+diff --git a/dist/core/compaction/utils.js b/dist/core/compaction/utils.js
+index bbbb6d1c80d66e2f4f539aed8dc263f30307b113..7d71b571f787d27d0d78b471a79ead7a7028f473 100644
+--- a/dist/core/compaction/utils.js
++++ b/dist/core/compaction/utils.js
+@@ -2,6 +2,7 @@
+ * Shared utilities for compaction and branch summarization.
+ */
+ import { contentText } from "@earendil-works/pi-ai";
++import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";
+ export function createFileOps() {
+ return {
+ read: new Set(),
+@@ -102,6 +103,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);
+@@ -113,6 +115,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(JSON.stringify(projection));
++ }
++ }
+ }
+ if (thinkingParts.length > 0) {
+ parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);
+@@ -123,6 +132,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/pnpm-lock.yaml b/pnpm-lock.yaml
index 4648eecd0..8ca258983 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -6,22 +6,25 @@ settings:
overrides:
'@tailwindcss/node>lightningcss': 1.33.0
- dompurify@3: '>=3.4.13 <4'
brace-expansion@1: '>=1.1.17 <2'
brace-expansion@2: '>=2.1.4 <3'
brace-expansion@5: '>=5.0.9 <6'
+ dompurify@3: '>=3.4.13 <4'
fast-uri@3: '>=3.1.5 <4'
- undici@6: '>=6.28.0 <7'
js-yaml@4: '>=4.3.1 <5'
+ undici@6: '>=6.28.0 <7'
vite@5: '>=6.4.3 <7'
patchedDependencies:
'@earendil-works/[email protected]':
- hash: d02b52788e66e62012d5b9d24599bfc5cb82e0cf0c8afee2b208eb5c0ff7cecb
+ hash: 62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1
path: patches/@[email protected]
'@earendil-works/[email protected]':
- hash: 1b38ecb724d9d9ff4135d8ec6dc92e3ba704c06baad8d221ca6191471875b825
+ hash: db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe
path: patches/@[email protected]
+ '@earendil-works/[email protected]':
+ hash: 60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227
+ path: patches/@[email protected]
importers:
@@ -42,7 +45,7 @@ importers:
devDependencies:
'@earendil-works/pi-ai':
specifier: 0.86.1
- version: 0.86.1(patch_hash=1b38ecb724d9d9ff4135d8ec6dc92e3ba704c06baad8d221ca6191471875b825)([email protected])([email protected])
+ version: 0.86.1(patch_hash=db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe)([email protected])([email protected])
'@pi-desktop/agent-host':
specifier: workspace:*
version: link:../../packages/agent-host
@@ -225,13 +228,13 @@ importers:
dependencies:
'@earendil-works/pi-agent-core':
specifier: 0.86.1
- version: 0.86.1(patch_hash=d02b52788e66e62012d5b9d24599bfc5cb82e0cf0c8afee2b208eb5c0ff7cecb)([email protected])([email protected])
+ version: 0.86.1(patch_hash=62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1)([email protected])([email protected])
'@earendil-works/pi-ai':
specifier: 0.86.1
- version: 0.86.1(patch_hash=1b38ecb724d9d9ff4135d8ec6dc92e3ba704c06baad8d221ca6191471875b825)([email protected])([email protected])
+ version: 0.86.1(patch_hash=db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe)([email protected])([email protected])
'@earendil-works/pi-coding-agent':
specifier: 0.86.1
+ version: 0.86.1(patch_hash=60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227)([email protected])([email protected])
'@pi-desktop/shared':
specifier: workspace:*
version: link:../shared
@@ -4819,10 +4822,10 @@ snapshots:
dependencies:
esbuild: 0.28.2
- '@earendil-works/[email protected](patch_hash=d02b52788e66e62012d5b9d24599bfc5cb82e0cf0c8afee2b208eb5c0ff7cecb)([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1)([email protected])([email protected])':
dependencies:
'@earendil-works/chord': 0.86.1
- '@earendil-works/pi-ai': 0.86.1(patch_hash=1b38ecb724d9d9ff4135d8ec6dc92e3ba704c06baad8d221ca6191471875b825)([email protected])([email protected])
+ '@earendil-works/pi-ai': 0.86.1(patch_hash=db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe)([email protected])([email protected])
'@earendil-works/pi-telemetry': 0.86.1
diff: 8.0.4
ignore: 7.0.8
@@ -4837,7 +4840,7 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected](patch_hash=1b38ecb724d9d9ff4135d8ec6dc92e3ba704c06baad8d221ca6191471875b825)([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe)([email protected])([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.124.0([email protected])
'@aws-sdk/client-bedrock-runtime': 3.1127.0
@@ -4858,11 +4861,11 @@ snapshots:
- ws
- zod
+ '@earendil-works/[email protected](patch_hash=60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227)([email protected])([email protected])':
dependencies:
'@earendil-works/chord': 0.86.1
- '@earendil-works/pi-agent-core': 0.86.1(patch_hash=d02b52788e66e62012d5b9d24599bfc5cb82e0cf0c8afee2b208eb5c0ff7cecb)([email protected])([email protected])
- '@earendil-works/pi-ai': 0.86.1(patch_hash=1b38ecb724d9d9ff4135d8ec6dc92e3ba704c06baad8d221ca6191471875b825)([email protected])([email protected])
+ '@earendil-works/pi-agent-core': 0.86.1(patch_hash=62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1)([email protected])([email protected])
+ '@earendil-works/pi-ai': 0.86.1(patch_hash=db5e0b64bd62cea3db7dbf9102f3602a9166aa01f49fd4e5123d57dc1a87f3fe)([email protected])([email protected])
'@earendil-works/pi-tui': 0.86.1
'@silvia-odwyer/photon-node': 0.3.4
chalk: 6.0.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index dff0ad25d..f07d07880 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -2,17 +2,22 @@ packages:
- apps/*
- packages/*
- docs
-# pnpm defaults to `lowest-direct`, which makes a plain `pnpm update` resolve
-# every range to its floor — silently downgrading dependencies instead of
-# refreshing them. Pin the intent: `pnpm update` means "newest within range".
-resolutionMode: highest
allowBuilds:
- electron: true
- esbuild: true
'@google/genai': true
- protobufjs: true
+ electron: true
electron-winstaller: true
+ esbuild: true
node-pty: true
+ protobufjs: true
+# Drop this list once the pinned @earendil-works packages are older than
+# pnpm's supply-chain age gate (packages published within the last day).
+minimumReleaseAgeExclude:
+ - '@earendil-works/[email protected]'
+ - '@earendil-works/[email protected]'
+ - '@earendil-works/[email protected]'
+ - '@earendil-works/[email protected]'
+ - '@earendil-works/[email protected]'
+ - '@earendil-works/[email protected]'
# Advisory fixes for transitives whose parents still resolve the vulnerable
# version. Drop each one once its parent ships a release that resolves the
# patched version on its own.
@@ -21,18 +26,18 @@ overrides:
# Custom Highlight API selector `::highlight()`. The parser fix ships in
# lightningcss 1.33.0.
'@tailwindcss/node>lightningcss': 1.33.0
- # Ships in the app. mermaid allows ^3.3.3 but resolves its own copy, so the
- # renderer would load an unpatched sanitizer next to our patched one.
- dompurify@3: '>=3.4.13 <4' # detached-subtree XSS, via mermaid
# Build toolchain only (electron-builder, node-gyp) — never reaches users.
# Kept current so `pnpm audit` stays quiet and a finding that *does* reach
# users stands out.
brace-expansion@1: '>=1.1.17 <2' # GHSA via minimatch@3
brace-expansion@2: '>=2.1.4 <3' # GHSA via @electron/universal, jake
brace-expansion@5: '>=5.0.9 <6' # GHSA via app-builder-lib
+ # Ships in the app. mermaid allows ^3.3.3 but resolves its own copy, so the
+ # renderer would load an unpatched sanitizer next to our patched one.
+ dompurify@3: '>=3.4.13 <4' # detached-subtree XSS, via mermaid
fast-uri@3: '>=3.1.5 <4' # GHSA via ajv@8
- undici@6: '>=6.28.0 <7' # GHSA via node-gyp@12
js-yaml@4: '>=4.3.1 <5' # CVE-2026-59870 via app-builder-lib
+ undici@6: '>=6.28.0 <7' # GHSA via node-gyp@12
# Docs site only. vitepress 1.6.4 asks for vite ^5.4.14 and no vite 5 is
# patched — the fixes for all four advisories (server.fs.deny bypass, esbuild
# dev-server CORS, optimized-deps `.map` traversal, launch-editor UNC) land in
@@ -40,15 +45,11 @@ overrides:
# a major its parent has not declared. Verified against `docs:build` and
# `docs:dev` (serves 200); drop it for vitepress 2 once that ships stable.
vite@5: '>=6.4.3 <7'
-# Drop this list once the pinned @earendil-works packages are older than
-# pnpm's supply-chain age gate (packages published within the last day).
-minimumReleaseAgeExclude:
- - '@earendil-works/[email protected]'
- - '@earendil-works/[email protected]'
- - '@earendil-works/[email protected]'
- - '@earendil-works/[email protected]'
- - '@earendil-works/[email protected]'
- - '@earendil-works/[email protected]'
patchedDependencies:
'@earendil-works/[email protected]': patches/@[email protected]
'@earendil-works/[email protected]': patches/@[email protected]
+ '@earendil-works/[email protected]': patches/@[email protected]
+# pnpm defaults to `lowest-direct`, which makes a plain `pnpm update` resolve
+# every range to its floor — silently downgrading dependencies instead of
+# refreshing them. Pin the intent: `pnpm update` means "newest within range".
+resolutionMode: highest
diff --git a/scripts/e2e-hosted-search.mjs b/scripts/e2e-hosted-search.mjs
new file mode 100644
index 000000000..eefcdc372
--- /dev/null
+++ b/scripts/e2e-hosted-search.mjs
@@ -0,0 +1,161 @@
+#!/usr/bin/env node
+// Offline artifact-level regression. Default invocation rebuilds the production
+// sidecar; --bundle runs an explicitly supplied artifact (e.g. a saved red baseline).
+// No Electron, host-core, database, user config, live credentials, or source mocks.
+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 { 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";
+
+const { values } = parseArgs({ options: {
+ bundle: { type: "string" }, "timeout-ms": { type: "string", default: "15000" },
+ help: { type: "boolean", short: "h" },
+} });
+if (values.help) {
+ console.log(`Usage: node scripts/e2e-hosted-search.mjs [--bundle PATH] [--timeout-ms 15000]
+Default: pnpm --filter @pi-desktop/shared build, then @pi-desktop/agent-runtime bundle.
+--bundle: skip rebuilding and run that explicit artifact, retaining its SHA-256.
+Evidence and isolated homes stay under PI_SCRATCH_DIR or mkdtemp(os.tmpdir()).
+Seven cases: next prompt, Read, instruction change, real Task/TaskWait, persisted restore, two invalid-history cases.
+Files are retained for inspection; no automatic deletion and no dependency installation.
+Reviewed source, patches, and lock metadata are fingerprinted before the build and again
+when the run ends; any change between the two fails the run.`);
+} else {
+ const root = resolve(import.meta.dirname, "..");
+ const timeoutMs = Number(values["timeout-ms"]);
+ assert.ok(Number.isFinite(timeoutMs) && timeoutMs >= 1000 && timeoutMs <= 120000, "timeout must be 1000..120000 ms");
+ // Scratch allocation is the one step that has nowhere to record a failure: if
+ // it throws there is no evidence directory, so the uncaught error on stderr is
+ // the intended signal. There is deliberately no fallback location.
+ const dir = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "hosted-search-e2e-"));
+ console.log(`Evidence: ${dir}`);
+ const evidence = { startedAt: new Date().toISOString() };
+ // Declared before the guard so the `finally` below can still run them when an
+ // early step (env isolation, dependency inspection, pnpm) fails.
+ let git = () => "unavailable";
+ let fingerprint = async () => null;
+ try {
+ const env = await isolatedEnv(join(dir, "build"));
+ // Reuse the already resolved project pnpm, not a PATH version-manager shim
+ // that might try to bootstrap another copy after HOME becomes isolated.
+ env.npm_config_manage_package_manager_versions = "false";
+ const pnpmEntry = process.env.npm_execpath;
+ const pnpmCommand = pnpmEntry && /\.[cm]?js$/.test(pnpmEntry) ? process.execPath : pnpmEntry ?? "pnpm";
+ const pnpmArgs = pnpmEntry && /\.[cm]?js$/.test(pnpmEntry) ? [pnpmEntry] : [];
+ const runPnpm = (args) => execFileSync(pnpmCommand, [...pnpmArgs, ...args], {
+ cwd: root, env, encoding: "utf8", timeout: 120000, maxBuffer: 8_000_000,
+ });
+ git = (...args) => {
+ try {
+ return execFileSync("git", args, { cwd: root, env, encoding: "utf8", timeout: 20000, maxBuffer: 32_000_000 }).trim();
+ } catch { return "unavailable"; }
+ };
+ const hash = async (path) => createHash("sha256").update(await readFile(path)).digest("hex");
+ // Reviewed source, patch, and lock metadata only: dependency trees and
+ // generated bundles are build outputs, so hashing them would fingerprint the
+ // build instead of the artifact under review.
+ const sourceScope = ["packages/agent-runtime", "packages/shared", "patches", "pnpm-lock.yaml", "pnpm-workspace.yaml", "package.json", "scripts/e2e-hosted-search.mjs", "scripts/e2e/hosted-search-provider.mjs", "scripts/e2e/hosted-search-sidecar.mjs", "scripts/e2e/hosted-search-scenarios.mjs"];
+ const generated = /(^|\/)(node_modules|dist|dist-bundle|coverage|\.turbo)(\/|$)|\.tsbuildinfo$/;
+ const listGit = (args) => {
+ try {
+ return execFileSync("git", args, { cwd: root, env, encoding: "utf8", timeout: 20000, maxBuffer: 32_000_000 })
+ .split("\0").map((entry) => entry.trim()).filter(Boolean);
+ } catch { return null; }
+ };
+ // One digest over tracked files plus untracked deliverables in scope: the
+ // `git status --short` string alone cannot reveal an edit that leaves the
+ // dirty set identical.
+ fingerprint = async () => {
+ const tracked = listGit(["ls-files", "-z", "--", ...sourceScope]);
+ const untracked = listGit(["ls-files", "-z", "--others", "--exclude-standard", "--", ...sourceScope]);
+ if (!tracked || !untracked) return null;
+ const files = [...new Set([...tracked, ...untracked])].filter((path) => !generated.test(path)).sort();
+ const digests = [];
+ for (const path of files) {
+ digests.push(`${path} ${await hash(join(root, path))}`);
+ }
+ return { files: files.length, sha256: createHash("sha256").update(digests.join("\n")).digest("hex") };
+ };
+ evidence.nodeVersion = process.version;
+ evidence.pnpmVersion = values.bundle ? "not invoked (supplied artifact)" : runPnpm(["--version"]).trim();
+ evidence.installedDependencies = {};
+ for (const name of ["pi-ai", "pi-agent-core", "pi-coding-agent"]) {
+ const manifest = JSON.parse(await readFile(join(root, "packages/agent-runtime/node_modules/@earendil-works", name, "package.json"), "utf8"));
+ evidence.installedDependencies[name] = manifest.version;
+ assert.equal(manifest.version, "0.86.1", `${name} must match the locked pi version`);
+ }
+ evidence.lockfileSha256 = await hash(join(root, "pnpm-lock.yaml"));
+ evidence.head = git("rev-parse", "HEAD");
+ evidence.statusBefore = git("status", "--short");
+ evidence.build = values.bundle ? "explicit supplied artifact; not rebuilt by this invocation" : "production package build + bundle";
+ evidence.sourceFingerprintBefore = await fingerprint();
+ assert.ok(evidence.head !== "unavailable" && evidence.sourceFingerprintBefore, "build source identity is unavailable");
+ if (!values.bundle) {
+ for (const [pkg, script] of [["@pi-desktop/shared", "build"], ["@pi-desktop/agent-runtime", "bundle"]]) {
+ const args = ["--filter", pkg, script];
+ console.log(`Build: pnpm ${args.join(" ")}`);
+ const output = runPnpm(args);
+ await writeFile(join(dir, `${script}.log`), output);
+ }
+ }
+ const source = resolve(root, values.bundle ?? "packages/agent-runtime/dist-bundle/sidecar.js");
+ const bundle = join(dir, "sidecar.mjs");
+ 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.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);
+ evidence.bundleSourceRewrittenDuringRun = evidence.bundleSourceSha256After !== evidence.sha256;
+ assert.equal(evidence.bundleSourceRewrittenDuringRun, false, "bundle source changed during qualification");
+ evidence.passed = evidence.results.every((result) => result.passed);
+ if (!evidence.passed) process.exitCode = 1;
+ } catch (error) {
+ evidence.passed = false;
+ evidence.error = error.stack ?? String(error);
+ console.error(evidence.error);
+ process.exitCode = 1;
+ } finally {
+ // The evidence directory exists by now, so no failure may escape before
+ // result.json is written.
+ try {
+ evidence.sourceFingerprintAfter = await fingerprint();
+ } catch (error) {
+ evidence.sourceFingerprintError = error.stack ?? String(error);
+ }
+ const before = evidence.sourceFingerprintBefore;
+ const after = evidence.sourceFingerprintAfter;
+ evidence.sourceChangedDuringRun = Boolean(before && after && before.sha256 !== after.sha256);
+ if (!before || !after || evidence.sourceChangedDuringRun) {
+ evidence.qualificationFailure = !before || !after
+ ? "reviewed source identity could not be verified"
+ : "reviewed source, lockfile, or patch artifacts changed during the run";
+ evidence.passed = false;
+ process.exitCode = 1;
+ }
+ evidence.statusAfter = git("status", "--short");
+ evidence.finishedAt = new Date().toISOString();
+ try {
+ await writeFile(join(dir, "result.json"), JSON.stringify(evidence, null, 2));
+ } catch (error) {
+ console.error(`failed to write result.json: ${error.message}`);
+ evidence.passed = false;
+ process.exitCode = 1;
+ }
+ console.log(`Result: ${evidence.passed ? "PASS" : "FAIL"}; ${join(dir, "result.json")}`);
+ }
+}
diff --git a/scripts/e2e/hosted-search-provider.mjs b/scripts/e2e/hosted-search-provider.mjs
new file mode 100644
index 000000000..6cb19a683
--- /dev/null
+++ b/scripts/e2e/hosted-search-provider.mjs
@@ -0,0 +1,158 @@
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+export const SEARCH_ITEM = {
+ id: "ws_offline_search", type: "web_search_call", status: "completed",
+ action: {
+ type: "search", query: "offline hosted search fixture",
+ sources: [{ type: "url", url: "http://127.0.0.1/offline-source", title: "Offline source" }],
+ },
+};
+
+export function assertReplay(body) {
+ const items = body.input.filter((item) => item.type === "web_search_call");
+ assert.deepEqual(items, [SEARCH_ITEM], "the next real provider request must preserve the nameless search wire item");
+ assert.equal(Object.hasOwn(items[0], "name"), false);
+ assert.equal(body.input.some((item) => item.type === "function_call" && /search/i.test(item.name)), false,
+ "hosted search must not become a local function call");
+}
+
+export function functionResult(body, name) {
+ const call = body.input.find((item) => item.type === "function_call" && item.name === name);
+ assert.ok(call, `${name} function call missing from provider history`);
+ const result = body.input.find((item) => item.type === "function_call_output" && item.call_id === call.call_id);
+ assert.ok(result, `${name} result missing from provider history`);
+ return result.output;
+}
+
+export function providerConfig(baseUrl, modelId = "offline-parent") {
+ const url = new URL(baseUrl);
+ assert.equal(url.hostname, "127.0.0.1");
+ assert.equal(url.protocol, "http:");
+ return {
+ id: "offline-provider", name: "Offline Responses fixture", baseUrl,
+ apiKey: "offline-test", authKind: "api_key", apiStyle: "responses",
+ modelId, supportsReasoning: false, supportedThinkingLevels: ["off"],
+ modelConfig: {
+ id: modelId, name: modelId, api: "openai-responses", provider: "offline-provider",
+ baseUrl, reasoning: false, input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ contextWindow: 128000, maxTokens: 4096, webSearch: true,
+ },
+ };
+}
+
+// These are provider wire fixtures, not Agent/estimator mocks. The production
+// Responses adapter must parse every item and serialize it again on continuation.
+function respondSse(res, model, plan, serial) {
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
+ let sequence = 0;
+ const emit = (type, fields) => res.write(
+ `event: ${type}\ndata: ${JSON.stringify({ type, sequence_number: sequence++, ...fields })}\n\n`,
+ );
+ const response = {
+ id: `resp_offline_${serial}`, object: "response", created_at: 1,
+ model, status: "in_progress", output: [], error: null, incomplete_details: null,
+ };
+ emit("response.created", { response });
+ emit("response.in_progress", { response });
+ const output = [];
+ if (plan.search) {
+ const output_index = output.length;
+ emit("response.output_item.added", {
+ output_index, item: { id: SEARCH_ITEM.id, type: "web_search_call", status: "in_progress" },
+ });
+ for (const status of ["in_progress", "searching", "completed"]) {
+ emit(`response.web_search_call.${status}`, { output_index, item_id: SEARCH_ITEM.id });
+ }
+ emit("response.output_item.done", { output_index, item: SEARCH_ITEM });
+ output.push(SEARCH_ITEM);
+ }
+ if (plan.text) {
+ const output_index = output.length;
+ const item = {
+ id: `msg_offline_${serial}`, type: "message", role: "assistant", status: "in_progress", content: [],
+ };
+ const locator = { output_index, item_id: item.id, content_index: 0 };
+ emit("response.output_item.added", { output_index, item });
+ emit("response.content_part.added", { ...locator, part: { type: "output_text", text: "", annotations: [] } });
+ emit("response.output_text.delta", { ...locator, delta: plan.text });
+ const part = { type: "output_text", text: plan.text, annotations: [] };
+ emit("response.output_text.done", { ...locator, text: plan.text });
+ emit("response.content_part.done", { ...locator, part });
+ const completed = { ...item, status: "completed", content: [part] };
+ emit("response.output_item.done", { output_index, item: completed });
+ output.push(completed);
+ }
+ if (plan.tool) {
+ const output_index = output.length;
+ const args = JSON.stringify(plan.tool.args);
+ const item = {
+ id: `fc_offline_${serial}`, call_id: `call_offline_${serial}`, type: "function_call",
+ name: plan.tool.name, arguments: "", status: "in_progress",
+ };
+ const locator = { output_index, item_id: item.id };
+ emit("response.output_item.added", { output_index, item });
+ emit("response.function_call_arguments.delta", { ...locator, delta: args });
+ emit("response.function_call_arguments.done", { ...locator, arguments: args });
+ const completed = { ...item, status: "completed", arguments: args };
+ emit("response.output_item.done", { output_index, item: completed });
+ output.push(completed);
+ }
+ emit("response.completed", {
+ response: {
+ ...response, status: "completed", output,
+ usage: {
+ input_tokens: 1000, output_tokens: 30, total_tokens: 1030,
+ input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 },
+ },
+ },
+ });
+ res.end();
+}
+
+export async function startProvider(dir, handler) {
+ const requests = [];
+ let failure;
+ const server = createServer(async (req, res) => {
+ try {
+ assert.equal(req.socket.remoteAddress, "127.0.0.1", "non-loopback connection rejected");
+ assert.equal(req.headers.host, `127.0.0.1:${server.address().port}`);
+ assert.equal(req.method, "POST");
+ assert.equal(req.url, "/v1/responses");
+ assert.equal(req.headers.authorization, "Bearer offline-test");
+ let raw = "";
+ for await (const chunk of req) {
+ raw += chunk;
+ assert.ok(Buffer.byteLength(raw) < 2_000_000, "fixture request size limit");
+ }
+ const body = JSON.parse(raw);
+ requests.push(body);
+ assert.equal(body.stream, true);
+ assert.ok(body.tools.some((tool) => tool.type === "web_search"), "native search must be enabled on the real request");
+ const plan = await handler(body, requests);
+ respondSse(res, body.model, plan, requests.length);
+ } catch (error) {
+ failure ??= error;
+ if (!res.headersSent) res.writeHead(400, { "Content-Type": "application/json" });
+ res.end(JSON.stringify({ error: { message: error.message, type: "invalid_request_error" } }));
+ }
+ });
+ server.requestTimeout = 5000;
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ return {
+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`, requests,
+ check() { if (failure) throw failure; },
+ async close() {
+ const closed = new Promise((resolve) => server.close(resolve));
+ server.closeAllConnections();
+ await closed;
+ await writeFile(join(dir, "provider-requests.json"), JSON.stringify(requests, null, 2));
+ },
+ };
+}
diff --git a/scripts/e2e/hosted-search-scenarios.mjs b/scripts/e2e/hosted-search-scenarios.mjs
new file mode 100644
index 000000000..323a038c0
--- /dev/null
+++ b/scripts/e2e/hosted-search-scenarios.mjs
@@ -0,0 +1,254 @@
+import assert from "node:assert/strict";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { OfflineSidecar, fixtureHost } from "./hosted-search-sidecar.mjs";
+import { assertReplay, functionResult, providerConfig, SEARCH_ITEM, startProvider } from "./hosted-search-provider.mjs";
+
+function parameters(baseUrl, dir, sessionId) {
+ return {
+ sessionId, mode: "agent", thinkingLevel: "off", infiniteProviderRetry: false,
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ provider: providerConfig(baseUrl), scratchDir: dir, projectPath: dir,
+ pluginTools: [], pluginSkills: [], trustedExtensions: [],
+ };
+}
+
+function assertText(sidecar, text) {
+ assert.ok([...sidecar.messages.values()].some((message) => message.role === "assistant" && message.content === text),
+ `missing completed assistant message: ${text}`);
+}
+
+function assertSearch(sidecar) {
+ const message = [...sidecar.messages.values()].find((entry) => entry.hostedSearch);
+ assert.ok(message, "search must reach the persisted UiMessage shape");
+ assert.equal(message.hostedSearch.status, "completed");
+ assert.equal(message.usage?.inputTokens, 1000, "provider usage must reach the real runtime before continuation");
+ const replay = message.hostedSearch.replay;
+ assert.ok(replay?.some((block) => block.phase === "web_search_call" && block.blockId === SEARCH_ITEM.id));
+ const block = replay.find((entry) => entry.blockId === SEARCH_ITEM.id);
+ assert.equal(Object.hasOwn(block, "name"), false, "the fixture must exercise a genuinely nameless search block");
+ assert.deepEqual(block.wire, SEARCH_ITEM);
+ assert.ok(sidecar.events.some(({ event }) => event.type === "message_update" && event.message?.hostedSearch),
+ "search activity must stream through the real agent loop");
+}
+
+function assertTool(body, name) {
+ assert.ok(body.tools.some((tool) => tool.type === "function" && tool.name === name), `${name} must be advertised`);
+}
+
+// Each scenario owns a fresh process and fixture server. A red case cannot
+// poison later cases; all failures retain their own transport evidence.
+async function scenario(bundle, root, name, timeoutMs, handler, run) {
+ const dir = join(root, name);
+ await mkdir(dir, { recursive: true });
+ const provider = await startProvider(dir, handler);
+ const children = [];
+ const start = async (suffix = "runtime", host = fixtureHost()) => {
+ const child = await OfflineSidecar.start(bundle, join(dir, suffix), host, timeoutMs);
+ children.push(child);
+ return child;
+ };
+ try {
+ await run({ provider, start, dir });
+ provider.check();
+ for (const child of children) if (!child.stopping) child.check();
+ return { name, passed: true, requests: provider.requests.length };
+ } catch (error) {
+ try { provider.check(); } catch (providerError) { error = providerError; }
+ return { name, passed: false, requests: provider.requests.length, error: error.stack ?? String(error) };
+ } finally {
+ try { await Promise.all(children.map((child) => child.stop())); }
+ finally { await provider.close(); }
+ }
+}
+
+export async function runScenarios(bundle, root, timeoutMs, report) {
+ const results = [];
+ const run = async (...args) => {
+ const result = await scenario(bundle, root, args[0], timeoutMs, ...args.slice(1));
+ results.push(result);
+ report(result);
+ };
+
+ await run("search-next-prompt", (body, requests) => {
+ if (requests.length === 1) return { search: true, text: "SEARCH_FINISHED" };
+ assert.equal(requests.length, 2, "unexpected retry/extra parent request");
+ assertReplay(body);
+ assert.match(JSON.stringify(body.input), /NEW_USER_PROMPT/);
+ return { text: "FOLLOWUP_FINISHED" };
+ }, async ({ provider, start, dir }) => {
+ const sidecar = await start();
+ const params = parameters(provider.baseUrl, dir, "next-prompt");
+ await sidecar.prompt(params, "Search the offline fixture.");
+ assertSearch(sidecar);
+ assertText(sidecar, "SEARCH_FINISHED");
+ await sidecar.prompt(params, "NEW_USER_PROMPT: use the previous search.");
+ assertText(sidecar, "FOLLOWUP_FINISHED");
+ assert.equal(provider.requests.length, 2);
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "session.get").length, 1,
+ "same-config next prompt must reuse the live runtime, not restore history");
+ });
+
+ for (const instructions of [false, true]) {
+ await run(instructions ? "search-read-instruction-change" : "search-read", (body, requests) => {
+ if (requests.length === 1) {
+ assertTool(body, "Read");
+ assert.doesNotMatch(JSON.stringify(body.input), /OFFLINE_NESTED_RULE/);
+ return { search: true, tool: { name: "Read", args: { path: "nested/fixture.txt" } } };
+ }
+ assert.equal(requests.length, 2, "Read continuation must not retry");
+ assertReplay(body);
+ assert.match(functionResult(body, "Read"), /OFFLINE_READ_RESULT/);
+ if (instructions) assert.match(JSON.stringify(body.input), /OFFLINE_NESTED_RULE/,
+ "path instruction resolution must actually change the next provider request");
+ return { text: "READ_CONTINUED" };
+ }, async ({ provider, start, dir }) => {
+ const sidecar = await start("runtime", fixtureHost({ instructions }));
+ await sidecar.prompt(parameters(provider.baseUrl, dir, "read"), "Search, then read nested/fixture.txt and continue.");
+ assertSearch(sidecar);
+ assertText(sidecar, "READ_CONTINUED");
+ assert.equal(provider.requests.length, 2);
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "tools.execute").length, 1);
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "project.instructions.resolve").length, 1);
+ });
+ }
+
+ let parentRequests = 0;
+ let delegateRequests = 0;
+ await run("search-task-delegation", (body) => {
+ if (body.model === "offline-explorer") {
+ delegateRequests++;
+ assert.equal(delegateRequests, 1);
+ assert.match(JSON.stringify(body.input), /OFFLINE_DELEGATE_BRIEF/);
+ assertTool(body, "Read");
+ assert.equal(body.tools.some((tool) => tool.name === "Task"), false, "delegate must use its own tool scope");
+ return { text: "EXPLORER_REAL_RUNTIME_REPORT" };
+ }
+ assert.equal(body.model, "offline-parent");
+ parentRequests++;
+ if (parentRequests === 1) {
+ assertTool(body, "Task");
+ return {
+ search: true,
+ tool: { name: "Task", args: { agent: "explorer", task: "OFFLINE_DELEGATE_BRIEF: report the fixture finding.", description: "Offline fixture exploration" } },
+ };
+ }
+ assertReplay(body);
+ if (parentRequests === 2) {
+ assertTool(body, "TaskWait");
+ const result = functionResult(body, "Task");
+ const id = result.match(/Delegation (\S+) started:/)?.[1];
+ assert.ok(id, `Task must start a real delegate: ${result}`);
+ return { tool: { name: "TaskWait", args: { delegationIds: [id], timeoutSeconds: 5 } } };
+ }
+ assert.equal(parentRequests, 3, "parent should converge without retry or duplicate idle-resume");
+ assert.match(functionResult(body, "TaskWait"), /EXPLORER_REAL_RUNTIME_REPORT/);
+ return { text: "PARENT_DELEGATION_CONVERGED" };
+ }, async ({ provider, start, dir }) => {
+ const sidecar = await start();
+ const params = parameters(provider.baseUrl, dir, "task");
+ params.subagents = [{
+ name: "explorer", description: "Inspect the offline fixture", tools: ["Read"],
+ prompt: "You are the offline explorer. Return the fixture report.", source: "builtin",
+ model: { providerId: "offline-provider", modelId: "offline-explorer" },
+ thinkingLevel: "off", permission: "inherit", idleTimeoutSeconds: 10, maxDurationSeconds: 15,
+ }];
+ params.subagentProviders = { "offline-provider/offline-explorer": providerConfig(provider.baseUrl, "offline-explorer") };
+ await sidecar.prompt(params, "Search, delegate to explorer, wait for its result and synthesize.");
+ assertSearch(sidecar);
+ assertText(sidecar, "PARENT_DELEGATION_CONVERGED");
+ assert.equal(delegateRequests, 1, "Task must reach a distinct real provider binding");
+ assert.equal(parentRequests, 3);
+ assert.equal(sidecar.hostCalls.some((call) => call.method === "tools.execute"), false,
+ "Task and TaskWait cannot be synthetic host tools");
+ assert.ok([...sidecar.messages.values()].some((message) =>
+ message.parentToolCallId && message.content === "EXPLORER_REAL_RUNTIME_REPORT"),
+ "real delegate transcript must carry the parent tool correlation");
+ });
+
+ await run("search-persist-restore", (body, requests) => {
+ if (requests.length === 1) return { search: true, text: "PERSIST_SEARCH" };
+ assert.equal(requests.length, 2);
+ assertReplay(body);
+ assert.match(JSON.stringify(body.input), /RESTORED_USER_PROMPT/);
+ return { text: "RESTORED_SEARCH_CONTINUED" };
+ }, async ({ provider, start, dir }) => {
+ const first = await start("before-restart");
+ const params = parameters(provider.baseUrl, dir, "persisted-session");
+ await first.prompt(params, "Search and persist this conversation.");
+ assertSearch(first);
+ const historyPath = join(dir, "ui-history.json");
+ const history = [...first.messages.values()];
+ assert.ok(history.some((message) => message.role === "user"), "persist the host-owned user row too");
+ await writeFile(historyPath, JSON.stringify(history, null, 2));
+ await first.stop();
+ // Deliberately cross a JSON/disk boundary and restart the Node process. No
+ // historyToEntries shortcut and no live AgentMessage injected into runtime.
+ const restored = JSON.parse(await readFile(historyPath, "utf8"));
+ const second = await start("after-restart", fixtureHost({ history: restored }));
+ await second.prompt(params, "RESTORED_USER_PROMPT: continue using the saved search.");
+ assertText(second, "RESTORED_SEARCH_CONTINUED");
+ assert.equal(second.hostCalls.filter((call) => call.method === "session.get").length, 1);
+ assert.equal(provider.requests.length, 2);
+ });
+ for (const replay of [{ invalid: true }, [{ type: "hostedSearch", phase: "unknown", blockId: "private-fixture-value" }]]) {
+ await run(Array.isArray(replay) ? "invalid-search-phase" : "invalid-search-container", () => {
+ assert.fail("invalid restored history must never reach the provider");
+ }, async ({ provider, start, dir }) => {
+ const history = [{
+ id: "invalid-history", role: "assistant", content: "stored result", status: "complete",
+ createdAt: "2026-09-20T00:00:00.000Z",
+ hostedSearch: { status: "completed", rounds: [], replay },
+ }];
+ // Serve the malformed row to the failing session only: the recovery prompt
+ // below opens a clean session that must still be able to run.
+ const fixture = fixtureHost({ history: [] });
+ const host = (method, params) => method === "session.get" && params.id === "invalid-history"
+ ? { session: { id: params.id, messages: history } }
+ : fixture(method, params);
+ const sidecar = await start("runtime", host);
+ const healthBefore = await sidecar.call("sidecar.health");
+ assert.equal(healthBefore.runtimes, 0, "a fresh fixture process must not own a live runtime");
+ await assert.rejects(sidecar.call("agent.prompt", {
+ ...parameters(provider.baseUrl, dir, "invalid-history"), content: "Continue the restored history.",
+ }), (error) => {
+ const rpc = JSON.parse(error.message);
+ assert.equal(rpc.code, -32000);
+ assert.equal(rpc.data.errorCode, "INTERNAL");
+ assert.equal(rpc.data.retriable, false);
+ assert.deepEqual(rpc.data.details, { origin: "local", phase: "context-validation" });
+ assert.doesNotMatch(error.message, /private-fixture-value/);
+ return true;
+ });
+ assert.equal(provider.requests.length, 0);
+ // The child only ever receives `history` as an RPC JSON copy, so
+ // re-serialising the harness-side array proves nothing about the child's
+ // memory. What this harness can observe is the Host surface: a rejected
+ // restore may only read the session through the runtime constructor's
+ // session.get, and may not call any other Host method. In-memory
+ // immutability of the restored copy is covered by the source replay
+ // tests, not here.
+ const restoreCalls = sidecar.hostCalls.slice();
+ assert.deepEqual(restoreCalls.filter((call) => call.method !== "session.get"), [],
+ "a rejected restore must not issue persistence-mutating Host RPCs");
+ assert.equal(restoreCalls.filter((call) => call.method === "session.get").length, 1,
+ "restore must read the session exactly once before rejecting");
+ const healthAfter = await sidecar.call("sidecar.health");
+ assert.equal(healthAfter.ok, true, "invalid history must not terminate the process");
+ assert.equal(healthAfter.runtimes, healthBefore.runtimes,
+ "a rejected restore must not register or leak a runtime");
+ // Same child, clean session: a rejected restore must not wedge recovery.
+ const cleanDir = join(dir, "clean-session");
+ await mkdir(cleanDir, { recursive: true });
+ const clean = await startProvider(cleanDir, () => ({ text: "CLEAN_SESSION_OK" }));
+ try {
+ await sidecar.prompt(parameters(clean.baseUrl, dir, "clean-after-invalid"), "CLEAN_SESSION_PROMPT");
+ assertText(sidecar, "CLEAN_SESSION_OK");
+ assert.equal(clean.requests.length, 1, "the recovery session must make exactly one provider request");
+ } finally {
+ await clean.close();
+ }
+ });
+ }
+ return results;
+}
diff --git a/scripts/e2e/hosted-search-sidecar.mjs b/scripts/e2e/hosted-search-sidecar.mjs
new file mode 100644
index 000000000..c14fe0d13
--- /dev/null
+++ b/scripts/e2e/hosted-search-sidecar.mjs
@@ -0,0 +1,212 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { createInterface } from "node:readline";
+import { setTimeout as delay } from "node:timers/promises";
+
+// Deliberately do not inherit credentials, proxies, NODE_OPTIONS, or user config.
+export async function isolatedEnv(dir) {
+ const home = join(dir, "home");
+ const data = join(dir, "data");
+ const temp = join(dir, "tmp");
+ await Promise.all([home, data, temp].map((path) => mkdir(path, { recursive: true })));
+ return {
+ PATH: process.env.PATH ?? "/usr/bin:/bin",
+ ...(process.platform === "win32" ? { SystemRoot: process.env.SystemRoot } : {}),
+ HOME: home, USERPROFILE: home,
+ XDG_CONFIG_HOME: join(home, "config"), XDG_CACHE_HOME: join(home, "cache"),
+ XDG_DATA_HOME: data, APPDATA: data, LOCALAPPDATA: data,
+ PI_DESKTOP_DATA_DIR: data, PI_CODING_AGENT_DIR: join(home, "agent"),
+ PI_SCRATCH_DIR: dir, TMPDIR: temp, TMP: temp, TEMP: temp,
+ COREPACK_ENABLE_NETWORK: "0", COREPACK_ENABLE_AUTO_PIN: "0",
+ NO_PROXY: "127.0.0.1", no_proxy: "127.0.0.1",
+ LANG: "en_US.UTF-8", TZ: "UTC",
+ };
+}
+
+export class OfflineSidecar {
+ constructor(child, dir, host, timeoutMs) {
+ this.child = child;
+ this.dir = dir;
+ this.host = host;
+ this.timeoutMs = timeoutMs;
+ this.events = [];
+ this.hostCalls = [];
+ this.messages = new Map();
+ this.pending = new Map();
+ this.stderr = "";
+ this.sequence = 0;
+ this.closed = false;
+ this.stopping = false;
+ child.on("error", (error) => this.fail(error));
+ this.exit = new Promise((resolve) => child.once("close", (code, signal) => {
+ this.closed = true;
+ if (!this.stopping) this.fail(new Error(`sidecar exited: ${code ?? signal}`));
+ resolve();
+ }));
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk) => {
+ this.stderr += chunk;
+ if (/unhandled promise rejection|TypeError:|ReferenceError:/.test(this.stderr)) {
+ this.fail(new Error(`sidecar stderr: ${this.stderr.slice(-5000)}`));
+ }
+ });
+ child.stdin.on("error", (error) => { if (!this.stopping) this.fail(error); });
+ this.lines = createInterface({ input: child.stdout });
+ this.lines.on("line", (line) => {
+ void this.receive(line).catch((error) => this.fail(error));
+ });
+ }
+
+ static async start(bundle, dir, host, timeoutMs) {
+ const env = await isolatedEnv(dir);
+ const child = spawn(process.execPath, [bundle], {
+ cwd: dir, env, stdio: ["pipe", "pipe", "pipe"],
+ });
+ const sidecar = new OfflineSidecar(child, dir, host, timeoutMs);
+ try {
+ assert.equal((await sidecar.call("sidecar.health")).ok, true);
+ return sidecar;
+ } catch (error) {
+ await sidecar.stop();
+ throw error;
+ }
+ }
+
+ fail(error) {
+ this.failure ??= error;
+ for (const pending of this.pending.values()) pending.reject(this.failure);
+ this.pending.clear();
+ }
+
+ check() { if (this.failure) throw this.failure; }
+
+ send(frame) {
+ this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...frame })}\n`);
+ }
+
+ async receive(line) {
+ const frame = JSON.parse(line);
+ if (frame.method === "host.proxy") {
+ const { method, params } = frame.params;
+ this.hostCalls.push({ method, params });
+ try {
+ const result = await this.host(method, params);
+ this.send({ id: frame.id, result: result ?? null });
+ } catch (error) {
+ // Best-effort production RPCs may swallow an error; fail this harness too.
+ this.send({ id: frame.id, error: { code: -32601, message: error.message } });
+ throw error;
+ }
+ return;
+ }
+ if (frame.id !== undefined) {
+ const pending = this.pending.get(String(frame.id));
+ assert.ok(pending, `unexpected RPC response: ${frame.id}`);
+ this.pending.delete(String(frame.id));
+ if (frame.error) pending.reject(new Error(JSON.stringify(frame.error)));
+ else pending.resolve(frame.result);
+ return;
+ }
+ assert.equal(frame.method, "agent.event", "unexpected sidecar notification");
+ const envelope = frame.params;
+ this.events.push(envelope);
+ const event = envelope.event;
+ if (event.type === "message_end") {
+ const message = event.message;
+ this.messages.set(message.id, message);
+ if (message.error) this.fail(new Error(`message error: ${JSON.stringify(message.error)}`));
+ }
+ if (event.type === "error") this.fail(new Error(`agent error: ${JSON.stringify(event.error)}`));
+ if (event.type === "status" && event.status.activity?.phase === "retrying") {
+ this.fail(new Error(`unexpected retry: ${JSON.stringify(event.status.activity.error)}`));
+ }
+ }
+
+ async call(method, params = {}) {
+ this.check();
+ const id = `offline-${++this.sequence}`;
+ let timer;
+ try {
+ return await new Promise((resolve, reject) => {
+ timer = setTimeout(() => {
+ this.fail(new Error(`RPC timeout: ${method}`));
+ }, this.timeoutMs);
+ this.pending.set(id, { resolve, reject });
+ this.send({ id, method, params });
+ });
+ } finally {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ }
+ }
+
+ async waitFor(predicate, label) {
+ const deadline = Date.now() + this.timeoutMs;
+ while (Date.now() < deadline) {
+ this.check();
+ if (await predicate()) return;
+ await delay(20);
+ }
+ throw new Error(`Timeout: ${label}; events=${this.events.slice(-8).map(({ event }) => event.type).join(",")}`);
+ }
+
+ async prompt(params, content) {
+ const start = this.events.length;
+ const turnId = `${params.sessionId}-turn-${Date.now()}-${++this.sequence}`;
+ const userMessageId = `${turnId}-user`;
+ // Electron/host normally persist the user row before agent.prompt. The
+ // sidecar emits assistant/tool rows, not a duplicate user message_end.
+ this.messages.set(userMessageId, {
+ id: userMessageId, role: "user", content, status: "complete", createdAt: new Date().toISOString(),
+ });
+ const result = await this.call("agent.prompt", { ...params, turnId, userMessageId, content });
+ assert.equal(result.accepted, true);
+ await this.waitFor(() => this.events.slice(start).some((envelope) =>
+ envelope.turnId === turnId && envelope.event.type === "agent_end"), `agent_end ${turnId}`);
+ await this.waitFor(async () => {
+ const { status } = await this.call("agent.getStatus", { sessionId: params.sessionId });
+ return status.isRunning === false;
+ }, `idle ${turnId}`);
+ this.check();
+ return this.events.slice(start);
+ }
+
+ async stop() {
+ if (this.stopping) return;
+ this.stopping = true;
+ if (!this.closed) {
+ this.child.stdin.end();
+ this.child.kill("SIGTERM");
+ const timer = setTimeout(() => this.child.kill("SIGKILL"), 1500);
+ try { await this.exit; } finally { clearTimeout(timer); }
+ }
+ this.lines.close();
+ this.fail(new Error("sidecar closed"));
+ await Promise.all([
+ writeFile(join(this.dir, "events.json"), JSON.stringify(this.events, null, 2)),
+ writeFile(join(this.dir, "host-rpc.json"), JSON.stringify(this.hostCalls, null, 2)),
+ writeFile(join(this.dir, "stderr.log"), this.stderr),
+ ]);
+ }
+}
+
+export function fixtureHost({ history = [], instructions = false } = {}) {
+ return async (method, params) => {
+ switch (method) {
+ case "session.get": return { session: { id: params.id, messages: history } };
+ case "project.instructions.resolve": return {
+ entries: instructions ? [{
+ source: "nested/AGENTS.md",
+ content: "OFFLINE_NESTED_RULE: explain the search and local fixture together.",
+ }] : [],
+ };
+ case "tools.execute":
+ assert.equal(params.toolName, "Read", "Task must execute inside the real runtime, never fake host");
+ assert.equal(params.args.path, "nested/fixture.txt");
+ return { ok: true, content: "OFFLINE_READ_RESULT: synthetic local file contents" };
+ default: throw new Error(`Unsupported fake-host RPC: ${method}`);
+ }
+ };
+}