Skip to content

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

chore(agent-runtime): sync Pi SDK to 0.87.0

vastsa0b71fae77a82
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 8312872cc..a201d1c9a 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -34,7 +34,7 @@
"electron-updater": "^6.8.9"
},
"devDependencies": {
- "@earendil-works/pi-ai": "0.86.1",
+ "@earendil-works/pi-ai": "0.87.0",
"@pi-desktop/agent-host": "workspace:*",
"@pi-desktop/agent-runtime": "workspace:*",
"@pi-desktop/host-runtime": "workspace:*",
diff --git a/docs/adr/0118-renderer-owned-queued-prompts.md b/docs/adr/0118-renderer-owned-queued-prompts.md
index 23b8ca9ee..ba811b35a 100644
--- a/docs/adr/0118-renderer-owned-queued-prompts.md
+++ b/docs/adr/0118-renderer-owned-queued-prompts.md
@@ -26,7 +26,7 @@ queue item. The renderer drains the queue one item at a time after the owning
session receives `agent_end`; each item uses the existing `agent/prompt` path,
preserving the host's single-running-turn invariant. Send now moves its item
to the head and calls the additive `agent/stop` IPC. The sidecar maps that
-request to pi-agent-core's `shouldStopAfterTurn` hook, so the current reply and
+request to pi-agent-core's `finishTurn` hook, so the current reply and
completed tool batch finish normally and the durable turn closes as
`completed` before the prioritized item starts.
diff --git a/docs/adr/0254-native-pi-session-continuation.md b/docs/adr/0254-native-pi-session-continuation.md
index 502f61ce3..6ca6bea97 100644
--- a/docs/adr/0254-native-pi-session-continuation.md
+++ b/docs/adr/0254-native-pi-session-continuation.md
@@ -22,6 +22,10 @@ PI-Desktop historically imports Pi sessions by flattening them into Desktop-owne
- Desktop sessions and their host-owned persistence are unchanged.
- Native branches, compaction data (including unknown fields such as `retainedTail`), custom/context messages, and future unknown entries remain untouched because reads are in-memory and writes are SDK append-only.
+- With the 0.87.0 coding-agent pin, `context_edit` entries are append-only and
+ affect only the SDK's future model-context projection. Raw source entries
+ and the visible native transcript remain unchanged. `appendContextEdit` is
+ covered by the same lease and parent-chain guard as every other SDK append.
- An uncooperative writer can still race within the OS append operation. The adapter detects prefix/suffix divergence after the append, preserves bytes, disposes the runtime, and requires reload; full mutual exclusion requires Pi clients to adopt a shared lease protocol.
- `@earendil-works/pi-coding-agent` is a runtime dependency of the bundled sidecar and its session format behavior is version-pinned.
- `bindExtensions` runs native startup/resource discovery with the SDK headless UI (`mode: "print"`, `hasUI: false`), error ownership, and explicit unsupported session controls. Guards and listeners precede startup; failure disposes the session and lease. Native extensions are trusted local code, not Desktop plugins or sandboxed tools.
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 5df3434c3..55672e84e 100644
--- a/docs/adr/0297-provider-hosted-web-search-adapter-capability.md
+++ b/docs/adr/0297-provider-hosted-web-search-adapter-capability.md
@@ -45,7 +45,7 @@ Two upstream facts forced the design:
API — never vendor names, base URL hostnames, or model-id substrings.
2. **Attachment and extraction live in the pi-ai adapters**, delivered by
- extending `patches/@[email protected]`:
+ extending `patches/@[email protected]`:
- `anthropic-messages.js` appends the `web_search_20250305` tool when
`model.webSearch === true`, captures search blocks as `hostedSearch`
content parts (raw wire block kept whole, streamed `input_json_delta`
@@ -57,7 +57,7 @@ Two upstream facts forced the design:
creates a `hostedSearch` slot for `web_search_call` items, collects
`url_citation` annotations, and replays the item for the same model.
Both adapters push a `hosted_search_update` stream event per block
- transition; `patches/@[email protected]` teaches
+ transition; `patches/@[email protected]` teaches
the agent loop to forward it as `message_update` — without that second
patch the events die in the loop's switch and search activity renders only
when the whole turn finishes. The patches are a stopgap; the same changes
diff --git a/docs/adr/scheduled-desktop-automations.md b/docs/adr/scheduled-desktop-automations.md
index 8df2e0c88..4a8508757 100644
--- a/docs/adr/scheduled-desktop-automations.md
+++ b/docs/adr/scheduled-desktop-automations.md
@@ -7,7 +7,7 @@
The shipped Scheduled page stores a cadence but never dispatches work when
that cadence becomes due. The pinned pi-ai, pi-agent-core and pi-coding-agent
-0.86.1 packages supply agent execution, not a persistent desktop wall-clock
+0.87.0 packages supply agent execution, not a persistent desktop wall-clock
scheduler. The existing Host-owned task and run tables already provide the
appropriate storage boundary.
@@ -82,4 +82,3 @@ The UI offers four time periods (09:00, 14:00, 19:00, 22:00) to keep setup
simple. AI tools retain precise local time configuration, and the form preserves
those custom times. Direct database access or renderer-mediated tool mutation
would duplicate ownership or bypass permission gates and is rejected.
-
diff --git a/docs/spec/02-architecture/02-tech-stack.md b/docs/spec/02-architecture/02-tech-stack.md
index 458c33b4e..ab8834cd5 100644
--- a/docs/spec/02-architecture/02-tech-stack.md
+++ b/docs/spec/02-architecture/02-tech-stack.md
@@ -12,15 +12,15 @@
| Host backend | **Rust** | stable Rust toolchain | tools/plugins/permissions/persistence adapters |
| Rust async | tokio | stable | host services |
| Host RPC | stdio JSON-RPC (NDJSON) | frozen (D001) | Electron main ↔ Rust host |
-| Agent engine | `@earendil-works/pi-agent-core` | 0.86.1 | agent loop |
-| Model API | `@earendil-works/pi-ai` | 0.86.1 | provider adapters, OAuth, and stream handling |
+| Agent engine | `@earendil-works/pi-agent-core` | 0.87.0 | agent loop |
+| Model API | `@earendil-works/pi-ai` | 0.87.0 | provider adapters, OAuth, and stream handling |
| Model catalog | `https://models.dev/api.json` | bundled release snapshot + process-local refresh | sole provider/model metadata source |
> pi-ai is not consulted for model names, capabilities, limits, modalities,
> thinking levels, or prices. It remains the request transport dependency.
> ChatGPT Plus/Pro and GitHub Copilot OAuth availability still comes from the
-> pinned pi-ai catalog; 0.86.1 includes the `gpt-6-astra` catalog entry.
-> The 0.86.1 pi-ai catalog also registers Meta/Muse subscription OAuth; Desktop enumerates it dynamically rather than maintaining a separate vendor list.
+> pinned pi-ai catalog; 0.87.0 includes the `gpt-6-astra` catalog entry.
+> The 0.87.0 pi-ai catalog also registers Meta/Muse subscription OAuth; Desktop enumerates it dynamically rather than maintaining a separate vendor list.
| Node runtime | Node.js | `>= 22.19` | pi requirement |
| DB | SQLite | Rust host-core via `rusqlite` | sessions/settings |
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 555013aa7..e1be5daf1 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1525,6 +1525,14 @@ with the original v3 `SessionManager`, Pi `ModelRuntime`, `SettingsManager`, and
leaf, compaction, model/thinking changes, and context-bearing custom messages;
it is never reconstructed from renderer `UiMessage` rows.
+The 0.87.0 SDK also applies append-only `context_edit` entries to this model
+projection. An edit can omit or replace an earlier message for later provider
+requests without rewriting its raw JSONL entry or the visible native history.
+Native Pi extensions use the SDK's boundary hooks; all entries they append,
+including context edits, pass through the sidecar's lease and parent-chain
+guard. This native extension lifecycle is separate from the Desktop Agent
+extension adapter described in [trusted extensions](../07-plugins/16-trusted-extensions.md).
+
The first native slice supports text prompt **without model tools**, stop/abort,
and explicit refresh. `createAgentSession` receives `noTools: "all"`; neither
built-in nor extension tools may bypass Desktop permissions. Tool parity awaits
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 92f2bdae4..6b68a0a4a 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -1559,6 +1559,13 @@ revision, Plan/Goal, collaboration, and queue operations remain unsupported
for native sessions in this slice. Forking is supported as described here and in
the runtime spec.
+The 0.87.0 `context_edit` entry is part of the native v3 JSONL branch. It changes
+only the SDK-built model projection by omitting or replacing a target message;
+the original line and renderer history remain intact. It is not copied into the
+Desktop transcript or SQLite, and needs no Desktop schema migration. The lease
+guard covers `SessionManager.appendContextEdit` alongside the other native
+append methods.
+
A native fork writes exactly one new v3 JSONL child in the parent's session
directory. Branch extraction runs against an in-memory manager over the parent
snapshot, then child title/parent saved model/thinking fallbacks are appended in
@@ -1595,4 +1602,3 @@ Hourly rows retain their fields but require explicit calendar confirmation
when converted. Known intent survives cadence changes and database reopen.
This additive JSON key needs no table or schema-version migration. Older
versions ignore the key and cannot enforce the new conversion guard.
-
diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.md
index d573957e7..e8e8c73ff 100644
--- a/docs/spec/03-runtime/11-provider-model-system.md
+++ b/docs/spec/03-runtime/11-provider-model-system.md
@@ -192,7 +192,7 @@ PI-Desktop must not permanently restrict users to a short fixed model list.
preserving all raw records in the file for future surfaces. Image input is
sent as a transient image content block only when the model accepts image
input. PDF capability is surfaced and retained in model metadata; because
- pi-ai 0.86.1 has no native PDF content block, PDF attachments remain bounded
+ pi-ai 0.87.0 has no native PDF content block, PDF attachments remain bounded
file references rather than being incorrectly encoded as images.
7. User-edited `ModelBinding` values remain explicit provider configuration:
they control selected request limits, enabled thinking levels, the default
@@ -219,7 +219,7 @@ PI-Desktop must not permanently restrict users to a short fixed model list.
self-hosted endpoint routinely accepts input its catalog entry omits.
Enabling image input turns on the transient image content block; enabling PDF
input records the capability but does not change the encoding, since pi-ai
- 0.86.1 has no PDF content block and PDFs stay bounded file references.
+ 0.87.0 has no PDF content block and PDFs stay bounded file references.
10. The settings checkboxes show the effective answer against the published
baseline, and setting one back to the published value stores "follow the
catalog" rather than an equal-valued override. Agreeing with models.dev is
@@ -480,7 +480,7 @@ same vendor key.
### Anthropic token endpoint rate limits
-The pinned pi-ai 0.86.1 patch gives Anthropic authorization-code exchange and
+The pinned pi-ai 0.87.0 patch gives Anthropic authorization-code exchange and
refresh a shared, bounded token-request policy: retry only an explicit HTTP
429, at most three total requests. Wait at least 1 s then 2 s, or longer when
`Retry-After` gives delta seconds or an HTTP date. A server delay beyond the
@@ -720,7 +720,7 @@ response, it stops consuming the stream instead of awaiting the server's
TCP FIN. Upstream pi-ai keeps iterating until the server closes the
connection, which hangs the turn behind reverse proxies that hold the idle
connection open. Until the fix ships upstream, `patches/` carries a pnpm
-patch on `@earendil-works/[email protected]` that breaks the event loop on the
+patch on `@earendil-works/[email protected]` that breaks the event loop on the
terminal event (the OpenAI SDK aborts the underlying request when the
consumer stops iterating). Drop the patch once a pi-ai release includes the
fix.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 254b73f01..fd9745e7d 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4181,7 +4181,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
runnable with the generic text-only, non-reasoning shape; pi-ai supplies only
the selected wire adapter, OAuth flow, and account model availability. A
ChatGPT Plus/Pro or GitHub Copilot account lists `gpt-6-astra` from the
- pinned pi-ai 0.86.1 catalog; models.dev then supplies its published metadata.
+ pinned pi-ai 0.87.0 catalog; models.dev then supplies its published metadata.
- **Specs linked**: `02-architecture/02-tech-stack.md`,
`03-runtime/11-provider-model-system.md`,
`03-runtime/13-model-catalog-and-selection.md`, ADR 0134
@@ -13955,7 +13955,9 @@ plugin-form fixtures in an isolated temporary directory at runtime.
context-bearing custom-message entries, and a valid project cwd. A faux local
model/auth binding is configured in the fixture Pi agent directory; Desktop
provider secrets are absent. A fixture extension restores custom state in
- `session_start` and contributes a skill through `resources_discover`.
+ `session_start`, contributes a skill through `resources_discover`, and uses
+ the 0.87 `turn_end` boundary to propose a `context_edit` for the settled
+ assistant entry.
- **Steps:** Start PI-Desktop with fixture-only agent/session directories;
refresh sessions; open the native row beside a Desktop row; submit one text
prompt; stop or let the faux response settle; send the same text again with
@@ -13970,6 +13972,8 @@ plugin-form fixtures in an isolated temporary directory at runtime.
Exactly two durable SDK-ID user rows remain, including after abort; smart-stop
never rewrites native history. Retries/compaction remain running and stoppable
until one terminal completion; the owned idle lease accepts the second send.
+ The `context_edit` is appended under the same lease, affects the next model
+ request, and leaves the original assistant row visible in native detail.
Compact and queue push/list reject before host access. Opaque host-turn queue
remove/prioritize remain Desktop-only because native paths create no entries.
- **Specs:** runtime §12; storage §12; security §12; ADR 0254.
@@ -13979,8 +13983,9 @@ plugin-form fixtures in an isolated temporary directory at runtime.
- **Preconditions:** A writable synthetic native v3 fixture is listed.
- **Steps:** Acquire Desktop continuation ownership, then simulate a foreign
- append/replacement before the next SDK append; also attempt a second Desktop
- lease and stale leases whose owners are live, remote, malformed, or uncertain.
+ append/replacement before the extension's `appendContextEdit`; also attempt a
+ second Desktop lease and stale leases whose owners are live, remote,
+ malformed, or uncertain.
Refresh list/detail with a dead same-host owner and unchanged or complete
append-only extended bytes, then prompt through normal UI capabilities.
- **Expected:** The second writer is refused; external divergence tears down
@@ -13988,8 +13993,9 @@ plugin-form fixtures in an isolated temporary directory at runtime.
appended and no bytes are truncated or rewritten; a lease releases on normal
dispose and is reclaimed after crash only with a dead same-host owner and an
unchanged target or same-file prefix-preserving complete parent-chain extension.
- Uncooperative Pi clients can still race the OS append; no shared-lock guarantee
- is claimed.
+ The context-edit append is refused by the same byte and parent check as other
+ SDK writes. Uncooperative Pi clients can still race the OS append; no
+ shared-lock guarantee is claimed.
- **Specs:** runtime §12; storage §12; security §12; ADR 0254.
- **Status:** Documented; run after integration into main.
@@ -14832,4 +14838,3 @@ renderer's durable transcript reads. No real model or provider is contacted.
`node --test apps/desktop/test/plugin-timeout-budgets.test.mjs`,
`pnpm --filter @pi-desktop/shared test`, and
`pnpm --filter @pi-desktop/host-runtime test`.
-
diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.md
index 94fcffaa8..c32e06cac 100644
--- a/docs/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/spec/07-plugins/16-trusted-extensions.md
@@ -16,6 +16,13 @@ which PI-Desktop adopts alongside the `pi-ai` and `pi-agent-core` kernel
contributes. D388 folded the earlier standalone "trusted extensions"
registry into this contribution; the engine below is unchanged.
+This contract describes extensions attached to Desktop Agent sessions. The
+Desktop adapter implements the explicit subset in §5–6; new upstream events do
+not become actionable here automatically. Native Pi continuation runs the
+coding-agent SDK's own extension lifecycle and can use its 0.87.0 boundary
+hooks, subject to the separate native-session lease and trust rules in
+[ADR 0254](../../adr/0254-native-pi-session-continuation.md).
+
Provider declarations are a separate manifest surface rather than part of this
contract: `contributes.providers` materializes Host-owned provider rows
([02-plugin-manifest-schema.md](02-plugin-manifest-schema.md) §5.4, ADR 0259),
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index d539f62a5..9195185c8 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -2515,7 +2515,7 @@ D193, and D194.
session's `agent_end`, the renderer drains one item through the existing
`agent/prompt` path. Send now promotes one item and calls additive
`pi-desktop/agent/stop`; the sidecar sets pi-agent-core's one-shot
- `shouldStopAfterTurn` flag, so the current assistant response/tool batch
+ `finishTurn` decision, so the current assistant response/tool batch
completes and the durable turn closes normally before the prioritized prompt
starts. Immediate abort keeps its current behavior and never clears the
queue.
diff --git a/docs/zh-CN/spec/02-architecture/02-tech-stack.md b/docs/zh-CN/spec/02-architecture/02-tech-stack.md
index 812246cd2..09dbbfd2e 100644
--- a/docs/zh-CN/spec/02-architecture/02-tech-stack.md
+++ b/docs/zh-CN/spec/02-architecture/02-tech-stack.md
@@ -15,12 +15,12 @@
| 主机后端 | **Rust** | 稳定的 Rust 工具链 | tools/plugins/permissions/persistence 适配器 |
| Rust 异步 | 东京 | 稳定 | 主机服务 |
| 主机 RPC | stdio JSON-RPC (NDJSON) | 冷冻(D001) | Electron 主 ↔ Rust 主机 |
-| Agent 引擎 | `@earendil-works/pi-agent-core` | 0.86.1 | 代理循环 |
-| 模型 API | `@earendil-works/pi-ai` | 0.86.1 | 提供商 |
+| Agent 引擎 | `@earendil-works/pi-agent-core` | 0.87.0 | 代理循环 |
+| 模型 API | `@earendil-works/pi-ai` | 0.87.0 | 提供商 |
| 模型目录 | `https://models.dev/api.json` | 随发版内置的快照 + 进程内刷新 | 唯一的提供商/模型元数据来源 |
-> 当前引脚为 **0.86.1**。ChatGPT / Copilot OAuth 目录包含 `gpt-6-astra`。Claude Opus 5 目录元数据从 **0.82.1** 起可用
-> 0.86.1 的 pi-ai 目录还注册了 Meta/Muse 订阅 OAuth;桌面端动态枚举它,不维护独立的供应商列表。
+> 当前引脚为 **0.87.0**。ChatGPT / Copilot OAuth 目录包含 `gpt-6-astra`。Claude Opus 5 目录元数据从 **0.82.1** 起可用
+> 0.87.0 的 pi-ai 目录还注册了 Meta/Muse 订阅 OAuth;桌面端动态枚举它,不维护独立的供应商列表。
>(`claude-opus-5`,1M 上下文,适应性思维)。
| Node 运行时 | Node.js | `>= 22.19` | 圆周率要求 |
| 数据库 | SQLite | Rust host-core 通过 `rusqlite` | sessions/settings |
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 1b9ac4810..efaf0dc4b 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
@@ -177,7 +177,7 @@ PI-Desktop 不得把用户永久限制在一份简短的固定模型列表上。
6. 输入与输出模态数组保留 `text`、`image`、`audio`、`video` 和 `pdf`。文本
agent 选择器暴露能处理文本的模型,同时在文件中保留全部原始记录以备将来的
界面使用。只有当模型接受图片输入时,图片才会作为临时图片内容块发送。PDF
- 能力会在模型元数据中呈现并保留;由于 pi-ai 0.86.1 没有原生的 PDF 内容块,
+ 能力会在模型元数据中呈现并保留;由于 pi-ai 0.87.0 没有原生的 PDF 内容块,
PDF 附件仍然是有界的文件引用,而不会被错误地编码成图片。
7. 用户编辑过的 `ModelBinding` 值仍属于显式的提供商配置:它们控制选定的请求
上限、启用的思考级别、应用到新的主页草稿与新持久化会话的默认思考级别
@@ -196,7 +196,7 @@ PI-Desktop 不得把用户永久限制在一份简短的固定模型列表上。
`true` 或 `false` 是用户的显式回答,并在目录变动后继续有效。与思考级别
不同,这两个覆盖不会被收窄到已发布的能力,因为经过代理或自托管的端点
经常接受其目录条目未列出的输入。启用图片输入会打开临时图片内容块;启用
- PDF 输入只记录该能力,不改变编码方式——pi-ai 0.86.1 没有 PDF 内容块,
+ PDF 输入只记录该能力,不改变编码方式——pi-ai 0.87.0 没有 PDF 内容块,
PDF 仍是有界的文件引用。
10. 设置里的复选框展示的是相对于已发布基线的有效答案;把某一项设回已发布的
值,存下来的是"跟随目录",而不是一个取值相同的覆盖。因此与 models.dev
@@ -392,7 +392,7 @@ sidecar 请求
### Anthropic token 端点限流
-固定版本 pi-ai 0.86.1 的仓库补丁为 Anthropic 授权码交换与刷新提供同一套
+固定版本 pi-ai 0.87.0 的仓库补丁为 Anthropic 授权码交换与刷新提供同一套
有限策略:只重试明确的 HTTP 429,最多总共三次请求。先等待至少 1 秒、再
等待至少 2 秒;若 `Retry-After` 给出更长的秒数或 HTTP 日期,则遵守该时间。
服务器要求的等待超出剩余预算时结束本次尝试,不缩短等待后提前重试。
@@ -600,7 +600,7 @@ OpenAI Responses 适配器必须把 `response.completed`(以及
而不是继续等待服务端的 TCP FIN。上游 pi-ai 会一直迭代直到服务端关闭
连接,在保持空闲连接不关的反向代理后面会导致整个回合挂起。在该修复
随上游发布之前,`patches/` 通过 pnpm patch 修改
-`@earendil-works/[email protected]`,在终态事件处跳出事件循环(消费方停止
+`@earendil-works/[email protected]`,在终态事件处跳出事件循环(消费方停止
迭代时 OpenAI SDK 会中止底层请求)。待 pi-ai 发布包含该修复的版本后
移除补丁。
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 7ceb18b1f..3217901b1 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -2261,7 +2261,7 @@ D193 和 D194。
空草稿显示「停止」,因此用户清空草稿即可露出立即停止操作。所属会话的
`agent_end` 之后,渲染器通过既有的 `agent/prompt` 路径排出一项。「立即发送」
把一项提升到队首并调用增量的 `pi-desktop/agent/stop`;sidecar 设置
- pi-agent-core 的一次性 `shouldStopAfterTurn` 标志,于是当前的助手回复 / 工具
+ pi-agent-core 的一次性 `finishTurn` 决策,于是当前的助手回复 / 工具
批次跑完、持久化回合正常关闭之后,优先的提示才开始。立即中止保持现有行为,
且从不清空队列。
- 这改变了渲染器状态归属并新增一个公开的 Electron IPC 通道,但不改动 host-core
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index 49913d245..cc1ed23e8 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -23,9 +23,9 @@
"clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('dist-bundle',{recursive:true,force:true})\""
},
"dependencies": {
- "@earendil-works/pi-agent-core": "0.86.1",
- "@earendil-works/pi-ai": "0.86.1",
- "@earendil-works/pi-coding-agent": "0.86.1",
+ "@earendil-works/pi-agent-core": "0.87.0",
+ "@earendil-works/pi-ai": "0.87.0",
+ "@earendil-works/pi-coding-agent": "0.87.0",
"@pi-desktop/shared": "workspace:*",
"jiti": "2.7.0",
"typebox": "^1.3.13",
diff --git a/packages/agent-runtime/src/extensions/loader.ts b/packages/agent-runtime/src/extensions/loader.ts
index 83203c4c1..fc00a64d7 100644
--- a/packages/agent-runtime/src/extensions/loader.ts
+++ b/packages/agent-runtime/src/extensions/loader.ts
@@ -78,7 +78,7 @@ export function createCodingAgentShim(): Record<string, unknown> {
isPowerShellToolResult: () => false,
isToolCallEventType: (type: unknown) =>
type === "tool_call" || type === "tool_result",
- VERSION: "0.86.1",
+ VERSION: "0.87.0",
};
}
diff --git a/packages/agent-runtime/src/hosted-search-contract.test.ts b/packages/agent-runtime/src/hosted-search-contract.test.ts
index 583f6077f..5ab7f8d66 100644
--- a/packages/agent-runtime/src/hosted-search-contract.test.ts
+++ b/packages/agent-runtime/src/hosted-search-contract.test.ts
@@ -5,7 +5,7 @@ import type { AssistantMessage } from "@earendil-works/pi-ai";
/**
* Contract tests for the pi-ai hosted web search patch.
*
- * The patch (patches/@[email protected]) teaches the
+ * The patch (patches/@[email protected]) teaches the
* anthropic-messages and openai-responses adapters to attach the provider
* hosted web search tool when the model record opts in, to extract the search
* blocks and citations from the stream, and to replay the search items on
@@ -414,7 +414,7 @@ describe("pi-ai hosted web search: streaming progress events", () => {
describe("pi-agent-core hosted web search forwarding", () => {
it("forwards hosted_search_update as message_update", async () => {
- // Locks the agent-loop patch (patches/@[email protected]):
+ // Locks the agent-loop patch (patches/@[email protected]):
// without it the loop's switch drops the event and search rounds render only
// after the whole turn finishes.
const { agentLoop } = await import("@earendil-works/pi-agent-core");
diff --git a/packages/agent-runtime/src/native-pi-session-lease.ts b/packages/agent-runtime/src/native-pi-session-lease.ts
index 728480176..22d656fe1 100644
--- a/packages/agent-runtime/src/native-pi-session-lease.ts
+++ b/packages/agent-runtime/src/native-pi-session-lease.ts
@@ -256,6 +256,7 @@ export function guardNativePiSessionManager(
"appendCustomEntry",
"appendSessionInfo",
"appendCustomMessageEntry",
+ "appendContextEdit",
"appendLabelChange",
"branchWithSummary",
] as const;
diff --git a/packages/agent-runtime/src/native-pi-session.test.ts b/packages/agent-runtime/src/native-pi-session.test.ts
index 74d586afb..21c0abf29 100644
--- a/packages/agent-runtime/src/native-pi-session.test.ts
+++ b/packages/agent-runtime/src/native-pi-session.test.ts
@@ -116,11 +116,26 @@ describe("NativePiSessionService", () => {
const lease = acquireNativePiSessionLease(f.file);
const manager = SessionManager.open(f.file);
guardNativePiSessionManager(manager, lease);
- manager.appendMessage({ role: "user", content: [{ type: "text", text: "desktop turn" }], timestamp: Date.now() });
+ const userEntryId = manager.appendMessage({
+ role: "user",
+ content: [{ type: "text", text: "desktop turn" }],
+ timestamp: Date.now(),
+ });
+ manager.appendContextEdit(userEntryId, {
+ content: [{ type: "text", text: "edited model context" }],
+ });
+ expect(manager.buildSessionContext().messages).toContainEqual({
+ role: "user",
+ content: [{ type: "text", text: "edited model context" }],
+ timestamp: expect.any(Number),
+ });
const afterOwnAppend = readFileSync(f.file, "utf8");
expect(afterOwnAppend).toContain("desktop turn");
+ expect(afterOwnAppend).toContain('"type":"context_edit"');
writeFileSync(f.file, `${afterOwnAppend}${JSON.stringify({ type: "custom", id: "foreign", parentId: manager.getLeafId(), timestamp: new Date().toISOString(), customType: "foreign" })}\n`);
- expect(() => manager.appendMessage({ role: "user", content: [{ type: "text", text: "must not write" }], timestamp: Date.now() })).toThrow(/changed/i);
+ expect(() => manager.appendContextEdit(userEntryId, {
+ content: [{ type: "text", text: "must not write" }],
+ })).toThrow(/changed/i);
expect(readFileSync(f.file, "utf8")).not.toContain("must not write");
lease.release();
});
diff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.ts
index 779b67a8b..c6d0369b2 100644
--- a/packages/agent-runtime/src/provider-binding.test.ts
+++ b/packages/agent-runtime/src/provider-binding.test.ts
@@ -678,7 +678,7 @@ describe("DeepSeek-family relay reasoning replay (#296)", () => {
* compat from an explicit allowlist in `getCompat`. Only a request that goes
* through the adapter can prove the placeholder survives that rebuild and
* reaches the wire, so this asserts the captured body rather than the compat
- * object. Guards patches/@[email protected].
+ * object. Guards patches/@[email protected].
*/
it("fills a thinking-less assistant turn with the documented placeholder", async () => {
const provider: RuntimeProviderConfig = {
diff --git a/packages/agent-runtime/src/provider-stream-frame-fields.test.ts b/packages/agent-runtime/src/provider-stream-frame-fields.test.ts
index f7dc33206..d2668bef6 100644
--- a/packages/agent-runtime/src/provider-stream-frame-fields.test.ts
+++ b/packages/agent-runtime/src/provider-stream-frame-fields.test.ts
@@ -17,7 +17,7 @@ import { stream as streamOpenAIResponses } from "@earendil-works/pi-ai/api/opena
//
// These tests drive the real stream decoders with a stubbed transport and feed
// every event through the real frame encoder, because that pair is where the
-// failure lived. They guard `patches/@[email protected]`; if
+// failure lived. They guard `patches/@[email protected]`; if
// the patch is dropped, they fail again.
const context = {
diff --git a/packages/agent-runtime/src/reasoning-content-backfill.test.ts b/packages/agent-runtime/src/reasoning-content-backfill.test.ts
index 7d51ceb8d..84e7d43f3 100644
--- a/packages/agent-runtime/src/reasoning-content-backfill.test.ts
+++ b/packages/agent-runtime/src/reasoning-content-backfill.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { convertMessages } from "@earendil-works/pi-ai/api/openai-completions";
import { DEEPSEEK_REASONING_REPLAY_PLACEHOLDER } from "@pi-desktop/shared";
-// Guards the pnpm patch on @earendil-works/pi-ai (patches/@[email protected]):
+// Guards the pnpm patch on @earendil-works/pi-ai (patches/@[email protected]):
// DeepSeek-style endpoints accept a history where either every assistant message
// carries a reasoning field or none does, and reject a mix. A relayed model that
// is not in the catalogue has `reasoning: false`, so pi's per-message backfill
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 02791e5ec..cfa256975 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -448,14 +448,16 @@ describe("DesktopAgentRuntime configuration matching", () => {
await runtime.dispose();
});
- it("stops once at the next completed turn boundary", async () => {
+ it("stops once at a successful finishTurn boundary and lets errors settle", async () => {
const runtime = createRuntime();
const agent = (runtime as any).agent;
agent.state.isStreaming = true;
expect(runtime.requestGracefulStop()).toEqual({ requested: true });
- expect(await agent.shouldStopAfterTurn({})).toBe(true);
- expect(await agent.shouldStopAfterTurn({})).toBe(false);
+ expect(await agent.finishTurn({ message: { stopReason: "error" } })).toBeUndefined();
+ expect(await agent.finishTurn({ message: { stopReason: "aborted" } })).toBeUndefined();
+ expect(await agent.finishTurn({ message: { stopReason: "stop" } })).toEqual({ action: "end" });
+ expect(await agent.finishTurn({ message: { stopReason: "stop" } })).toBeUndefined();
agent.state.isStreaming = false;
expect(runtime.requestGracefulStop()).toEqual({ requested: false });
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 3fe4029ab..475d18b61 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -2014,14 +2014,14 @@ Delegation rules:
// ordering guarantee is untouched.
toolExecution: "parallel",
steeringMode: "all",
- // A queued renderer prompt asks the current run to finish normally at
- // the next turn boundary. pi-agent-core evaluates this after the
- // assistant response and completed tool batch, before another provider
- // request, so no second concurrent durable turn is created.
- shouldStopAfterTurn: async () => {
- if (!this.gracefulStopRequested) return false;
+ // pi-agent-core 0.87 replaces shouldStopAfterTurn with finishTurn. A
+ // queued renderer prompt ends a completed turn at the next boundary,
+ // without treating an error or abort as a graceful stop.
+ finishTurn: async ({ message }) => {
+ if (!this.gracefulStopRequested) return;
+ if (message.stopReason === "error" || message.stopReason === "aborted") return;
this.gracefulStopRequested = false;
- return true;
+ return { action: "end" };
},
});
diff --git a/packages/shared/src/provider-presets.ts b/packages/shared/src/provider-presets.ts
index b8659be11..8c2023a62 100644
--- a/packages/shared/src/provider-presets.ts
+++ b/packages/shared/src/provider-presets.ts
@@ -348,7 +348,7 @@ export function isOfficialDeepSeekEndpoint(input: { baseUrl?: string }): boolean
* Documented non-empty stand-in when a strict DeepSeek-compatible relay requires
* reasoning replay but the turn's real thinking was never retained (compaction
* summary, synthetic bridge assistants, or thinking-less turns). Must match the
- * literal embedded in patches/@[email protected].
+ * literal embedded in patches/@[email protected].
*/
export const DEEPSEEK_REASONING_REPLAY_PLACEHOLDER =
"[reasoning not retained for this turn]";
diff --git a/packages/shared/src/trusted-extensions.ts b/packages/shared/src/trusted-extensions.ts
index 0064e3d4b..25710f1b9 100644
--- a/packages/shared/src/trusted-extensions.ts
+++ b/packages/shared/src/trusted-extensions.ts
@@ -153,7 +153,7 @@ export const TRUSTED_EXTENSION_HANDLER_TIMEOUT_MS = 30_000;
export const TRUSTED_EXTENSION_PROMPT_TIMEOUT_MS = 5 * 60_000;
/** The pinned kernel version every pi package in the sidecar must share (spec §13). */
-export const TRUSTED_EXTENSION_KERNEL_VERSION = "0.86.1";
+export const TRUSTED_EXTENSION_KERNEL_VERSION = "0.87.0";
/** Palette command id prefix for extension commands. */
export const TRUSTED_EXTENSION_COMMAND_ID_PREFIX = "extension:";
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 000000000..b43ea190d
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,392 @@
+diff --git a/dist/agent-loop.js b/dist/agent-loop.js
+index 4bbd0ce..5bf74e7 100644
+--- a/dist/agent-loop.js
++++ b/dist/agent-loop.js
+@@ -292,6 +292,12 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc
+ case "toolcall_start":
+ case "toolcall_delta":
+ case "toolcall_end":
++ // Hosted web search (PI-Desktop): the pi-ai adapters push
++ // `hosted_search_update` when a provider-side search block starts
++ // or completes. Forward it like any other progress event so the
++ // application renders each search round as it happens instead of
++ // only learning about searches from the final message.
++ case "hosted_search_update":
+ if (partialMessage) {
+ partialMessage = event.partial;
+ context.messages[context.messages.length - 1] = partialMessage;
+diff --git a/dist/agent.js b/dist/agent.js
+index a2f462f..a3b8a7f 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";
+@@ -359,6 +360,7 @@ export class Agent {
+ }
+ }
+ async handleRunFailure(error, aborted) {
++ const errorDetails = aborted ? undefined : localRequestErrorDetails(error);
+ const failureMessage = {
+ role: "assistant",
+ content: [{ type: "text", text: "" }],
+@@ -367,7 +369,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 85c89e8..995a28d 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 d430a3f..1682577 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 f7c6a26..a5de558 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 736c315..4517456 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 2fa0e35..1a22a7d 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 f34eede..fc0191d 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 01ffaa5..73970f3 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]
new file mode 100644
index 000000000..308dc7f30
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,1611 @@
+diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
+index d462f30..3d3dab1 100644
+--- a/dist/api/anthropic-messages.js
++++ b/dist/api/anthropic-messages.js
+@@ -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,17 +481,50 @@ export const stream = (model, context, options) => {
+ output.content.push(block);
+ stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
+ }
++ // Hosted web search (PI-Desktop): server-side search blocks
++ // are captured whole. The paired `server_tool_use` +
++ // `web_search_tool_result` blocks round-trip verbatim via
++ // the hostedSearch block so multi-turn conversations keep
++ // their grounding (encrypted content included).
++ else if (event.content_block.type === "server_tool_use") {
++ const block = {
++ type: "hostedSearch",
++ phase: "server_tool_use",
++ blockId: event.content_block.id,
++ name: event.content_block.name,
++ input: event.content_block.input,
++ inputJson: "",
++ index: event.index,
++ };
++ output.content.push(block);
++ stream.push({ type: "hosted_search_update", contentIndex: output.content.length - 1, partial: output });
++ }
++ else if (event.content_block.type === "web_search_tool_result" ||
++ event.content_block.type === "web_search_tool_result_error") {
++ const isError = event.content_block.type === "web_search_tool_result_error";
++ const block = {
++ type: "hostedSearch",
++ phase: "web_search_tool_result",
++ blockId: event.content_block.tool_use_id,
++ isError,
++ // The raw block is the replay payload; keep it verbatim.
++ wire: event.content_block,
++ index: event.index,
++ };
++ output.content.push(block);
++ stream.push({ type: "hosted_search_update", contentIndex: output.content.length - 1, partial: output });
++ }
+ }
+ else if (event.type === "content_block_delta") {
+ if (event.delta.type === "text_delta") {
+ const index = blocks.findIndex((b) => b.index === event.index);
+ const block = blocks[index];
+ if (block && block.type === "text") {
+- block.text += event.delta.text;
++ block.text += event.delta.text ?? "";
+ stream.push({
+ type: "text_delta",
+ contentIndex: index,
+- delta: event.delta.text,
++ delta: event.delta.text ?? "",
+ partial: output,
+ });
+ }
+@@ -493,11 +533,11 @@ export const stream = (model, context, options) => {
+ const index = blocks.findIndex((b) => b.index === event.index);
+ const block = blocks[index];
+ if (block && block.type === "thinking") {
+- block.thinking += event.delta.thinking;
++ block.thinking += event.delta.thinking ?? "";
+ stream.push({
+ type: "thinking_delta",
+ contentIndex: index,
+- delta: event.delta.thinking,
++ delta: event.delta.thinking ?? "",
+ partial: output,
+ });
+ }
+@@ -506,12 +546,24 @@ export const stream = (model, context, options) => {
+ const index = blocks.findIndex((b) => b.index === event.index);
+ const block = blocks[index];
+ if (block && block.type === "toolCall") {
+- block.partialJson += event.delta.partial_json;
++ block.partialJson += event.delta.partial_json ?? "";
+ block.arguments = parseStreamingJson(block.partialJson);
+ stream.push({
+ type: "toolcall_delta",
+ contentIndex: index,
+- delta: event.delta.partial_json,
++ delta: event.delta.partial_json ?? "",
++ partial: output,
++ });
++ }
++ // Hosted web search (PI-Desktop): server_tool_use input
++ // (the query) streams as input_json_delta like any tool
++ // call; accumulate it so the row can show the query live.
++ else if (block && block.type === "hostedSearch" && block.phase === "server_tool_use") {
++ block.inputJson = (block.inputJson ?? "") + (event.delta.partial_json ?? "");
++ block.input = parseStreamingJson(block.inputJson);
++ stream.push({
++ type: "hosted_search_update",
++ contentIndex: index,
+ partial: output,
+ });
+ }
+@@ -521,7 +573,19 @@ export const stream = (model, context, options) => {
+ const block = blocks[index];
+ if (block && block.type === "thinking") {
+ block.thinkingSignature = block.thinkingSignature || "";
+- block.thinkingSignature += event.delta.signature;
++ 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;
++ // 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);
+ }
+ }
+ }
+@@ -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;
++ }
+ }
+ }
+ 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);
+ }
+ }
++ // Hosted web search (PI-Desktop): attach the server-side tool when the
++ // model record opts in. A hosted tool has no client execute; its blocks
++ // are extracted by the stream loop below and replayed by convertMessages.
++ if (model.webSearch === true) {
++ params.tools = [
++ ...(params.tools ?? []),
++ { type: "web_search_20250305", name: "web_search" },
++ ];
++ }
+ // 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 +1156,15 @@ function convertMessages(transformedMessages, isOAuthToken, cacheControl, allowE
+ input: block.arguments ?? {},
+ });
+ }
++ // Hosted web search (PI-Desktop): replay both halves of the
++ // 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") {
++ 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 ec1e206..572dce7 100644
+--- a/dist/api/azure-openai-responses.js
++++ b/dist/api/azure-openai-responses.js
+@@ -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;
+ }
++ // Hosted web search (PI-Desktop): same opt-in as openai-responses; the
++ // azure adapter reuses the shared stream processor, which already knows
++ // how to extract web_search_call items.
++ if (model.webSearch === true) {
++ params.tools = [...(params.tools ?? []), { type: "web_search" }];
++ }
+ if (model.reasoning) {
+ if (options?.reasoningEffort || options?.reasoningSummary) {
+ const effort = options?.reasoningEffort
+@@ -252,6 +268,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
+ };
+ }
+ }
++ // Hosted web search (PI-Desktop): sources ride the opt-in `include`
++ // channel; merged here because the reasoning block above assigns
++ // `params.include` outright.
++ if (model.webSearch === true) {
++ params.include = [...new Set([...(params.include ?? []), "web_search_call.action.sources"])];
++ }
+ // 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 3106c5d..8b209bb 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 80720d0..68d3a57 100644
+--- a/dist/api/openai-completions.js
++++ b/dist/api/openai-completions.js
+@@ -1039,21 +1039,27 @@ export function convertMessages(model, context, compat, options) {
+ if (preservedReasoningDetails) {
+ assistantMsg.reasoning_details = preservedReasoningDetails;
+ }
+- if (compat.requiresReasoningContentOnAssistantMessages &&
+- model.reasoning &&
+- assistantMsg.reasoning_content === undefined) {
+- assistantMsg.reasoning_content = "";
+- }
++ // Catalogue-model empty fill moved to the history-wide pass below so
++ // empty-string (#223) and non-empty placeholder (strict relays) share one path.
++
+ // Skip assistant messages that have no content and no tool calls.
+ // Some providers require "either content or tool_calls, but not none".
+ // Other providers also don't accept empty assistant messages.
+ // This handles aborted assistant responses that got no content.
++ // Keep reasoning-only assistants (#296 retained thinking): map a
++ // minimal content stand-in so the already-set reasoning_* field
++ // still reaches the wire.
+ const content = assistantMsg.content;
+ const hasContent = content !== null &&
+ content !== undefined &&
+ (typeof content === "string" ? content.length > 0 : content.length > 0);
++ const hasReasoningReplay = OPENAI_COMPLETIONS_REASONING_FIELDS.some((field) => typeof assistantMsg[field] === "string" &&
++ assistantMsg[field].length > 0);
+ if (!hasContent && !assistantMsg.tool_calls) {
+- continue;
++ if (!hasReasoningReplay) {
++ continue;
++ }
++ assistantMsg.content = ".";
+ }
+ params.push(assistantMsg);
+ }
+@@ -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,
++ // reasoning_text, or reasoning). Relayed models outside the catalogue are
++ // often not flagged `reasoning`, so this pass also covers them (#223).
++ // Official DeepSeek accepts ""; OpenCode/third-party relays that require a
++ // real echo set requiresNonEmptyReasoningReplay and receive a documented
++ // placeholder instead of a silent empty string (#296).
++ // Placeholder text must match DEEPSEEK_REASONING_REPLAY_PLACEHOLDER in
++ // @pi-desktop/shared provider-presets.
++ const reasoningFields = ["reasoning_content", "reasoning_text", "reasoning"];
++ if (compat.requiresReasoningContentOnAssistantMessages) {
++ let activeField;
++ for (const field of reasoningFields) {
++ if (params.some((m) => m.role === "assistant" &&
++ typeof m[field] === "string" &&
++ m[field].length > 0)) {
++ activeField = field;
++ break;
++ }
++ }
++ if (!activeField && model.reasoning) {
++ activeField = "reasoning_content";
++ }
++ if (activeField) {
++ const fill = compat.requiresNonEmptyReasoningReplay
++ ? "[reasoning not retained for this turn]"
++ : "";
++ for (const m of params) {
++ if (m.role === "assistant" && m[activeField] === undefined) {
++ m[activeField] = fill;
++ }
++ }
++ }
++ }
+ return params;
+ }
+ function convertTools(tools, compat) {
+@@ -1265,6 +1306,9 @@ function detectCompat(model) {
+ requiresAssistantAfterToolResult: false,
+ requiresThinkingAsText: false,
+ requiresReasoningContentOnAssistantMessages: isDeepSeek,
++ // Relays that reject an empty reasoning echo must set this explicitly:
++ // no endpoint can be auto-detected as requiring a real one.
++ requiresNonEmptyReasoningReplay: undefined,
+ thinkingFormat: isDeepSeek
+ ? "deepseek"
+ : isZai
+@@ -1318,6 +1362,8 @@ function getCompat(model) {
+ requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
+ requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ??
+ detected.requiresReasoningContentOnAssistantMessages,
++ requiresNonEmptyReasoningReplay: model.compat.requiresNonEmptyReasoningReplay ??
++ detected.requiresNonEmptyReasoningReplay,
+ thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,
+ openRouterRouting: model.compat.openRouterRouting ?? {},
+ vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
+@@ -1337,4 +1383,4 @@ function getCompat(model) {
+ vllmPriority: model.compat.vllmPriority,
+ };
+ }
+-//# sourceMappingURL=openai-completions.js.map
+\ No newline at end of file
++//# sourceMappingURL=openai-completions.js.map
+diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-shared.js
+index 53597d2..763f99a 100644
+--- a/dist/api/openai-responses-shared.js
++++ b/dist/api/openai-responses-shared.js
+@@ -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") {
++ 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 +414,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ stream.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
+ return slot;
+ }
++ // Hosted web search (PI-Desktop): a server-side search call. The raw
++ // item is kept whole; `response.web_search_call.*` status events and
++ // the done item update the same slot. Replay pushes the item back as
++ // an output item so multi-turn search state survives.
++ if (item.type === "web_search_call") {
++ const block = {
++ type: "hostedSearch",
++ phase: "web_search_call",
++ blockId: item.id,
++ status: item.status ?? "in_progress",
++ wire: item,
++ };
++ output.content.push(block);
++ const slot = {
++ type: "hostedSearch",
++ block,
++ contentIndex: output.content.length - 1,
++ };
++ outputSlots.set(outputIndex, slot);
++ stream.push({ type: "hosted_search_update", contentIndex: slot.contentIndex, partial: output });
++ return slot;
++ }
+ return undefined;
+ };
+ const getOrCreateSlot = (outputIndex, item) => {
+@@ -485,11 +516,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ const slot = getSlot(event.output_index, "thinking");
+ if (!slot)
+ continue;
+- slot.block.thinking += event.delta;
++ slot.block.thinking += event.delta ?? "";
+ stream.push({
+ type: "thinking_delta",
+ contentIndex: slot.contentIndex,
+- delta: event.delta,
++ delta: event.delta ?? "",
+ partial: output,
+ });
+ }
+@@ -509,11 +540,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ const slot = getSlot(event.output_index, "thinking");
+ if (!slot)
+ continue;
+- slot.block.thinking += event.delta;
++ slot.block.thinking += event.delta ?? "";
+ stream.push({
+ type: "thinking_delta",
+ contentIndex: slot.contentIndex,
+- delta: event.delta,
++ delta: event.delta ?? "",
+ partial: output,
+ });
+ }
+@@ -521,23 +552,44 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ const slot = getSlot(event.output_index, "text");
+ if (!slot)
+ continue;
+- slot.block.text += event.delta;
++ slot.block.text += event.delta ?? "";
+ stream.push({
+ type: "text_delta",
+ contentIndex: slot.contentIndex,
+- delta: event.delta,
++ delta: event.delta ?? "",
+ 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.
++ else if (event.type === "response.output_text.annotation.added") {
++ const annotation = event.annotation;
++ if (annotation?.type === "url_citation" && typeof annotation.url === "string") {
++ output.hostedSearchCitations = output.hostedSearchCitations ?? [];
++ output.hostedSearchCitations.push({
++ url: annotation.url,
++ title: typeof annotation.title === "string" ? annotation.title : undefined,
++ });
++ }
++ }
++ // Hosted web search status transitions (`response.web_search_call.in_progress`
++ // / `.completed` / `.failed`); the payload mirrors the item.
++ else if (typeof event.type === "string" && event.type.startsWith("response.web_search_call.")) {
++ const item = event.item ?? event.output_item;
++ 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");
+ if (!slot)
+ continue;
+- slot.block.text += event.delta;
++ slot.block.text += event.delta ?? "";
+ stream.push({
+ type: "text_delta",
+ contentIndex: slot.contentIndex,
+- delta: event.delta,
++ delta: event.delta ?? "",
+ partial: output,
+ });
+ }
+@@ -545,9 +597,9 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ const slot = getSlot(event.output_index, "toolCall");
+ if (!slot || slot.block.partialJson === undefined)
+ continue;
+- slot.block.partialJson += event.delta;
++ slot.block.partialJson += event.delta ?? "";
+ slot.block.arguments = parseStreamingJson(slot.block.partialJson);
+- pushToolCallDelta(slot, event.delta);
++ pushToolCallDelta(slot, event.delta ?? "");
+ }
+ else if (event.type === "response.function_call_arguments.done") {
+ const slot = getSlot(event.output_index, "toolCall");
+@@ -633,9 +685,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
+ });
+ outputSlots.delete(event.output_index);
+ }
++ // Hosted web search (PI-Desktop): finalize the slot with the
++ // done item so replay carries the server's final representation.
++ else if (item.type === "web_search_call" && slot?.type === "hostedSearch") {
++ slot.block.status = item.status ?? slot.block.status;
++ slot.block.wire = item;
++ stream.push({
++ type: "hosted_search_update",
++ contentIndex: slot.contentIndex,
++ partial: output,
++ });
++ outputSlots.delete(event.output_index);
++ }
+ }
+ else if (event.type === "response.completed" || event.type === "response.incomplete") {
+ finalizeResponse(event.response);
++ // The response is fully delivered: stop consuming the stream so the
++ // request does not hang when the server (or a reverse proxy) never
++ // closes the connection after the terminal event.
++ break;
+ }
+ 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 1396c8d..39d201f 100644
+--- a/dist/api/openai-responses.js
++++ b/dist/api/openai-responses.js
+@@ -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,
+ });
+ }
++ // Hosted web search (PI-Desktop): attach the server-side tool when the
++ // model record opts in. The Responses `web_search` tool definition is a
++ // bare tagged object; it never passes through convertResponsesTools.
++ if (model.webSearch === true) {
++ params.tools = [...(params.tools ?? []), { type: "web_search" }];
++ }
+ if (options?.toolChoice !== undefined) {
+ params.tool_choice = options.toolChoice;
+ }
+@@ -264,6 +281,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar
+ if (model.provider === "xai")
+ params.include = ["reasoning.encrypted_content"];
+ }
++ // Hosted web search (PI-Desktop): sources ride the opt-in `include`
++ // channel; merged here because the reasoning block above assigns
++ // `params.include` outright.
++ if (model.webSearch === true) {
++ params.include = [...new Set([...(params.include ?? []), "web_search_call.action.sources"])];
++ }
+ // 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 216a45f..23528b8 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 8692e90..0291387 100644
+--- a/dist/auth/oauth/anthropic.js
++++ b/dist/auth/oauth/anthropic.js
+@@ -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"
++ ? "Wait, close this dialog, and start a new sign-in attempt."
++ : "Wait before retrying. If the problem continues, sign in again.";
++ const reason = code === "invalid_grant"
++ ? "Anthropic rejected the authorization grant. Please sign in again."
++ : code === "invalid_response"
++ ? `Anthropic returned an invalid token response. ${recovery}`
++ : status === 429
++ ? `Anthropic token requests are rate limited. ${recovery}`
++ : `Anthropic token request failed (HTTP ${status}). ${recovery}`;
++ super(reason);
++ this.name = "AnthropicOAuthTokenError";
++ this.status = status;
++ this.code = code;
++ }
++}
++function tokenRetryDelay(header, attempt) {
++ const fallback = 1000 * 2 ** attempt;
++ const value = header?.trim();
++ if (!value || value.length > 128)
++ return fallback;
++ const serverDelay = /^\d+$/.test(value)
++ ? Number(value) * 1000
++ : /^[A-Za-z]{3}, /.test(value)
++ ? Date.parse(value) - Date.now()
++ : NaN;
++ return Number.isNaN(serverDelay) ? fallback : Math.max(fallback, serverDelay);
++}
++function waitForTokenRetry(delay, signal) {
++ signal.throwIfAborted();
++ return new Promise((resolve, reject) => {
++ const timer = setTimeout(() => {
++ signal.removeEventListener("abort", abort);
++ resolve();
++ }, delay);
++ const abort = () => {
++ clearTimeout(timer);
++ signal.removeEventListener("abort", abort);
++ reject(signal.reason);
++ };
++ signal.addEventListener("abort", abort, { once: true });
+ });
+- const responseBody = await response.text();
+- if (!response.ok) {
+- throw new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${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)]);
++ const deadline = performance.now() + 30_000;
++ const serialized = JSON.stringify(body);
++ for (let attempt = 0; ; attempt++) {
++ requestSignal.throwIfAborted();
++ const response = await fetch(url, {
++ method: "POST",
++ headers: {
++ "Content-Type": "application/json",
++ Accept: "application/json",
++ },
++ body: serialized,
++ signal: requestSignal,
++ });
++ const responseBody = await response.text();
++ if (response.ok)
++ return responseBody;
++ // Never put a token endpoint's response body in an error or log.
++ let invalidGrant = false;
++ try {
++ const data = JSON.parse(responseBody);
++ invalidGrant = data?.error === "invalid_grant" || data?.error?.type === "invalid_grant";
++ }
++ catch { /* Non-JSON errors are reported by status only. */ }
++ const failure = new AnthropicOAuthTokenError(response.status,
++ invalidGrant ? "invalid_grant" : response.status === 429 ? "rate_limited" : "http_error",
++ body.grant_type);
++ // Only an explicit rate-limit rejection is replayed. Network errors,
++ // 5xx and invalid_grant may follow a consumed/rotated grant: do not retry.
++ if (response.status !== 429 || invalidGrant || attempt >= 2)
++ throw failure;
++ const delay = tokenRetryDelay(response.headers.get("Retry-After"), attempt);
++ 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 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig
+ }, signal);
+ }
+ catch (error) {
++ if (error instanceof AnthropicOAuthTokenError || error?.name === "AbortError" || error?.name === "TimeoutError")
++ throw error;
+ 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 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig
+ tokenData = JSON.parse(responseBody);
+ }
+ catch (error) {
+- throw new Error(`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`);
++ throw new AnthropicOAuthTokenError(0, "invalid_response", "authorization_code");
+ }
+ return {
+ type: "oauth",
+@@ -280,6 +351,8 @@ async function refreshAnthropicToken(refreshToken, signal) {
+ }, signal);
+ }
+ catch (error) {
++ if (error instanceof AnthropicOAuthTokenError || error?.name === "AbortError" || error?.name === "TimeoutError")
++ throw error;
+ throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);
+ }
+ let data;
+@@ -287,7 +360,7 @@ async function refreshAnthropicToken(refreshToken, signal) {
+ data = JSON.parse(responseBody);
+ }
+ catch (error) {
+- throw new Error(`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`);
++ throw new AnthropicOAuthTokenError(0, "invalid_response", "refresh_token");
+ }
+ return {
+ type: "oauth",
+diff --git a/dist/index.d.ts b/dist/index.d.ts
+index 5e8403d..50f728e 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 cf46c04..0fe0023 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 5915ca6..f5d4114 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">;
+@@ -546,6 +576,12 @@ export interface OpenAICompletionsCompat {
+ requiresThinkingAsText?: boolean;
+ /** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. Default: auto-detected from URL. */
+ requiresReasoningContentOnAssistantMessages?: boolean;
++ /**
++ * Whether a replayed assistant message that carries no reasoning must send a documented
++ * non-empty placeholder instead of an empty string. Some relays reject the empty echo.
++ * Default: false; only an explicit model.compat opt-in enables it.
++ */
++ requiresNonEmptyReasoningReplay?: boolean;
+ /** Format for reasoning/thinking parameter. "openai" uses reasoning_effort, "openrouter" uses reasoning: { effort }, "deepseek" uses thinking: { type } plus reasoning_effort when supported, "together" uses reasoning: { enabled } plus reasoning_effort when supported, "baseten" uses configurable chat_template_args plus reasoning_effort when supported, "zai" uses thinking: { type }, "qwen" uses top-level enable_thinking: boolean, "qwen-chat-template" uses chat_template_kwargs.enable_thinking and preserve_thinking, "chat-template" uses configurable chat_template_kwargs, "string-thinking" uses top-level thinking: string, and "ant-ling" uses reasoning: { effort } only when the mapped effort is non-null. Default: "openai". */
+ thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "baseten" | "zai" | "qwen" | "chat-template" | "qwen-chat-template" | "string-thinking" | "ant-ling";
+ /** Kwargs to send as `chat_template_kwargs` when `thinkingFormat` is `chat-template`. Use `{ "$var": "thinking.enabled" }`, `{ "$var": "thinking.effort" }`, or `{ "$var": "thinking.budget" }` for pi-controlled thinking values. */
+@@ -809,6 +845,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.
+@@ -833,4 +871,4 @@ export interface ImagesModel<TApi extends ImagesApi> extends Omit<Model<Api>, "a
+ provider: ImagesProviderId;
+ output: ("text" | "image")[];
+ }
+-//# sourceMappingURL=types.d.ts.map
+\ No newline at end of file
++//# sourceMappingURL=types.d.ts.map
+diff --git a/dist/utils/assistant-message-frame.d.ts b/dist/utils/assistant-message-frame.d.ts
+index 0820719..0584f68 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 c0e0019..a86f593 100644
+--- a/dist/utils/assistant-message-frame.js
++++ b/dist/utils/assistant-message-frame.js
+@@ -1,15 +1,30 @@
++import { normalizeHostedSearchContent } from "./hosted-search.js";
+ import { parseStreamingJson } from "./json-parse.js";
++
++// A gateway that re-serializes provider events with `omitempty` (Go) or drops
++// `undefined` (JS) hands a text / thinking / tool-call delta over with the
++// string field missing. The frame protocol requires a string there, and the only
++// value that can be dropped that way is the empty one, so a non-string payload
++// reads as "". Reading `.length` off it used to throw a bare TypeError that the
++// runtime surfaced as a retriable provider failure and then reproduced on every
++// later turn of the session.
++function textValue(value) {
++ return typeof value === "string" ? value : "";
++}
++function textLength(value) {
++ return typeof value === "string" ? value.length : 0;
++}
+ function cloneTextContent(content) {
+ return {
+ type: "text",
+- text: content.text,
++ text: textValue(content.text),
+ ...(content.textSignature === undefined ? {} : { textSignature: content.textSignature }),
+ };
+ }
+ function cloneThinkingContent(content) {
+ return {
+ type: "thinking",
+- thinking: content.thinking,
++ thinking: textValue(content.thinking),
+ ...(content.thinkingSignature === undefined ? {} : { thinkingSignature: content.thinkingSignature }),
+ ...(content.redacted === undefined ? {} : { redacted: content.redacted }),
+ };
+@@ -24,6 +39,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 +138,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") {
+@@ -112,7 +158,7 @@ export class AssistantMessageFrameEncoder {
+ }
+ this.startBlock(event.contentIndex, {
+ kind: "text",
+- coveredChars: content.text.length,
++ coveredChars: textLength(content.text),
+ deltaChars: 0,
+ });
+ return { type: "text_start", contentIndex: event.contentIndex, content: cloneTextContent(content) };
+@@ -139,7 +185,7 @@ export class AssistantMessageFrameEncoder {
+ }
+ this.startBlock(event.contentIndex, {
+ kind: "thinking",
+- coveredChars: content.thinking.length,
++ coveredChars: textLength(content.thinking),
+ deltaChars: 0,
+ });
+ return {
+@@ -183,12 +229,13 @@ export class AssistantMessageFrameEncoder {
+ const state = this.block(event.contentIndex, "toolCall");
+ if (state.kind !== "toolCall")
+ throw new Error("Unreachable tool-call encoder state");
++ const delta = textValue(event.delta);
+ if (state.caughtUp) {
+- return event.delta.length === 0
++ return delta.length === 0
+ ? undefined
+- : { type: "toolcall_delta", contentIndex: event.contentIndex, delta: event.delta };
++ : { type: "toolcall_delta", contentIndex: event.contentIndex, delta };
+ }
+- state.catchupJson += event.delta;
++ state.catchupJson += delta;
+ const argumentsValue = parseStreamingJson(state.catchupJson);
+ if (serializedArguments(argumentsValue) !== state.snapshotArguments) {
+ // Legacy grammar calls include the initial input in toolcall_start, but their
+@@ -254,12 +301,13 @@ export class AssistantMessageFrameEncoder {
+ const state = this.block(contentIndex, kind);
+ if (state.kind === "toolCall")
+ throw new Error("Unreachable text encoder state");
++ const text = textValue(delta);
+ const deltaStart = state.deltaChars;
+- state.deltaChars += delta.length;
++ state.deltaChars += text.length;
+ const covered = Math.max(0, state.coveredChars - deltaStart);
+- if (covered >= delta.length)
++ if (covered >= text.length)
+ return undefined;
+- const uncovered = covered === 0 ? delta : delta.slice(covered);
++ const uncovered = covered === 0 ? text : text.slice(covered);
+ return kind === "text"
+ ? { type: "text_delta", contentIndex, delta: uncovered }
+ : { type: "thinking_delta", contentIndex, delta: uncovered };
+@@ -311,6 +359,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 6dcca6e..5ccaaf2 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 d04ff22..28564cc 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 0000000..a76ae52
+--- /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 0000000..b177a26
+--- /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 0000000..a72f65b
+--- /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 0000000..4d276dd
+--- /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 0000000..879b78c
+--- /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 0000000..5c63b88
+--- /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..7f7abae59
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,469 @@
+diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js
+index 36fdb31..322876f 100644
+--- a/dist/core/agent-session.js
++++ b/dist/core/agent-session.js
+@@ -64,10 +64,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;
+ }
+@@ -300,7 +300,7 @@ export class AgentSession {
+ const projection = this.sessionManager.buildSessionProjection();
+ if (!model ||
+ model.contextWindow <= 0 ||
+- !shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens, model.contextWindow, settings)) {
++ !shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch(), model).tokens, model.contextWindow, settings)) {
+ return { ...context, messages: projection.messages };
+ }
+ await this._runAutoCompaction("threshold", false);
+@@ -438,7 +438,7 @@ export class AgentSession {
+ entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
+ break;
+ case "compaction": {
+- const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch()).tokens;
++ const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch(), this.model ?? undefined).tokens;
+ entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, draft.details, true, draft.usage);
+ break;
+ }
+@@ -1876,7 +1876,7 @@ export class AgentSession {
+ const settings = this.settingsManager.getCompactionSettings(model);
+ const { model: requestModel, apiKey, headers, env, } = await this._getSummarizationRequestAuth(model, this._compactionAbortController.signal);
+ const pathEntries = this.sessionManager.getBranch();
+- const preparation = prepareCompaction(pathEntries, settings);
++ const preparation = prepareCompaction(pathEntries, settings, requestModel);
+ if (!preparation) {
+ // Check why we can't compact
+ const lastEntry = pathEntries[pathEntries.length - 1];
+@@ -1933,7 +1933,7 @@ export class AgentSession {
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
+ const newEntries = this.sessionManager.getEntries();
+ this._refreshFinalizedContext();
+- const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
++ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().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) {
+@@ -2111,11 +2111,11 @@ export class AgentSession {
+ const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
+ if (hasContextEdits) {
+- contextTokens = estimateProjectedContextTokens(projection, branch).tokens;
++ contextTokens = estimateProjectedContextTokens(projection, branch, this.model ?? undefined).tokens;
+ }
+ else 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) {
+@@ -2161,7 +2161,7 @@ export class AgentSession {
+ return false;
+ }
+ const pathEntries = this.sessionManager.getBranch();
+- const preparation = prepareCompaction(pathEntries, settings);
++ const preparation = prepareCompaction(pathEntries, settings, model);
+ if (!preparation) {
+ return false;
+ }
+@@ -2219,7 +2219,7 @@ export class AgentSession {
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
+ const newEntries = this.sessionManager.getEntries();
+ this._refreshFinalizedContext();
+- const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
++ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().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) {
+@@ -3122,7 +3122,7 @@ export class AgentSession {
+ if (!hasPostCompactionUsage)
+ return { tokens: null, contextWindow, percent: null };
+ }
+- const estimate = estimateProjectedContextTokens(projection, branch);
++ const estimate = estimateProjectedContextTokens(projection, branch, 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 bf7729f..794ec01 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/branch-summarization.d.ts b/dist/core/compaction/branch-summarization.d.ts
+index 12cb88e..6ff7356 100644
+--- a/dist/core/compaction/branch-summarization.d.ts
++++ b/dist/core/compaction/branch-summarization.d.ts
+@@ -6,7 +6,7 @@
+ */
+ import type { AgentMessage, StreamFn } from "@earendil-works/pi-agent-core";
+ import type { RetryCallbacks, RetryPolicy } from "@earendil-works/pi-ai";
+-import type { Model, Usage } from "@earendil-works/pi-ai/compat";
++import type { Api, Model, Usage } from "@earendil-works/pi-ai/compat";
+ import type { ReadonlySessionManager, SessionEntry } from "../session-manager.ts";
+ import { type FileOperations } from "./utils.ts";
+ export interface BranchSummaryResult {
+@@ -87,7 +87,7 @@ export declare function collectEntriesForBranchSummary(session: ReadonlySessionM
+ * @param entries - Entries in chronological order
+ * @param tokenBudget - Maximum tokens to include (0 = no limit)
+ */
+-export declare function prepareBranchEntries(entries: SessionEntry[], tokenBudget?: number): BranchPreparation;
++export declare function prepareBranchEntries(entries: SessionEntry[], tokenBudget?: number, model?: Model<Api>): BranchPreparation;
+ /**
+ * Generate a summary of abandoned branch entries.
+ *
+diff --git a/dist/core/compaction/branch-summarization.js b/dist/core/compaction/branch-summarization.js
+index 3f98859..b68f7ad 100644
+--- a/dist/core/compaction/branch-summarization.js
++++ b/dist/core/compaction/branch-summarization.js
+@@ -95,7 +95,7 @@ function getMessageFromEntry(entry) {
+ * @param entries - Entries in chronological order
+ * @param tokenBudget - Maximum tokens to include (0 = no limit)
+ */
+-export function prepareBranchEntries(entries, tokenBudget = 0) {
++export function prepareBranchEntries(entries, tokenBudget = 0, model) {
+ const messages = [];
+ const fileOps = createFileOps();
+ let totalTokens = 0;
+@@ -125,7 +125,7 @@ export function prepareBranchEntries(entries, tokenBudget = 0) {
+ continue;
+ // Extract file ops from assistant messages (tool calls)
+ extractFileOpsFromMessage(message, fileOps);
+- const tokens = estimateTokens(message);
++ const tokens = estimateTokens(message, model);
+ // Check budget before adding
+ if (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {
+ // If this is a summary entry, try to fit it anyway as it's important context
+@@ -189,7 +189,7 @@ export async function generateBranchSummary(entries, options) {
+ // Token budget = context window minus reserved space for prompt + response
+ const contextWindow = model.contextWindow || 128000;
+ const tokenBudget = contextWindow - reserveTokens;
+- const { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);
++ const { messages, fileOps } = prepareBranchEntries(entries, tokenBudget, model);
+ if (messages.length === 0) {
+ return { summary: "No content to summarize" };
+ }
+diff --git a/dist/core/compaction/compaction.d.ts b/dist/core/compaction/compaction.d.ts
+index 04416da..fdf79d9 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, type SessionProjection } from "../session-manager.ts";
+ import { type FileOperations } from "./utils.ts";
+ /** Details stored in CompactionEntry.details for file tracking */
+@@ -50,9 +50,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.
+ */
+-export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;
++export declare function estimateContextTokens(messages: AgentMessage[], model?: Model<Api>): ContextUsageEstimate;
+ /** Estimate projected context without trusting usage captured before a later edit or compaction. */
+-export declare function estimateProjectedContextTokens(projection: SessionProjection, branchEntries: SessionEntry[]): ContextUsageEstimate;
++export declare function estimateProjectedContextTokens(projection: SessionProjection, branchEntries: SessionEntry[], model?: Model<Api>): ContextUsageEstimate;
+ /**
+ * Check if compaction should trigger based on context usage.
+ */
+@@ -60,8 +60,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.
+@@ -91,7 +93,7 @@ export interface CutPointResult {
+ *
+ * Only considers entries between `startIndex` and `endIndex` (exclusive).
+ */
+-export declare function findCutPoint(entries: SessionEntry[], startIndex: number, endIndex: number, keepRecentTokens: number): CutPointResult;
++export declare function findCutPoint(entries: SessionEntry[], startIndex: number, endIndex: number, keepRecentTokens: number, model?: Model<Api>): CutPointResult;
+ /**
+ * Returns an error message when a summarization response cannot safely be persisted.
+ * A length stop contains partial text and must not become a session checkpoint.
+@@ -132,7 +134,7 @@ export interface CompactionPreparation {
+ /** Compaction settions from settings.jsonl */
+ settings: CompactionSettings;
+ }
+-export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings): CompactionPreparation | undefined;
++export declare function prepareCompaction(pathEntries: SessionEntry[], settings: CompactionSettings, model?: Model<Api>): CompactionPreparation | undefined;
+ /**
+ * Generate summaries for compaction using prepared data.
+ * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
+diff --git a/dist/core/compaction/compaction.js b/dist/core/compaction/compaction.js
+index b86498c..1034f8a 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, getCurrentSystemMessage, normalizeContext, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";
++import { contentText, getCurrentSystemMessage, 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 { buildSessionProjection, sessionEntryToContextMessages, } from "../session-manager.js";
+ import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
+@@ -116,24 +118,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,
+@@ -145,7 +142,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,
+@@ -155,8 +152,8 @@ export function estimateContextTokens(messages) {
+ };
+ }
+ /** Estimate projected context without trusting usage captured before a later edit or compaction. */
+-export function estimateProjectedContextTokens(projection, branchEntries) {
+- const estimate = estimateContextTokens(projection.messages);
++export function estimateProjectedContextTokens(projection, branchEntries, model) {
++ const estimate = estimateContextTokens(projection.messages, model);
+ if (estimate.lastUsageIndex !== null) {
+ let projectedMessageIndex = 0;
+ let usageEntryId;
+@@ -181,10 +178,10 @@ export function estimateProjectedContextTokens(projection, branchEntries) {
+ return estimate;
+ }
+ const currentSystem = getCurrentSystemMessage(projection.messages);
+- let tokens = currentSystem ? estimateTokens(currentSystem) : 0;
++ let tokens = currentSystem ? estimateTokens(currentSystem, model) : 0;
+ for (const message of projection.messages) {
+ if (message.role !== "system")
+- tokens += estimateTokens(message);
++ tokens += estimateTokens(message, model);
+ }
+ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
+ }
+@@ -219,43 +216,15 @@ function estimateTextAndImageContentChars(content) {
+ * Estimate token count for a message using chars/4 heuristic.
+ * This is conservative (overestimates tokens).
+ */
+-export function estimateTokens(message) {
++export function estimateTokens(message, model) {
+ let chars = 0;
+ switch (message.role) {
+- case "system": {
+- const system = message;
+- chars = estimateTextAndImageContentChars(system.content);
+- if (system.sections) {
+- for (const section of Object.values(system.sections)) {
+- if (section)
+- chars += section.length;
+- }
+- }
+- if (system.toolsAdded)
+- chars += JSON.stringify(system.toolsAdded).length;
+- return Math.ceil(chars / 4);
+- }
+- 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);
+ }
+@@ -269,7 +238,7 @@ export function estimateTokens(message) {
+ return Math.ceil(chars / 4);
+ }
+ }
+- return 0;
++ throw new LocalRequestError("context-validation");
+ }
+ function isCutPointMessage(message) {
+ switch (message.role) {
+@@ -352,7 +321,7 @@ export function findTurnStartIndex(entries, entryIndex, startIndex) {
+ *
+ * Only considers entries between `startIndex` and `endIndex` (exclusive).
+ */
+-export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens) {
++export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens, model) {
+ const cutPoints = findValidCutPoints(entries, startIndex, endIndex);
+ if (cutPoints.length === 0) {
+ return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };
+@@ -362,7 +331,7 @@ export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens) {
+ let cutIndex = cutPoints[0]; // Default: keep from first message (not header)
+ for (let i = endIndex - 1; i >= startIndex; i--) {
+ const entry = entries[i];
+- const messageTokens = sessionEntryToContextMessages(entry).reduce((sum, message) => sum + estimateTokens(message), 0);
++ const messageTokens = sessionEntryToContextMessages(entry).reduce((sum, message) => sum + estimateTokens(message, model), 0);
+ if (messageTokens === 0)
+ continue;
+ accumulatedTokens += messageTokens;
+@@ -570,7 +539,7 @@ function findProjectedTurnStartIndex(entries, entryIndex, startIndex) {
+ }
+ return -1;
+ }
+-function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens) {
++function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens, model) {
+ const cutPoints = [];
+ for (let i = startIndex; i < endIndex; i++) {
+ const entry = entries[i];
+@@ -584,7 +553,7 @@ function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens)
+ let exceededBudget = false;
+ let cutIndex = cutPoints[0];
+ for (let i = endIndex - 1; i >= startIndex; i--) {
+- const messageTokens = entries[i].messages.reduce((sum, message) => sum + estimateTokens(message), 0);
++ const messageTokens = entries[i].messages.reduce((sum, message) => sum + estimateTokens(message, model), 0);
+ if (messageTokens === 0)
+ continue;
+ accumulatedTokens += messageTokens;
+@@ -624,7 +593,7 @@ function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens)
+ isSplitTurn: !startsTurn && turnStartIndex !== -1,
+ };
+ }
+-export function prepareCompaction(pathEntries, settings) {
++export function prepareCompaction(pathEntries, settings, model) {
+ if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
+ return undefined;
+ }
+@@ -642,8 +611,8 @@ export function prepareCompaction(pathEntries, settings) {
+ boundaryStart = prevCompactionIndex + 1;
+ }
+ const boundaryEnd = projectedEntries.length;
+- const tokensBefore = estimateProjectedContextTokens(projection, pathEntries).tokens;
+- const cutPoint = findProjectedCutPoint(projectedEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens);
++ const tokensBefore = estimateProjectedContextTokens(projection, pathEntries, model).tokens;
++ const cutPoint = findProjectedCutPoint(projectedEntries, boundaryStart, boundaryEnd, settings.keepRecentTokens, model);
+ const firstKeptEntry = projectedEntries[cutPoint.firstKeptEntryIndex]?.sourceEntry;
+ if (!firstKeptEntry?.id)
+ return undefined;
+diff --git a/dist/core/compaction/utils.js b/dist/core/compaction/utils.js
+index bbbb6d1..7d71b57 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 2299ae487..e5bce48c6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -16,15 +16,15 @@ overrides:
vite@5: '>=6.4.3 <7'
patchedDependencies:
- '@earendil-works/[email protected]':
- hash: 62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1
- path: patches/@[email protected]
- '@earendil-works/[email protected]':
- hash: 6dca323bf8dc43f1fe3e458a808e5ba0d46bb51fa962f1275e3cf24c63927090
- path: patches/@[email protected]
- '@earendil-works/[email protected]':
- hash: 60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227
- path: patches/@[email protected]
+ '@earendil-works/[email protected]':
+ hash: fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344
+ path: patches/@[email protected]
+ '@earendil-works/[email protected]':
+ hash: 04fc9262ce616ddb28a253b99ba59fa562e8d8a4c347fa2ea84f710d85d42971
+ path: patches/@[email protected]
+ '@earendil-works/[email protected]':
+ hash: f343e44e55203618be186df28a5ae64e8d84992452b456169afc57b2eed5310e
+ path: patches/@[email protected]
importers:
@@ -44,8 +44,8 @@ importers:
version: 6.8.9
devDependencies:
'@earendil-works/pi-ai':
- specifier: 0.86.1
- version: 0.86.1(patch_hash=6dca323bf8dc43f1fe3e458a808e5ba0d46bb51fa962f1275e3cf24c63927090)([email protected])([email protected])
+ specifier: 0.87.0
+ version: 0.87.0(patch_hash=04fc9262ce616ddb28a253b99ba59fa562e8d8a4c347fa2ea84f710d85d42971)([email protected])([email protected])
'@pi-desktop/agent-host':
specifier: workspace:*
version: link:../../packages/agent-host
@@ -230,14 +230,14 @@ importers:
packages/agent-runtime:
dependencies:
'@earendil-works/pi-agent-core':
- specifier: 0.86.1
- version: 0.86.1(patch_hash=62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1)([email protected])([email protected])
+ specifier: 0.87.0
+ version: 0.87.0(patch_hash=fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344)([email protected])([email protected])
'@earendil-works/pi-ai':
- specifier: 0.86.1
- version: 0.86.1(patch_hash=6dca323bf8dc43f1fe3e458a808e5ba0d46bb51fa962f1275e3cf24c63927090)([email protected])([email protected])
+ specifier: 0.87.0
+ version: 0.87.0(patch_hash=04fc9262ce616ddb28a253b99ba59fa562e8d8a4c347fa2ea84f710d85d42971)([email protected])([email protected])
'@earendil-works/pi-coding-agent':
- specifier: 0.86.1
- version: 0.86.1(patch_hash=60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227)([email protected])([email protected])
+ specifier: 0.87.0
+ version: 0.87.0(patch_hash=f343e44e55203618be186df28a5ae64e8d84992452b456169afc57b2eed5310e)([email protected])([email protected])
'@pi-desktop/shared':
specifier: workspace:*
version: link:../shared
@@ -723,30 +723,30 @@ packages:
search-insights:
optional: true
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-GzUr5n4tFBHUYxN9CjcRHK8QWo9tbxNrZu6iWPQ+PFiFrLASvSZOKeAVAgh3gHv/t0X5OvUpFlrMQ/nEFfCYpg==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-t8QOTf0GTHrsDSfcdtXuA9RCkh6mnR4l25N0SM/sgH7Ih25jH4tGXNbkGs9MWpV5xTu9MRPj4A7Zn1UEwQm9+g==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-8TbBzhYsDeu5V1Zl2NsyrBqJAzX1EiEL3Np3ZjGpy0pSDdGRVOpcyW1qruLqfWmEqGcnxmvgnTMLS/wJNZO2XQ==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-c5b2FMdJ7C++HBa6AyBmusdf96gdgRqpF7J+UCq2yVGB28UETJvJ190HkgDWUaLPnOQQPbanjKMAm/TgRmFE2w==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-1XHhI6D/fyQdsBieHC/E/4zGKVOoGe4yDyX67VXvzoYkFsX/qE7NpZE7E1RC8e6Bz8B9oG/P+MQFXikv2/BGEg==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-lbRm+EMY6Jx3l+HLpbqbm9Yrhkc5u7EffLk2id+zJQEoBuR5I+tijGiZU8zlnuuCclmQOgH0PVjL9PLbeqJ9MQ==}
engines: {node: '>=22.19.0'}
hasBin: true
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-vZBuNfJnruxZyemZ3O05V0S/Ylze08ahFTIQ1Mik++gVdOevPl89gt/Uv0U97BPAJaj9cj6Vf9rcIgKtUrd0BA==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-S9JJVGHya/h0e0M+zwPTB6RkPe7PmLLqfBUTssFYW5mxAti6oZEILn4jvaUImENRC3U9RwXAB6H4gw8xj2J0GQ==}
engines: {node: '>=22.19.0'}
hasBin: true
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-SOcEqOS3oVGgKeahs2jHB906d8hFjuLP+RBee8xKYMRgw5KAeWHNg+YABfL0ALlp3Bt6tW4b632MLghc3vnTog==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-IEUMnV6mgHyOMfAxa4CKXoBKKfHM8KxNjbXWM4Bps/iLJcFMf8hQsEZ+95VnVTc7C0cU77Rmdxt773C35jb5AA==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-FU/zU/zG4RWokcZt+BVXXcieWi5ggvYnWP2kkB5XXjMaHRoy5BDhcZJ9JAnLTN9MwrCRoXgPQxOI0bFqwYeZkQ==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-7gTC0XOgQfVWg4yGxwHINBpCnGl9p4KEC7PXIc8gAwc/cyxSW4VuFQrp+r1YD3oM+rBkoepKwAt6w6+VJ7BCaw==}
engines: {node: '>=22.19.0'}
'@electron-internal/[email protected]':
@@ -4816,15 +4816,15 @@ snapshots:
transitivePeerDependencies:
- '@algolia/client-search'
- '@earendil-works/[email protected]':
+ '@earendil-works/[email protected]':
dependencies:
esbuild: 0.28.2
- '@earendil-works/[email protected](patch_hash=62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1)([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344)([email protected])([email protected])':
dependencies:
- '@earendil-works/chord': 0.86.1
- '@earendil-works/pi-ai': 0.86.1(patch_hash=6dca323bf8dc43f1fe3e458a808e5ba0d46bb51fa962f1275e3cf24c63927090)([email protected])([email protected])
- '@earendil-works/pi-telemetry': 0.86.1
+ '@earendil-works/chord': 0.87.0
+ '@earendil-works/pi-ai': 0.87.0(patch_hash=04fc9262ce616ddb28a253b99ba59fa562e8d8a4c347fa2ea84f710d85d42971)([email protected])([email protected])
+ '@earendil-works/pi-telemetry': 0.87.0
diff: 8.0.4
ignore: 7.0.8
typebox: 1.3.27
@@ -4838,11 +4838,11 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected](patch_hash=6dca323bf8dc43f1fe3e458a808e5ba0d46bb51fa962f1275e3cf24c63927090)([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=04fc9262ce616ddb28a253b99ba59fa562e8d8a4c347fa2ea84f710d85d42971)([email protected])([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.124.0([email protected])
'@aws-sdk/client-bedrock-runtime': 3.1127.0
- '@earendil-works/pi-telemetry': 0.86.1
+ '@earendil-works/pi-telemetry': 0.87.0
'@google/genai': 2.21.0
'@smithy/node-http-handler': 4.12.1
http-proxy-agent: 9.1.0
@@ -4859,12 +4859,12 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected](patch_hash=60323335b0bd5cdbd857e5b9cf24bb794766f85bf3682694b9a43694bb435227)([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=f343e44e55203618be186df28a5ae64e8d84992452b456169afc57b2eed5310e)([email protected])([email protected])':
dependencies:
- '@earendil-works/chord': 0.86.1
- '@earendil-works/pi-agent-core': 0.86.1(patch_hash=62947f964f4c6270c68576ce7aa748a00bd20bca9c96e0dc49a4c17b0b283be1)([email protected])([email protected])
- '@earendil-works/pi-ai': 0.86.1(patch_hash=6dca323bf8dc43f1fe3e458a808e5ba0d46bb51fa962f1275e3cf24c63927090)([email protected])([email protected])
- '@earendil-works/pi-tui': 0.86.1
+ '@earendil-works/chord': 0.87.0
+ '@earendil-works/pi-agent-core': 0.87.0(patch_hash=fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344)([email protected])([email protected])
+ '@earendil-works/pi-ai': 0.87.0(patch_hash=04fc9262ce616ddb28a253b99ba59fa562e8d8a4c347fa2ea84f710d85d42971)([email protected])([email protected])
+ '@earendil-works/pi-tui': 0.87.0
'@silvia-odwyer/photon-node': 0.3.4
chalk: 6.0.0
cross-spawn: 7.0.6
@@ -4889,9 +4889,9 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected]': {}
+ '@earendil-works/[email protected]': {}
- '@earendil-works/[email protected]':
+ '@earendil-works/[email protected]':
dependencies:
get-east-asian-width: 1.6.0
marked: 18.0.11
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index f07d07880..7a83053ff 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -12,12 +12,12 @@ allowBuilds:
# 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]'
+ - '@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.
@@ -46,9 +46,9 @@ overrides:
# `docs:dev` (serves 200); drop it for vitepress 2 once that ships stable.
vite@5: '>=6.4.3 <7'
patchedDependencies:
- '@earendil-works/[email protected]': patches/@[email protected]
- '@earendil-works/[email protected]': patches/@[email protected]
- '@earendil-works/[email protected]': patches/@[email protected]
+ '@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".
diff --git a/scripts/e2e-hosted-search.mjs b/scripts/e2e-hosted-search.mjs
index eefcdc372..a4eced637 100644
--- a/scripts/e2e-hosted-search.mjs
+++ b/scripts/e2e-hosted-search.mjs
@@ -87,7 +87,7 @@ when the run ends; any change between the two fails the run.`);
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`);
+ assert.equal(manifest.version, "0.87.0", `${name} must match the locked pi version`);
}
evidence.lockfileSha256 = await hash(join(root, "pnpm-lock.yaml"));
evidence.head = git("rev-parse", "HEAD");