Skip to content

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

chore(deps): upgrade Pi runtime to 1.5.0 and adopt its features

vastsaa28baea56615
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 2aa485e5c..7aa732226 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -36,8 +36,8 @@
"electron-updater": "^6.8.9"
},
"devDependencies": {
- "@earendil-works/pi-ai": "1.4.0",
- "@earendil-works/pi-mcp": "1.4.0",
+ "@earendil-works/pi-ai": "1.5.0",
+ "@earendil-works/pi-mcp": "1.5.0",
"@pi-desktop/agent-host": "workspace:*",
"@pi-desktop/computer-use": "workspace:*",
"@pi-desktop/agent-runtime": "workspace:*",
diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
index 3ce11cb7d..8854ce2a4 100644
--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx
@@ -288,7 +288,9 @@ export const AssistantTurn = memo(function AssistantTurn({
const canEditMessages = sessionAllows(session ?? (paneSessionId.startsWith("remote:") ? { id: paneSessionId } : undefined), "canEditMessages");
const summary = getAssistantTurnSummary(entry);
const { actionMessage, metaMessage, latestUsageMessage, usage, responseDurationMs, responseOutputTokens } = summary;
- const modelId = metaMessage?.modelId ?? latestUsageMessage?.modelId;
+ const modelSource = metaMessage?.modelId ? metaMessage : latestUsageMessage;
+ const modelId = modelSource?.modelId;
+ const responseModelId = modelSource?.responseModelId;
const complete = !isActive && !summary.hasError && summary.hasContent && Boolean(actionMessage);
// A live reply is joined only on menu/copy demand. Finished reply plugins
// still receive exactly the text that the completed turn's Copy action uses.
@@ -432,6 +434,7 @@ export const AssistantTurn = memo(function AssistantTurn({
{!isActive && metaMessage ? (
<MessageMeta
modelId={modelId}
+ responseModelId={responseModelId}
usage={usage}
responseDurationMs={responseDurationMs}
responseOutputTokens={responseOutputTokens}
diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsx
index 5942fc729..3f9400317 100644
--- a/apps/desktop/src/features/chat/transcript/shared.tsx
+++ b/apps/desktop/src/features/chat/transcript/shared.tsx
@@ -160,12 +160,15 @@ export function CopyButton({
}
export function MessageMeta({
modelId,
+ responseModelId,
usage,
responseDurationMs,
responseOutputTokens,
responseOutputEstimated,
}: {
modelId?: string;
+ /** Concrete model the provider reported serving the turn, when it differs. */
+ responseModelId?: string;
usage?: MessageUsage;
responseDurationMs?: number;
responseOutputTokens?: number;
@@ -187,9 +190,19 @@ export function MessageMeta({
return (
<div className="message-meta">
{modelId ? (
- <span className="message-meta-chip model" title={modelId}>
- {modelId}
- </span>
+ responseModelId ? (
+ <span
+ className="message-meta-chip model"
+ title={t("chat.servedByModel", { requested: modelId, served: responseModelId })}
+ aria-label={t("chat.servedByModel", { requested: modelId, served: responseModelId })}
+ >
+ {responseModelId}
+ </span>
+ ) : (
+ <span className="message-meta-chip model" title={modelId}>
+ {modelId}
+ </span>
+ )
) : null}
{usage && showTurnUsage ? (
<TurnUsageCapsule
@@ -330,7 +343,11 @@ export function AssistantErrorMessage({ message }: { message: UiMessage }) {
{message.modelId ? (
<>
<dt>{t("chat.errorModel")}</dt>
- <dd>{message.modelId}</dd>
+ <dd>
+ {message.responseModelId
+ ? t("chat.servedByModel", { requested: message.modelId, served: message.responseModelId })
+ : message.modelId}
+ </dd>
</>
) : null}
</dl>
diff --git a/apps/desktop/test/anthropic-oauth-retry.test.mjs b/apps/desktop/test/anthropic-oauth-retry.test.mjs
index fa1eb55e7..36e6a5749 100644
--- a/apps/desktop/test/anthropic-oauth-retry.test.mjs
+++ b/apps/desktop/test/anthropic-oauth-retry.test.mjs
@@ -144,7 +144,7 @@ test("token requests identify the client instead of inheriting a browser User-Ag
assert.equal((await signIn()).kind, "done");
await oauth.resolveAuth(seed());
assert.deepEqual(requests.map(req => req.body.grant_type), ["authorization_code", "refresh_token"]);
- for (const req of requests) assert.match(req.headers["user-agent"], /^pi\/1\.4\.0 \(/);
+ for (const req of requests) assert.match(req.headers["user-agent"], /^pi\/1\.5\.0 \(/);
});
});
diff --git a/apps/desktop/test/message-meta-served-model.test.mjs b/apps/desktop/test/message-meta-served-model.test.mjs
new file mode 100644
index 000000000..07d714812
--- /dev/null
+++ b/apps/desktop/test/message-meta-served-model.test.mjs
@@ -0,0 +1,58 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { createInstance } from "i18next";
+import { I18nextProvider } from "react-i18next";
+import { catalogs } from "@pi-desktop/i18n";
+import { createServer } from "vite";
+import { fileURLToPath } from "node:url";
+
+/*
+ * A router or virtual model (OpenRouter auto, a pi-messages virtual model)
+ * resolves to a concrete model per response (Pi 1.5 `responseModel`). The
+ * turn's model chip shows what actually answered and keeps the requested model
+ * reachable in its accessible label. Rendered through the real component and
+ * English catalog.
+ */
+
+const ROOT = fileURLToPath(new URL("..", import.meta.url));
+
+async function withMeta(run) {
+ const server = await createServer({
+ root: ROOT,
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ esbuild: { jsx: "automatic" },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ try {
+ const { MessageMeta } = await server.ssrLoadModule("/src/features/chat/transcript/shared.tsx");
+ const i18n = createInstance();
+ // Match the app: React escapes rendered values (src/main.tsx).
+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } }, interpolation: { escapeValue: false } });
+ const render = (props) =>
+ renderToStaticMarkup(createElement(I18nextProvider, { i18n }, createElement(MessageMeta, props)));
+ await run({ render });
+ } finally {
+ await server.close();
+ }
+}
+
+test("the model chip names the served model and labels the requested one", async () => {
+ await withMeta(({ render }) => {
+ const html = render({ modelId: "openrouter/auto", responseModelId: "anthropic/claude-sonnet-4.5" });
+ assert.match(html, />anthropic\/claude-sonnet-4\.5</);
+ assert.match(html, /aria-label="Requested openrouter\/auto; served by anthropic\/claude-sonnet-4\.5"/);
+ assert.match(html, /title="Requested openrouter\/auto; served by anthropic\/claude-sonnet-4\.5"/);
+ });
+});
+
+test("a turn without a different served model keeps the requested model chip", async () => {
+ await withMeta(({ render }) => {
+ const html = render({ modelId: "gpt-5.5" });
+ assert.match(html, /title="gpt-5\.5">gpt-5\.5</);
+ assert.doesNotMatch(html, /served by/);
+ });
+});
diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rs
index 741584e2c..833b1e845 100644
--- a/crates/host-core/src/plugin_sessions.rs
+++ b/crates/host-core/src/plugin_sessions.rs
@@ -293,6 +293,7 @@ fn parse_message(
usage: None,
response_duration_ms: None,
response_output_tokens: None,
+ response_model_id: None,
error: None,
revision_root_id: None,
revision_count: None,
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index 86b684154..783c63954 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -227,6 +227,11 @@ pub struct UiMessage {
pub model_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_id: Option<String>,
+ /// Concrete model the provider reports serving this turn when it differs
+ /// from `model_id` (virtual or fallback models). Stored in record meta; no
+ /// SQL migration, and older builds ignore it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub response_model_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub usage: Option<MessageUsage>,
/// Elapsed model streaming time for the response throughput statistic.
@@ -439,6 +444,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<String
if let Some(provider_id) = &message.provider_id {
meta_obj.insert("providerId".into(), json!(provider_id));
}
+ if let Some(response_model_id) = &message.response_model_id {
+ meta_obj.insert("responseModelId".into(), json!(response_model_id));
+ }
if let Some(usage) = &message.usage {
meta_obj.insert("usage".into(), json!(usage));
}
@@ -632,6 +640,10 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
let error = meta.get("error").cloned();
let response_duration_ms = meta.get("responseDurationMs").and_then(|v| v.as_i64());
let response_output_tokens = meta.get("responseOutputTokens").and_then(|v| v.as_i64());
+ let response_model_id = meta
+ .get("responseModelId")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
let revision_root_id = meta
.get("revisionRootId")
.and_then(|v| v.as_str())
@@ -728,6 +740,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
usage,
response_duration_ms,
response_output_tokens,
+ response_model_id: response_model_id.clone(),
error,
revision_root_id,
revision_count,
@@ -784,6 +797,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
usage,
response_duration_ms,
response_output_tokens,
+ response_model_id: response_model_id.clone(),
error,
revision_root_id,
revision_count,
@@ -4488,6 +4502,7 @@ mod tests {
usage: None,
response_duration_ms: None,
response_output_tokens: None,
+ response_model_id: None,
error: None,
revision_root_id: None,
revision_count: None,
@@ -5453,6 +5468,7 @@ mod tests {
usage: None,
response_duration_ms: None,
response_output_tokens: None,
+ response_model_id: None,
error: None,
revision_root_id: None,
revision_count: None,
@@ -6257,6 +6273,7 @@ mod tests {
}),
response_duration_ms: Some(2_000),
response_output_tokens: Some(34),
+ response_model_id: Some("vendor/concrete-model".into()),
error: None,
revision_root_id: None,
revision_count: None,
@@ -6316,6 +6333,10 @@ mod tests {
assert_eq!(usage.total_tokens, 48);
assert_eq!(detail.messages[0].response_duration_ms, Some(2_000));
assert_eq!(detail.messages[0].response_output_tokens, Some(34));
+ assert_eq!(
+ detail.messages[0].response_model_id.as_deref(),
+ Some("vendor/concrete-model")
+ );
}
#[test]
@@ -6398,6 +6419,7 @@ mod tests {
usage: None,
response_duration_ms: None,
response_output_tokens: None,
+ response_model_id: None,
error: None,
revision_root_id: None,
revision_count: None,
diff --git a/docs/project/pi-150-adoption.md b/docs/project/pi-150-adoption.md
new file mode 100644
index 000000000..505b167d1
--- /dev/null
+++ b/docs/project/pi-150-adoption.md
@@ -0,0 +1,113 @@
+# Pi 1.5.0 adoption
+
+## Scope
+
+Upgrade Agent Runtime's `pi-agent-core`, `pi-ai`, and `pi-coding-agent`, plus
+Desktop's `pi-ai` and `pi-mcp`, to exactly 1.5.0. Keep the Pi release group
+aligned through the lockfile and exact release-age exclusions, which now include
+the new `pi-schema` package. No Host protocol, database schema, persisted
+provider endpoint, permission policy, extension `VERSION` marker, or storage
+ownership changes.
+
+Official release notes: [Pi 1.5.0](https://github.com/earendil-works/pi/releases/tag/v1.5.0).
+
+## Compatibility work
+
+- Rebase the three pnpm patches onto the published 1.5.0 package layouts.
+ `pi-agent-core` applied unchanged. `pi-ai` needed manual ports where 1.5.0
+ replaced re-parsing with incremental tool-call parsing and moved compat
+ schemas to `pi-schema`:
+ - Anthropic hosted-search capture now registers `server_tool_use` and
+ `web_search_tool_result` blocks in the adapter's `openBlocks` map and
+ streams the query through `ToolCallArgumentsStream`, instead of an
+ `index` / `inputJson` scratch on the block.
+ - `requiresNonEmptyReasoningReplay` is declared with the pi-schema builders.
+ - Local request-error mapping is re-inserted where 1.5.0 removed the
+ per-block scratch cleanup from the Anthropic and OpenAI Responses catch
+ paths.
+ - `pi-coding-agent` only needed its `Api` type import re-applied.
+- `pi-ai` no longer re-exports TypeBox. Agent Runtime imports `Type` from its
+ existing direct `typebox` dependency. Tool schemas stay plain JSON Schema, so
+ validation on pi-schema accepts them unchanged.
+- Bump Agent Runtime's direct `undici` from 8.10.2 to 8.12.3 to match
+ `pi-coding-agent` 1.5.0. Two 8.x copies split `pi-ai` into two peer instances
+ and pulled undici into the sidecar entry (891 KiB, over the 500 KiB gate);
+ one copy restores 315 KiB and the 1.4 instance topology.
+
+## Inherited without Desktop code changes
+
+- Incremental tool-call argument parsing in providers and agent proxy streams
+ (lower CPU and memory for large streamed tool calls).
+- pi-schema coercion for plain JSON Schema tools, including MCP tools (numeric
+ strings, single value to array). Validation messages shown to the model
+ change wording.
+- JPEG-first image resizing in the bundled coding-agent resize worker.
+- Provider fixes: Gemini `const` to `enum`, Bedrock strict-tool retry,
+ OpenRouter reported costs, LiteLLM overflow detection, Claude
+ system-after-empty-assistant ordering and capped effort, Kimi K3.1 settings,
+ GPT-5.4/5.5 tool namespace after model switch, OpenCode endpoints.
+- GPT-6.1 Terra and the models.dev v2 catalog in pi-ai's built-in models.
+ Desktop's bundled models.dev catalog and overlays remain the source of what
+ the UI offers.
+
+## Adopted 1.5 features
+
+- **Billed vs. estimated cost.** `usageFromPi` records a total marked
+ `usage.cost.totalFromProvider` as `costStatus: "reported"`, even when the
+ model has no catalog rates, and keeps unmarked totals `estimated`. Replay back
+ into Pi restores the marker. Persisted cost keeps its five numeric fields.
+- **Served model.** Agent Runtime stores Pi's `responseModel` as the additive
+ `responseModelId` message field when it differs from the requested model and
+ is not a dated snapshot of it (`response-model.ts`). Host-core round-trips it
+ through record meta with no SQL migration; older builds ignore it. The model
+ chip shows the served model and labels the requested one (`chat.servedByModel`
+ in all shipped locales), and error details show both.
+- **Extension `pi.exec()`.** `extensions/managed-exec.ts` now decodes output
+ across chunk boundaries, caps stdout and stderr combined in bytes (default
+ 10 MiB), terminates on overflow with `truncated: true` and a nonzero code, and
+ resolves a spawn failure with code 1 and the spawn error in stderr.
+ `ExtensionExecResult` gains `truncated`.
+- **Zhipu/Z.ai `1308`.** Desktop's classifier treats the JSON error code `1308`
+ (plan usage limit, sent as 429) as terminal `PROVIDER_ERROR`, so neither retry
+ budget replays it.
+- **GPT-6.1 Terra.** The bundled models.dev catalog is refreshed to the current
+ snapshot, which lists `gpt-6.1-terra` for OpenAI and Azure (1.05M context,
+ reasoning). The refresh also drops `openai/gpt-image-1` from chat records;
+ image settings metadata lives in `settings-operation-metadata.json` and is
+ unaffected. ChatGPT (Codex) accounts list models from the live
+ `/codex/models` endpoint; `CODEX_MODELS_CLIENT_VERSION` is unchanged because
+ verifying a newer client version needs a real account.
+- Not applicable to Desktop: TUI rendering, `pi update` / self-update command,
+ extension package changelogs, terminal keybinding hints.
+
+## Explicitly unchanged
+
+- Existing user data needs no migration. No persisted format, RPC, Plugin SDK,
+ or permission contract changes.
+- `pi-coding-agent` remains transitional; it is not the normal Desktop agent
+ loop, compaction engine, or durable session store.
+
+## Validation
+
+Validation was run from the dedicated request worktree based on
+`d858250b62ab2224162e26d16643d04f22fa5eb6` (`origin/main`, 2026-11-06).
+
+- `pnpm build:js`, Desktop typecheck, and lint passed.
+- Agent Runtime: 121 test files, 1,753 tests passed. Shared: 1,402 passed.
+ i18n: 31 passed.
+- Desktop: 4,862 tests, 4,856 passed, 3 skipped. Three timing-sensitive tests
+ (`macos-signing-watchdog`, `npm-executable`, `remote-host-ssh-transport`)
+ timed out under the full parallel run and passed 41/41 when rerun alone.
+- Host-core: `cargo fmt --check` passed; 1,202 of 1,203 tests passed. The one
+ failure, `review_rpc_records_workspace_scratch_and_approved_external_write_edit`,
+ fails identically on the unmodified base commit. Clippy reports two existing
+ warnings in `review.rs` and `transcripts.rs`.
+- Pi dependency and patch gates passed; patch-hash fixture tests passed.
+- Trusted-extension E2E passed 57/57 with the worktree-built debug Host binary
+ and the primary checkout's Electron, using isolated fixture state.
+- Hosted-search E2E passed 10/10 only with a local, uncommitted fake-host
+ addition for `tools.fileBatchCapabilities`. Without it every scenario stops
+ with `Unsupported fake-host RPC`: `bdc35fa12` added that runtime RPC but not
+ the handler in `scripts/e2e/hosted-search-sidecar.mjs`, which this change
+ does not touch. That fixture gap is a separate fix.
+- No real provider or live service was used.
diff --git a/docs/spec/02-architecture/02-tech-stack.md b/docs/spec/02-architecture/02-tech-stack.md
index e52fd04cd..b303d0ff4 100644
--- a/docs/spec/02-architecture/02-tech-stack.md
+++ b/docs/spec/02-architecture/02-tech-stack.md
@@ -12,9 +12,9 @@
| 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` | 1.4.0 | agent loop |
-| Model API | `@earendil-works/pi-ai` | 1.4.0 | provider adapters, OAuth, and stream handling |
-| Model catalog | models.dev + Pi Providers/Models | bundled models.dev + pinned Pi 1.4.0 | models.dev chat metadata; Pi account IDs, wire capabilities, and typed operations |
+| Agent engine | `@earendil-works/pi-agent-core` | 1.5.0 | agent loop |
+| Model API | `@earendil-works/pi-ai` | 1.5.0 | provider adapters, OAuth, and stream handling |
+| Model catalog | models.dev + Pi Providers/Models | bundled models.dev + pinned Pi 1.5.0 | models.dev chat metadata; Pi account IDs, wire capabilities, and typed operations |
> models.dev owns published chat metadata; pi-ai owns transports and auth.
> Host persists Desktop account rows, credentials, and explicit binding overrides.
diff --git a/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
index ff14b6fdd..68357c334 100644
--- a/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
+++ b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
@@ -9,10 +9,10 @@ boundaries must keep that split clear as upstream packages evolve.
## 2. Current ownership
The sidecar pins `@earendil-works/pi-agent-core`, `pi-ai`, and
-`pi-coding-agent` together at exactly `1.4.0`; Desktop's `pi-ai` and `pi-mcp`
+`pi-coding-agent` together at exactly `1.5.0`; Desktop's `pi-ai` and `pi-mcp`
development dependencies use the same release. Target-release package patches
remain narrow compatibility deltas and are listed with their audited behavior
-in `docs/project/pi-140-adoption.md`.
+in `docs/project/pi-150-adoption.md`.
- `@earendil-works/pi-agent-core` supplies the agent loop and its stable agent,
event, and tool types. Agent Runtime owns desktop-specific compaction,
@@ -39,7 +39,7 @@ in `docs/project/pi-140-adoption.md`.
attribution follows that SDK's install-telemetry setting. The Desktop-owned
main and delegated Agent paths use the explicit identity above.
-The extension shim is a versioned compatibility subset, not the full 1.4.0
+The extension shim is a versioned compatibility subset, not the full 1.5.0
coding-agent API. Its legacy `VERSION` marker remains sourced from
`TRUSTED_EXTENSION_KERNEL_VERSION` and intentionally identifies the modeled
0.87.1 extension surface.
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 04b55b635..1f0ff282f 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -995,6 +995,7 @@ type UiMessage = {
sessionMessage?: SessionMessageOrigin;
thinking?: string; // assistant reasoning, never folded into content
usage?: MessageUsage; // provider-reported assistant usage
+ responseModelId?: string; // concrete served model when it differs from modelId
responseDurationMs?: number; // elapsed assistant response duration for throughput
providerWaitMs?: number; // request start to first model response event
modelStreamDurationMs?: number; // streamed thinking and answer duration
@@ -1076,6 +1077,16 @@ no-op. `responseDurationMs` and `responseOutputTokens` are optional transcript
metadata persisted in message metadata, so protocol v11 and storage schema v16
remain unchanged.
+`responseModelId` is the same kind of optional message metadata. Agent Runtime
+sets it from the provider-reported response model (Pi `responseModel`) only when
+that model differs from the requested `modelId` and is not a dated snapshot of
+it; the value is trimmed, bounded to 200 characters, and rejected when it holds
+control characters. The transcript model chip shows it and names the requested
+model in its label. `MessageUsage.costStatus` is `reported` when the provider
+returned the billed total (Pi `usage.cost.totalFromProvider`), `estimated` when
+the total comes from catalog rates, and `unknown` without a usable price; a
+rollup is `reported` only when every part is.
+
The Settings font picker (ADR 0083) reads installed system font families
through one Electron-only allowlisted channel:
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 89887ab4d..76cabcdba 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -207,8 +207,8 @@ claim the same counter, so a setup 429 followed by a stream 429 cannot reset or
multiply the budget. The captured response status is applied before classifying
the provider message in both phases, so a generic 429 body still enters the
429 budget while known non-retryable classifications remain terminal. Explicit
-billing/account exhaustion (including `insufficient_quota` and spend-limit
-codes) is terminal `PROVIDER_ERROR` even with HTTP 429. The main session and
+billing/account exhaustion (including `insufficient_quota`, spend-limit
+codes, and Zhipu/Z.ai usage-limit code `1308`) is terminal `PROVIDER_ERROR` even with HTTP 429. The main session and
builtin subagents use the same controller and policy.
429 retries are silent at the transcript lifecycle: no intermediate assistant
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 066f06a86..51b106535 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -414,7 +414,8 @@ replayed by either retry budget, and a delegate reports it as
messages (including OpenCode Zen's `FreeUsageLimitError`, `insufficient_quota`,
`credit_balance_exhausted`,
organization/project spend-limit codes, `insufficient credits`, and
-`requires more credits`) map to terminal `PROVIDER_ERROR` even when the HTTP
+`requires more credits`, and Zhipu/Z.ai JSON error code `1308` for a reached plan
+usage limit) map to terminal `PROVIDER_ERROR` even when the HTTP
status is 429, and HTTP 402 is terminal `PROVIDER_ERROR` even when the body
omits those phrases. Throughput rate-limit wording, including
Bedrock's `Throttling error: Too many tokens, please wait before trying again.`,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 925b9d92c..285429a01 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -290,6 +290,32 @@
- **Milestone:** Maintenance.
- **Status:** Candidate validation recorded in `docs/project/pi-140-adoption.md`.
+### E2E-PI-150-kernel-upgrade
+
+- **Preconditions:** Exact Pi 1.5.0 release-group pins (including the new
+ `pi-schema` package) and rebased package patches in a dedicated worktree,
+ isolated fixture state, and no real provider credentials.
+- **Steps:** Run the existing runtime, native Pi session, and identity suites
+ against the installed 1.5.0 packages. Stream Anthropic hosted-search blocks
+ through the incrementally parsed 1.5.0 adapter. Build the split sidecar
+ bundle. Run the existing hosted-search and trusted-extension offline suites.
+- **Expected:** Desktop tool schemas built with TypeBox validate unchanged on
+ pi-schema. Hosted-search capture, live query updates, citations, replay, and
+ local request errors remain intact. The release group resolves a single
+ `undici` 8.x, so the sidecar entry stays below its size threshold. Identity
+ headers report 1.5.0. No provider credentials or live services are used.
+- **Coverage:** `pi-upstream-1.5-identity.test.ts`,
+ `pi-upstream-1.5-contract.test.ts`, `pi-1.5-adapter-features.test.ts`,
+ `official-native-search.test.ts`, `native-pi-session.test.ts`,
+ `agent-runtime-bundle-package.test.mjs`, `anthropic-oauth-retry.test.mjs`,
+ plus the existing `test:e2e:hosted-search` and
+ `test:e2e:trusted-extensions` commands.
+- **Specs:** [Pi dependency boundary](../02-architecture/06-pi-runtime-dependency-boundary.md),
+ [trusted extensions](../07-plugins/16-trusted-extensions.md).
+- **Acceptance:** Offline runtime/contract and isolated process validation.
+- **Milestone:** Maintenance.
+- **Status:** Candidate validation recorded in `docs/project/pi-150-adoption.md`.
+
### E2E-QUEUE-send-now-wakes-subagents
- **Preconditions:** Dedicated request worktree with built workspace packages,
diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.md
index 1f5ecdb7d..522aaba2c 100644
--- a/docs/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/spec/07-plugins/16-trusted-extensions.md
@@ -395,6 +395,10 @@ are detached before publication so later extension mutations cannot rewrite them
SDK `exec` owns its process group/tree and terminates it on scope retirement or
its explicit timeout;
disposal waits for tracked process cleanup, with cleanup failures diagnosed.
+Output is decoded across chunk boundaries. `maxBuffer` (default 10 MiB) caps
+stdout and stderr combined in bytes; overflow terminates the command and returns
+`truncated: true` with a nonzero `code`. A command that cannot be spawned
+resolves with `code: 1` and the spawn error in `stderr` instead of rejecting.
Processes deliberately escaping the group and direct Node API spawns are outside
this ownership contract.
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 7dc6e7af8..730bf6c85 100644
--- a/docs/zh-CN/spec/02-architecture/02-tech-stack.md
+++ b/docs/zh-CN/spec/02-architecture/02-tech-stack.md
@@ -15,9 +15,9 @@
| 主机后端 | **Rust** | 稳定的 Rust 工具链 | tools/plugins/permissions/persistence 适配器 |
| Rust 异步 | 东京 | 稳定 | 主机服务 |
| 主机 RPC | stdio JSON-RPC (NDJSON) | 冷冻(D001) | Electron 主 ↔ Rust 主机 |
-| Agent engine | `@earendil-works/pi-agent-core` | 1.4.0 | agent loop |
-| Model API | `@earendil-works/pi-ai` | 1.4.0 | provider adapters, OAuth, and stream handling |
-| Model catalog | models.dev + Pi Providers/Models | bundled models.dev + pinned Pi 1.4.0 | models.dev chat metadata; Pi account IDs, wire capabilities, and typed operations |
+| Agent engine | `@earendil-works/pi-agent-core` | 1.5.0 | agent loop |
+| Model API | `@earendil-works/pi-ai` | 1.5.0 | provider adapters, OAuth, and stream handling |
+| Model catalog | models.dev + Pi Providers/Models | bundled models.dev + pinned Pi 1.5.0 | models.dev chat metadata; Pi account IDs, wire capabilities, and typed operations |
> models.dev owns published chat metadata; pi-ai owns transports and auth.
> Host 持有 Desktop 账户行、凭据和显式绑定覆盖。
diff --git a/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md b/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md
index 269c1a464..1fdfc0c66 100644
--- a/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md
+++ b/docs/zh-CN/spec/02-architecture/06-pi-runtime-dependency-boundary.md
@@ -10,8 +10,8 @@ JavaScript 包。上游包演进时,必须保持这一职责划分清晰。
## 2. 当前职责
Sidecar 将 `@earendil-works/pi-agent-core`、`pi-ai` 与 `pi-coding-agent` 精确固定在
-`1.4.0`;Desktop 的 `pi-ai` 和 `pi-mcp` 开发依赖也使用同一版本。补丁行为与迁移
-记录见 `docs/project/pi-140-adoption.md`。
+`1.5.0`;Desktop 的 `pi-ai` 和 `pi-mcp` 开发依赖也使用同一版本。补丁行为与迁移
+记录见 `docs/project/pi-150-adoption.md`。
- `@earendil-works/pi-agent-core` 提供 Agent 循环,以及稳定的 agent、event、tool
类型。Agent Runtime 自行维护桌面专用的上下文投影、压缩和 prompt 模板展开。
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 4b5292bd2..133201fb5 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -791,6 +791,7 @@ type UiMessage = {
sessionMessage?: SessionMessageOrigin;
thinking?: string; // assistant reasoning, never folded into content
usage?: MessageUsage; // provider-reported assistant usage
+ responseModelId?: string; // concrete served model when it differs from modelId
responseDurationMs?: number; // model stream duration for throughput
responseOutputTokens?: number; // estimated partial output when stop has no final usage
toolName?: string;
@@ -862,6 +863,12 @@ ID、或会话无法解析出默认目标时,得到 `supportsReasoning: false`
元数据保留在消息元数据中,因此协议 v11 和存储架构 v16
保持不变。
+`responseModelId` 同为可选消息元数据。仅当 Provider 报告的响应模型(Pi `responseModel`)与请求的
+`modelId` 不同且不是其日期快照时,Agent Runtime 才写入;值会去除首尾空白、限制在 200 字符内,含控制字符则丢弃。
+转录本模型标签显示该值,并在标签说明中注明请求的模型。`MessageUsage.costStatus` 为 `reported` 表示 Provider
+返回了实际计费总额(Pi `usage.cost.totalFromProvider`),`estimated` 表示按目录单价估算,`unknown` 表示无可用价格;
+汇总仅在所有部分均为 `reported` 时才为 `reported`。
+
设置字体选择器(ADR 0083)通过一个仅 Electron 的允许通道读取
系统已安装字体:
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index 9f0bfb555..e34ce2ab7 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -158,7 +158,7 @@ pi 消费排队输入时保留渲染器提供的消息 id;即使补充输入
429 后跟流阶段的 429 无法重置或倍增该预算。在两个阶段中,
捕获的响应状态都会在对提供商消息进行分类之前应用,因此通用的
429 正文仍会进入 429 预算,而已知的不可重试分类仍然是终止的。明确的
-账单/账户额度耗尽(包括 `insufficient_quota` 和消费限额代码)即使状态为
+账单/账户额度耗尽(包括 `insufficient_quota`、消费限额代码和智谱/Z.ai 用量上限代码 `1308`)即使状态为
HTTP 429,也会成为终止的 `PROVIDER_ERROR`。
主会话和内置子代理使用相同的控制器和策略。
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index b78302ff9..df090c16b 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -400,7 +400,7 @@ Node sidecar 将提供商 SDK 错误映射到:
`maximum prompt length is`、Groq、llama.cpp,以及 Bedrock 的
`Input is too long for requested model`。`CONTEXT_TOO_LARGE` 不会进入任何重试
预算,子代理会将其报告为 `SUBAGENT_CONTEXT_OVERFLOW`。明确的账单/账户耗尽代码和
-消息(包括 `insufficient_quota`、`credit_balance_exhausted`、组织用量限额以及组织/项目消费限额代码)
+消息(包括 `insufficient_quota`、`credit_balance_exhausted`、组织用量限额、组织/项目消费限额代码以及智谱/Z.ai 用量上限 JSON 代码 `1308`)
即使 HTTP 状态为 429,也映射为终止的 `PROVIDER_ERROR`。吞吐限流措辞(包括 Bedrock 的
`Throttling error: Too many tokens, please wait before trying again.`)仍映射为
`PROVIDER_RATE_LIMITED`。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 487e34a99..75caab25e 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -51,6 +51,23 @@
`test:e2e:hosted-search` 和 `test:e2e:trusted-extensions` 命令。具体范围与候选验证记录见英文源及
`docs/project/pi-140-adoption.md`。
+### E2E-PI-150-kernel-upgrade
+
+- **前提:** 在专属 worktree 中精确固定 Pi 1.5.0 release group(含新增的 `pi-schema`)并
+ 重建包补丁,使用隔离 fixture 状态,不提供真实 Provider 凭据。
+- **步骤:** 在已安装的 1.5.0 包上运行现有 runtime、原生 Pi 会话和身份测试;经 1.5.0
+ 增量解析的 Anthropic 适配器流式传输 hosted-search 块;构建拆分的 sidecar bundle;运行现有
+ hosted-search 和可信扩展离线套件。
+- **预期:** Desktop 用 TypeBox 构建的工具 schema 在 pi-schema 上校验不变。Hosted-search
+ 捕获、实时查询更新、引用、重放与本地请求错误保持不变。Release group 只解析一个 `undici`
+ 8.x,sidecar 入口保持在体积阈值内。身份请求头报告 1.5.0。不使用 Provider 凭据或线上服务。
+- **覆盖:** `pi-upstream-1.5-identity.test.ts`、`pi-upstream-1.5-contract.test.ts`、
+ `pi-1.5-adapter-features.test.ts`、`official-native-search.test.ts`、
+ `native-pi-session.test.ts`、`agent-runtime-bundle-package.test.mjs`、
+ `anthropic-oauth-retry.test.mjs`,以及现有 `test:e2e:hosted-search` 和
+ `test:e2e:trusted-extensions` 命令。具体范围与候选验证记录见英文源及
+ `docs/project/pi-150-adoption.md`。
+
### E2E-LEGACY-DICTATION-idle-model-release
- **前提:** 通过 `VoiceService` 接口测试保留的本地 Dictation 服务,使用确定性的
diff --git a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
index 01492a8d6..97ea4f450 100644
--- a/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
+++ b/docs/zh-CN/spec/07-plugins/16-trusted-extensions.md
@@ -301,6 +301,8 @@ Agent 工作。在请求前 hook 等待期间停止,不会继续请求模型
事件的 30 秒上限,可运行至完成、传入信号取消、Stop 或销毁;迟到的工具进度和结果被丢弃。
已采纳的工具进度和结果会先复制再发布,扩展之后的原地修改不能改写它们。`pi.exec`
创建的进程树随作用域退出或显式超时终止,销毁等待已登记进程清理并报告失败。
+输出跨数据块解码;`maxBuffer`(默认 10 MiB)按字节合并限制 stdout 与 stderr,超限即终止命令并返回
+`truncated: true` 与非零 `code`。无法启动的命令返回 `code: 1`,`stderr` 为启动错误,不再抛出。
主动逃离进程组或通过 Node API 直接创建的进程不在此所有权范围。
带返回值的 Hook 输入输出使用独立副本,头部修改仅在处理器及时成功后提交。
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index cd7bbdc6e..d7c375358 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -31,13 +31,13 @@
"clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('dist-bundle',{recursive:true,force:true})\""
},
"dependencies": {
- "@earendil-works/pi-agent-core": "1.4.0",
- "@earendil-works/pi-ai": "1.4.0",
- "@earendil-works/pi-coding-agent": "1.4.0",
+ "@earendil-works/pi-agent-core": "1.5.0",
+ "@earendil-works/pi-ai": "1.5.0",
+ "@earendil-works/pi-coding-agent": "1.5.0",
"@pi-desktop/shared": "workspace:*",
"jiti": "2.7.0",
"typebox": "1.3.27",
- "undici": "8.10.2",
+ "undici": "8.12.3",
"yaml": "2.9.0"
},
"devDependencies": {
diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.ts
index 2a9dcbfc6..ffc16a70d 100644
--- a/packages/agent-runtime/src/agent-errors.test.ts
+++ b/packages/agent-runtime/src/agent-errors.test.ts
@@ -669,6 +669,25 @@ describe("classifyAgentError", () => {
});
});
+ // Zhipu/Z.ai code 1308 is the plan usage cap, sent as 429; it resets after
+ // hours, so the rate-limit budget must not replay it (pi #11537).
+ it.each([
+ '429 {"error":{"code":"1308","message":"已达到 5 小时的使用上限。您的限额将在 2026-11-06 23:00:00 重置。"}}',
+ '429: {"error":{"code":1308,"message":"Usage limit reached for 5 hour."}}',
+ ])("does not retry the Zhipu usage-limit code: %s", (message) => {
+ expect(classifyAgentError(Object.assign(new Error(message), { status: 429 }))).toMatchObject({
+ code: "PROVIDER_ERROR",
+ retriable: false,
+ });
+ });
+
+ it("keeps a 429 that only mentions 1308 elsewhere retryable", () => {
+ expect(classifyAgentError(Object.assign(
+ new Error('429 {"error":{"code":"1302","message":"rate limit, request 13080"}}'),
+ { status: 429 },
+ ))).toMatchObject({ code: "PROVIDER_RATE_LIMITED", retriable: true });
+ });
+
it("classifies structured 429 quota errors before generic status handling", () => {
expect(classifyAgentError(Object.assign(
new Error("429: rate limit response"),
diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.ts
index 8c0064cd5..ca94df4bd 100644
--- a/packages/agent-runtime/src/agent-errors.ts
+++ b/packages/agent-runtime/src/agent-errors.ts
@@ -60,6 +60,14 @@ const RATE_LIMIT_PATTERN =
const EXHAUSTED_QUOTA_CODE_PATTERN =
/\b(?:insufficient_quota|credit_balance_exhausted|organization_spend_limit_exceeded|project_spend_limit_exceeded|organization_usage_limit_exceeded|FreeUsageLimitError)\b/i;
+/**
+ * Zhipu/Z.ai (open.bigmodel.cn) error code 1308: the plan usage limit is
+ * reached. It arrives as HTTP 429 but resets after hours, so it is terminal
+ * like pi-ai 1.5 treats it. Only a JSON `code` field matches; a bare 1308 in
+ * a byte count or request id does not.
+ */
+const ZHIPU_USAGE_LIMIT_PATTERN = /"code"\s*:\s*"?1308(?![0-9])/;
+
const EXHAUSTED_QUOTA_MESSAGE_PATTERN =
/\b(?:billing|spending|credit|disk)\s+quotas?\b|\b(?:organization|project)\s+spend\s+limit\s+(?:reached|exceeded)\b|\bquota\b.{0,100}\b(?:plan|billing)\b|\binsufficient\s+credits\b|\brequires\s+more\s+credits\b|\bpayment\s+required\b/i;
@@ -646,6 +654,7 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {
if (
EXHAUSTED_QUOTA_CODE_PATTERN.test(rawMessage) ||
EXHAUSTED_QUOTA_MESSAGE_PATTERN.test(rawMessage) ||
+ ZHIPU_USAGE_LIMIT_PATTERN.test(rawMessage) ||
(typeof providerCode === "string" &&
EXHAUSTED_QUOTA_CODE_PATTERN.test(providerCode))
) {
diff --git a/packages/agent-runtime/src/agent-messages.ts b/packages/agent-runtime/src/agent-messages.ts
index 53687ee93..5e3bcff78 100644
--- a/packages/agent-runtime/src/agent-messages.ts
+++ b/packages/agent-runtime/src/agent-messages.ts
@@ -72,8 +72,15 @@ export function usageFromPi(
const validCost = usage.cost && (["input", "output", "cacheRead", "cacheWrite", "total"] as const).every((key) => Number.isFinite(usage.cost[key]) && usage.cost[key] >= 0);
// Pi adapters normally calculate cost from model rates. Unmarked all-zero
// costs are also their missing-price placeholder, not evidence of free use.
- const costStatus = provenance.costStatus ?? (validCost && usage.cost.total > 0 ? "estimated" : "unknown");
- const cost = validCost && costStatus !== "unknown" ? { ...usage.cost } : undefined;
+ // Pi 1.5 marks a total that is the provider-billed cost (for example
+ // OpenRouter usage accounting). That is authoritative over catalog-rate
+ // provenance, including models without native rates.
+ const billed = validCost && usage.cost.totalFromProvider === true;
+ const costStatus = billed ? "reported"
+ : provenance.costStatus ?? (validCost && usage.cost.total > 0 ? "estimated" : "unknown");
+ const cost = validCost && costStatus !== "unknown"
+ ? { input: usage.cost.input, output: usage.cost.output, cacheRead: usage.cost.cacheRead, cacheWrite: usage.cost.cacheWrite, total: usage.cost.total }
+ : undefined;
if (totalTokens <= 0 && inputTokens <= 0 && outputTokens <= 0 && !cost?.total) return undefined;
return {
inputTokens,
@@ -103,7 +110,7 @@ export function usageToPi(usage: MessageUsage | undefined): AccountedPiUsage {
...(usage?.reasoningTokens !== undefined ? { reasoning: usage.reasoningTokens } : {}),
totalTokens: usage?.totalTokens ?? input + output + cacheRead + cacheWrite,
cost: usage?.cost && usage.costStatus !== "unknown"
- ? { ...usage.cost }
+ ? { ...usage.cost, ...(usage.costStatus === "reported" ? { totalFromProvider: true } : {}) }
: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
// Explicitly tag the numeric placeholder so it can never become a known
// zero-dollar charge when reconstructed history crosses this boundary again.
diff --git a/packages/agent-runtime/src/background-job-tools.test.ts b/packages/agent-runtime/src/background-job-tools.test.ts
index cc48efde4..f23d530f3 100644
--- a/packages/agent-runtime/src/background-job-tools.test.ts
+++ b/packages/agent-runtime/src/background-job-tools.test.ts
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentTool } from "@earendil-works/pi-agent-core";
-import { Type } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { buildJobTools } from "./background-job-tools.js";
import type { RuntimeHost } from "./host-client.js";
diff --git a/packages/agent-runtime/src/background-job-tools.ts b/packages/agent-runtime/src/background-job-tools.ts
index dfe1c0ce5..5b26b5aa0 100644
--- a/packages/agent-runtime/src/background-job-tools.ts
+++ b/packages/agent-runtime/src/background-job-tools.ts
@@ -1,7 +1,7 @@
/** Model job controls route to their existing owner; only Bash crosses Host RPC. */
import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
import type { TObject } from "typebox";
-import { Type } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import {
BACKGROUND_JOBS_VERSION,
type BackgroundJobSnapshot,
diff --git a/packages/agent-runtime/src/extensions/managed-exec.test.ts b/packages/agent-runtime/src/extensions/managed-exec.test.ts
index b41a6beeb..95afdc87d 100644
--- a/packages/agent-runtime/src/extensions/managed-exec.test.ts
+++ b/packages/agent-runtime/src/extensions/managed-exec.test.ts
@@ -29,8 +29,46 @@ it("cancels an owned process tree after an explicit readiness signal", async ()
it("never starts an already-cancelled exec and keeps normal command output", async () => {
const owner = new AbortController();
expect(await managedExec(process.execPath, ["-e", "process.stdout.write('ok')"], tmpdir(), owner.signal))
- .toMatchObject({ stdout: "ok", code: 0, killed: false });
+ .toMatchObject({ stdout: "ok", code: 0, killed: false, truncated: false });
owner.abort();
expect(() => managedExec(process.execPath, ["-e", "process.exit(9)"], tmpdir(), owner.signal))
.toThrow();
});
+
+it("decodes a multi-byte character split across output chunks", async () => {
+ const owner = new AbortController();
+ // "中" is three UTF-8 bytes; write them as two separate chunks.
+ const source = "const b=Buffer.from('中文');process.stdout.write(b.subarray(0,1));setTimeout(()=>process.stdout.write(b.subarray(1)),50);";
+ expect(await managedExec(process.execPath, ["-e", source], tmpdir(), owner.signal))
+ .toMatchObject({ stdout: "中文", code: 0, killed: false, truncated: false });
+});
+
+it("terminates a command whose combined output exceeds maxBuffer and reports truncation", async () => {
+ const owner = new AbortController();
+ const source = "process.stderr.write('ee');setInterval(()=>process.stdout.write('x'.repeat(1024)),5);";
+ const result = await managedExec(process.execPath, ["-e", source], tmpdir(), owner.signal, { maxBuffer: 2048 });
+ expect(result.truncated).toBe(true);
+ expect(result.killed).toBe(true);
+ expect(result.code).not.toBe(0);
+ expect(Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr)).toBeLessThanOrEqual(2048);
+});
+
+it("drops an incomplete UTF-8 suffix at the truncation boundary", async () => {
+ const owner = new AbortController();
+ const source = "process.stdout.write(Buffer.from('aé'));setInterval(()=>{},1000);";
+ const result = await managedExec(process.execPath, ["-e", source], tmpdir(), owner.signal, { maxBuffer: 2 });
+ expect(result).toMatchObject({ stdout: "a", truncated: true });
+});
+
+it("resolves a missing executable as a failed command with the spawn error", async () => {
+ const owner = new AbortController();
+ const result = await managedExec("pi-desktop-missing-executable-e2e", [], tmpdir(), owner.signal);
+ expect(result.code).toBe(1);
+ expect(result.truncated).toBe(false);
+ expect(result.stderr).toContain("ENOENT");
+});
+
+it("rejects an invalid maxBuffer before spawning", () => {
+ const owner = new AbortController();
+ expect(() => managedExec(process.execPath, ["-e", ""], tmpdir(), owner.signal, { maxBuffer: -1 })).toThrow(RangeError);
+});
diff --git a/packages/agent-runtime/src/extensions/managed-exec.ts b/packages/agent-runtime/src/extensions/managed-exec.ts
index 471c0b549..abd33540f 100644
--- a/packages/agent-runtime/src/extensions/managed-exec.ts
+++ b/packages/agent-runtime/src/extensions/managed-exec.ts
@@ -1,11 +1,27 @@
+import { constants as bufferConstants } from "node:buffer";
import { spawn } from "node:child_process";
+import { StringDecoder } from "node:string_decoder";
import type { ExtensionExecOptions, ExtensionExecResult } from "./runner.js";
-/** Own the process group created through pi.exec; direct Node spawns are unowned. */
+/** Default combined stdout + stderr byte cap for pi.exec. */
+export const DEFAULT_EXTENSION_EXEC_MAX_BUFFER = 10 * 1024 * 1024;
+
+/**
+ * Own the process group created through pi.exec; direct Node spawns are unowned.
+ *
+ * Mirrors Pi 1.5 exec semantics: output is decoded across chunk boundaries,
+ * `maxBuffer` caps stdout and stderr combined in bytes and terminates the
+ * command on overflow with `truncated: true` and a nonzero code, and a command
+ * that cannot be spawned resolves with code 1 and the spawn error in stderr.
+ */
export function managedExec(command: string, args: string[], cwd: string,
owner: AbortSignal, options?: ExtensionExecOptions): Promise<ExtensionExecResult> {
const signal = options?.signal ? AbortSignal.any([owner, options.signal]) : owner;
signal.throwIfAborted();
+ const maxBuffer = options?.maxBuffer ?? DEFAULT_EXTENSION_EXEC_MAX_BUFFER;
+ if (!Number.isInteger(maxBuffer) || maxBuffer < 0 || maxBuffer > bufferConstants.MAX_STRING_LENGTH) {
+ throw new RangeError(`maxBuffer must be an integer between 0 and ${bufferConstants.MAX_STRING_LENGTH} bytes`);
+ }
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd: options?.cwd ?? cwd,
@@ -14,9 +30,13 @@ export function managedExec(command: string, args: string[], cwd: string,
detached: process.platform !== "win32",
windowsHide: true,
});
- const maxBuffer = options?.maxBuffer ?? 10 * 1024 * 1024;
let stdout = "";
let stderr = "";
+ const stdoutDecoder = new StringDecoder("utf8");
+ const stderrDecoder = new StringDecoder("utf8");
+ let outputBytes = 0;
+ let truncated = false;
+ let spawnError: Error | undefined;
let killed = false;
let settled = false;
let killTimer: ReturnType<typeof setTimeout> | undefined;
@@ -27,8 +47,19 @@ export function managedExec(command: string, args: string[], cwd: string,
clearTimeout(timeout);
clearTimeout(killTimer);
signal.removeEventListener("abort", kill);
- if (error) reject(error);
- else resolve({ stdout, stderr, code: code ?? (killed ? 143 : 0), killed });
+ if (error) {
+ reject(error);
+ return;
+ }
+ // An incomplete UTF-8 suffix of truncated output was never accepted; do not flush it.
+ if (!truncated) {
+ stdout += stdoutDecoder.end();
+ stderr += stderrDecoder.end();
+ }
+ if (spawnError && !stderr) stderr = spawnError.message;
+ const exitCode = code ?? (killed ? 143 : spawnError ? 1 : 0);
+ // A truncated result must never read as success.
+ resolve({ stdout, stderr, code: truncated && exitCode === 0 ? 1 : exitCode, killed, truncated });
};
const kill = () => {
if (killed || settled) return;
@@ -56,13 +87,34 @@ export function managedExec(command: string, args: string[], cwd: string,
signal.addEventListener("abort", kill, { once: true });
if (signal.aborted) kill();
if (options?.timeout) timeout = setTimeout(kill, options.timeout);
- child.stdout.on("data", (chunk: Buffer) => {
- stdout += chunk.toString("utf8").slice(0, Math.max(0, maxBuffer - stdout.length));
+ const takeWithinCap = (data: Buffer): Buffer | undefined => {
+ if (truncated) return undefined;
+ const remaining = maxBuffer - outputBytes;
+ if (data.length <= remaining) {
+ outputBytes += data.length;
+ return data;
+ }
+ truncated = true;
+ child.stdout.destroy();
+ child.stderr.destroy();
+ kill();
+ return remaining > 0 ? data.subarray(0, remaining) : undefined;
+ };
+ child.stdout.on("data", (data: Buffer) => {
+ const chunk = takeWithinCap(data);
+ if (chunk) stdout += stdoutDecoder.write(chunk);
+ });
+ child.stderr.on("data", (data: Buffer) => {
+ const chunk = takeWithinCap(data);
+ if (chunk) stderr += stderrDecoder.write(chunk);
});
- child.stderr.on("data", (chunk: Buffer) => {
- stderr += chunk.toString("utf8").slice(0, Math.max(0, maxBuffer - stderr.length));
+ child.once("error", (error) => {
+ // A spawn failure (missing executable, bad cwd) is a failed command, not a host fault.
+ if (!child.pid) {
+ spawnError = error;
+ finish(undefined, 1);
+ } else finish(error);
});
- child.once("error", (error) => finish(error));
child.once("close", (code) => finish(undefined, code));
});
}
diff --git a/packages/agent-runtime/src/extensions/runner.ts b/packages/agent-runtime/src/extensions/runner.ts
index c13544cd4..adab760ef 100644
--- a/packages/agent-runtime/src/extensions/runner.ts
+++ b/packages/agent-runtime/src/extensions/runner.ts
@@ -101,6 +101,8 @@ export type ExtensionExecResult = {
stderr: string;
code: number;
killed: boolean;
+ /** Output exceeded `maxBuffer`; stdout and stderr are incomplete and `code` is nonzero. */
+ truncated: boolean;
};
export type ExtensionToolInfo = { name: string; description: string; active: boolean };
diff --git a/packages/agent-runtime/src/fixed-tool-declarations.test.ts b/packages/agent-runtime/src/fixed-tool-declarations.test.ts
index 8b54969b9..13580c602 100644
--- a/packages/agent-runtime/src/fixed-tool-declarations.test.ts
+++ b/packages/agent-runtime/src/fixed-tool-declarations.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from "vitest";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import { DEEPSEEK_MODELS } from "@earendil-works/pi-ai/providers/deepseek.models";
-import { Type, type Api, type Model } from "@earendil-works/pi-ai";
+import { type Api, type Model } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { toolDeclarationPolicy, toolActivationSection, restoredToolActivation, TOOL_ACTIVATION_SECTION } from "./fixed-tool-declarations.js";
import { replaceSystemPrompt, systemTranscriptCheckpoint } from "./system-transcript.js";
diff --git a/packages/agent-runtime/src/fixed-tool-declarations.ts b/packages/agent-runtime/src/fixed-tool-declarations.ts
index 721f39663..aa0098a03 100644
--- a/packages/agent-runtime/src/fixed-tool-declarations.ts
+++ b/packages/agent-runtime/src/fixed-tool-declarations.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import type { AgentMessage, AgentTool } from "@earendil-works/pi-agent-core";
-import { getCurrentSystemMessage, toToolDeclaration, Type, type Api, type Model } from "@earendil-works/pi-ai";
+import { getCurrentSystemMessage, toToolDeclaration, type Api, type Model } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import * as Value from "typebox/value";
import { contextBudgetLimitsFor, automaticCompactionThresholdFor } from "./context-budget.js";
import { estimateOutputCapInputTokens } from "./output-cap.js";
diff --git a/packages/agent-runtime/src/image-generation/tool.ts b/packages/agent-runtime/src/image-generation/tool.ts
index 07b36d6bd..29c537a47 100644
--- a/packages/agent-runtime/src/image-generation/tool.ts
+++ b/packages/agent-runtime/src/image-generation/tool.ts
@@ -1,4 +1,4 @@
-import { Type } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
export const imageGenerationDescription =
"Generate raster images using the image model configured in Settings > Models. items supports distinct prompts and count variants; at most 10 images total. Each image may incur a charge. Generate only the requested number, report partial failures, and do not retry without the user's request. Results contain local image paths: display successful images with Markdown image links. For edits, provide images as local paths from the session, attachments, or project. Use previous result paths to refine generated images; preserve originals.";
diff --git a/packages/agent-runtime/src/native-pi-session.test.ts b/packages/agent-runtime/src/native-pi-session.test.ts
index 91425cfff..93a641407 100644
--- a/packages/agent-runtime/src/native-pi-session.test.ts
+++ b/packages/agent-runtime/src/native-pi-session.test.ts
@@ -3,7 +3,8 @@ import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AgentSession, ModelRuntime, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent";
-import { createAssistantMessageEventStream, PI_ATTRIBUTION, Type, type AssistantMessage } from "@earendil-works/pi-ai";
+import { createAssistantMessageEventStream, PI_ATTRIBUTION, type AssistantMessage } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { NativePiSessionService } from "./native-pi-session.js";
import {
acquireNativePiSessionLease,
@@ -504,7 +505,7 @@ function fauxModelRuntime() {
}
describe("native continuation review regressions", () => {
- it.each([true, false])("uses the native SDK telemetry preference for 1.4 attribution (%s)", async (enabled) => {
+ it.each([true, false])("uses the native SDK telemetry preference for 1.5 attribution (%s)", async (enabled) => {
const f = await configuredFixture();
const settingsPath = join(f.agentDir, "settings.json");
const settings = JSON.parse(readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
@@ -523,7 +524,7 @@ describe("native continuation review regressions", () => {
expect(identities).toHaveLength(1);
expect(identities[0]).toMatchObject({
userAgent: "detailed",
- version: "1.4.0",
+ version: "1.5.0",
attribution: enabled ? PI_ATTRIBUTION : null,
});
} finally {
diff --git a/packages/agent-runtime/src/pi-1.4-adapter-features.test.ts b/packages/agent-runtime/src/pi-1.5-adapter-features.test.ts
similarity index 99%
rename from packages/agent-runtime/src/pi-1.4-adapter-features.test.ts
rename to packages/agent-runtime/src/pi-1.5-adapter-features.test.ts
index 54771f1da..2f175978e 100644
--- a/packages/agent-runtime/src/pi-1.4-adapter-features.test.ts
+++ b/packages/agent-runtime/src/pi-1.5-adapter-features.test.ts
@@ -50,7 +50,7 @@ const usage: AssistantMessage["usage"] = {
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
};
-describe("Pi 1.4 adapters through Desktop provider binding", () => {
+describe("Pi 1.5 adapters through Desktop provider binding", () => {
it.each(["claude-haiku-5-5", "claude-opus-5"] as const)("disables thinking without effort markers while preserving hosted search: %s", async (id) => {
const payload = await anthropicRequest(anthropic(id), [{ role: "user", content: "Hello", timestamp: 1 }]);
expect(payload.thinking).toEqual({ type: "disabled" });
diff --git a/packages/agent-runtime/src/pi-anthropic-strict-fallback.test.ts b/packages/agent-runtime/src/pi-anthropic-strict-fallback.test.ts
index 26e478439..c6b673cfc 100644
--- a/packages/agent-runtime/src/pi-anthropic-strict-fallback.test.ts
+++ b/packages/agent-runtime/src/pi-anthropic-strict-fallback.test.ts
@@ -1,4 +1,5 @@
-import { normalizeContext, Type, type Message, type Model } from "@earendil-works/pi-ai";
+import { normalizeContext, type Message, type Model } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { stream } from "@earendil-works/pi-ai/api/anthropic-messages";
import { describe, expect, it } from "vitest";
diff --git a/packages/agent-runtime/src/pi-upstream-1.4-contract.test.ts b/packages/agent-runtime/src/pi-upstream-1.5-contract.test.ts
similarity index 96%
rename from packages/agent-runtime/src/pi-upstream-1.4-contract.test.ts
rename to packages/agent-runtime/src/pi-upstream-1.5-contract.test.ts
index 8e7594c8d..4ee95301c 100644
--- a/packages/agent-runtime/src/pi-upstream-1.4-contract.test.ts
+++ b/packages/agent-runtime/src/pi-upstream-1.5-contract.test.ts
@@ -26,7 +26,7 @@ function fixture() {
const executions: unknown[] = [];
const requests: Request[] = [];
const runtime = new DesktopAgentRuntime({
- sessionId: "pi-1.4-fixture", mode: "agent", thinkingLevel: "off",
+ sessionId: "pi-1.5-fixture", mode: "agent", thinkingLevel: "off",
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
provider: {
id: "fixture", name: "Fixture", modelId: "fixture", apiKey: "fixture",
@@ -57,7 +57,7 @@ function fixture() {
return { runtime, executions, requests, respond, agent };
}
-describe("Pi 1.4 tool-call contracts through Desktop", () => {
+describe("Pi 1.5 tool-call contracts through Desktop", () => {
it("rejects malformed final JSON before Host execution and accepts a corrected call", async () => {
const { runtime, executions, requests, respond, agent } = fixture();
const malformed = '{"path":"wrong.txt","content":"partial",';
diff --git a/packages/agent-runtime/src/pi-upstream-1.4-identity.test.ts b/packages/agent-runtime/src/pi-upstream-1.5-identity.test.ts
similarity index 89%
rename from packages/agent-runtime/src/pi-upstream-1.4-identity.test.ts
rename to packages/agent-runtime/src/pi-upstream-1.5-identity.test.ts
index 4e334116a..78d791d78 100644
--- a/packages/agent-runtime/src/pi-upstream-1.4-identity.test.ts
+++ b/packages/agent-runtime/src/pi-upstream-1.5-identity.test.ts
@@ -7,7 +7,7 @@ import {
import { describe, expect, it } from "vitest";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
-describe("Pi 1.4 client identity", () => {
+describe("Pi 1.5 client identity", () => {
it("clears agent-core attribution while retaining pi-ai's detailed User-Agent", () => {
const identity = mergeClientIdentity(
{ attribution: PI_ATTRIBUTION },
@@ -15,7 +15,7 @@ describe("Pi 1.4 client identity", () => {
);
expect(identity?.attribution).toBeNull();
- expect(formatUserAgent(identity)).toMatch(/^pi\/1\.4\.0 \(/);
+ expect(formatUserAgent(identity)).toMatch(/^pi\/1\.5\.0 \(/);
for (const target of [
{ provider: "openrouter", baseUrl: "https://openrouter.ai/api/v1" },
{ provider: "nvidia", baseUrl: "https://integrate.api.nvidia.com/v1" },
diff --git a/packages/agent-runtime/src/provider-retry.test.ts b/packages/agent-runtime/src/provider-retry.test.ts
index bcd5adb53..7c276caef 100644
--- a/packages/agent-runtime/src/provider-retry.test.ts
+++ b/packages/agent-runtime/src/provider-retry.test.ts
@@ -477,6 +477,28 @@ describe("provider rate-limit retry", () => {
expect(events).toEqual(["error"]);
});
+ it("does not replay a Zhipu 1308 usage-limit 429 through the rate-limit budget", async () => {
+ const claim = vi.fn(() => undefined);
+ const sleep = vi.fn(async () => undefined);
+ const createStream = vi.fn(() => failedStream({
+ errorMessage: '429 {"error":{"code":"1308","message":"Usage limit reached for 5 hour."}}',
+ }));
+ const stream = createProviderRetryStream(model, context, {}, createStream, {
+ claim, sleep, headers: () => undefined, status: () => 429,
+ });
+
+ const events: string[] = [];
+ for await (const event of stream) events.push(event.type);
+
+ expect(createStream).toHaveBeenCalledTimes(1);
+ expect(sleep).not.toHaveBeenCalled();
+ expect(claim).toHaveBeenCalledWith(
+ expect.objectContaining({ code: "PROVIDER_ERROR", retriable: false }),
+ "request",
+ );
+ expect(events).toEqual(["error"]);
+ });
+
it("clears a captured 429 before a fetch fails without a response", async () => {
let calls = 0;
let snapshot: { status: number; headers: Record<string, string> } | undefined;
diff --git a/packages/agent-runtime/src/request-usage.test.ts b/packages/agent-runtime/src/request-usage.test.ts
index b0ad96e1a..edd1696f0 100644
--- a/packages/agent-runtime/src/request-usage.test.ts
+++ b/packages/agent-runtime/src/request-usage.test.ts
@@ -62,3 +62,48 @@ it("does not turn unknown native rates into a zero-dollar request", async () =>
}, { costStatus: "estimated", nativeCost: { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN } });
expect(usageFromPi((await stream.result()).usage)?.costStatus).toBe("unknown");
});
+
+describe("provider-billed cost (Pi 1.5 totalFromProvider)", () => {
+ function billed(totalFromProvider: boolean | undefined): AssistantMessage {
+ const message = response();
+ message.usage.cost = { input: 0.001, output: 0.002, cacheRead: 0, cacheWrite: 0, total: 0.0042,
+ ...(totalFromProvider === undefined ? {} : { totalFromProvider }) };
+ return message;
+ }
+ function run(message: AssistantMessage, options: Parameters<typeof accountModelStream>[2] = {}) {
+ const reports: MessageUsage[] = [];
+ const stream = accountModelStream({ id: "openrouter/model", provider: "openrouter" }, () => {
+ const inner = createAssistantMessageEventStream();
+ inner.push({ type: "done", reason: "stop", message }); inner.end(); return inner;
+ }, { ...options, onUsage: (usage) => reports.push(usage) });
+ return { stream, reports };
+ }
+
+ it("records a provider-billed total as reported, even when catalog rates are unknown", async () => {
+ const { stream, reports } = run(billed(true), {
+ costStatus: "estimated", nativeCost: { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN },
+ });
+ const result = await stream.result();
+ expect(reports[0]).toMatchObject({ costStatus: "reported", cost: { total: 0.0042 } });
+ // The persisted cost keeps the five numeric fields only.
+ expect(Object.keys(reports[0]?.cost ?? {}).sort()).toEqual(["cacheRead", "cacheWrite", "input", "output", "total"]);
+ // Replaying history back into Pi keeps the billed marker.
+ expect(result.usage.cost.totalFromProvider).toBe(true);
+ expect(usageFromPi(result.usage)?.costStatus).toBe("reported");
+ });
+
+ it.each([false, undefined])("keeps a catalog total (totalFromProvider=%s) estimated", async (flag) => {
+ const { stream, reports } = run(billed(flag), { nativeCost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 } });
+ const result = await stream.result();
+ expect(reports[0]).toMatchObject({ costStatus: "estimated", cost: { total: 0.0042 } });
+ expect(result.usage.cost.totalFromProvider).toBeUndefined();
+ });
+
+ it("marks a combined total reported only when every part was billed", async () => {
+ const a = run(billed(true)); await a.stream.result();
+ const b = run(billed(false), { nativeCost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 } }); await b.stream.result();
+ const c = run(billed(true)); await c.stream.result();
+ expect(addUsage(a.reports[0], b.reports[0])?.costStatus).toBe("estimated");
+ expect(addUsage(a.reports[0], c.reports[0])?.costStatus).toBe("reported");
+ });
+});
diff --git a/packages/agent-runtime/src/response-model.test.ts b/packages/agent-runtime/src/response-model.test.ts
new file mode 100644
index 000000000..1148c301b
--- /dev/null
+++ b/packages/agent-runtime/src/response-model.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { concreteResponseModel } from "./response-model.js";
+
+describe("concreteResponseModel", () => {
+ it.each([
+ ["openrouter/auto", "anthropic/claude-sonnet-4.5", "anthropic/claude-sonnet-4.5"],
+ ["claude-opus-4-1", "claude-sonnet-4-5", "claude-sonnet-4-5"],
+ ["virtual-fast", " vendor/model-a ", "vendor/model-a"],
+ ])("keeps a different served model (%s -> %s)", (requested, served, expected) => {
+ expect(concreteResponseModel({ responseModel: served }, requested)).toBe(expected);
+ });
+
+ it.each([
+ ["gpt-4o", "gpt-4o"],
+ ["gpt-4o", "gpt-4o-2024-08-06"],
+ ["claude-sonnet-4-5", "claude-sonnet-4-5-20250929"],
+ ["m", ""],
+ ["m", "x".repeat(201)],
+ ["m", "evil\u001b]8;;http://x\u0007"],
+ ["m", "a\u0085b"],
+ ])("drops a redundant or unsafe value (%s / %j)", (requested, served) => {
+ expect(concreteResponseModel({ responseModel: served }, requested)).toBeUndefined();
+ });
+
+ it("ignores a missing or non-string value", () => {
+ expect(concreteResponseModel({}, "m")).toBeUndefined();
+ expect(concreteResponseModel({ responseModel: 42 }, "m")).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/response-model.ts b/packages/agent-runtime/src/response-model.ts
new file mode 100644
index 000000000..6a921076b
--- /dev/null
+++ b/packages/agent-runtime/src/response-model.ts
@@ -0,0 +1,32 @@
+/** Bound for a provider-reported model id shown in the transcript. */
+const MAX_RESPONSE_MODEL_LENGTH = 200;
+
+/** A dated snapshot of the requested id (`gpt-4o-2024-08-06`, `claude-x-20250101`). */
+const DATED_SNAPSHOT_SUFFIX = /^-\d{4}-?\d{2}-?\d{2}$/;
+
+/**
+ * The concrete model a provider reports serving a response (Pi 1.5
+ * `AssistantMessage.responseModel`), kept only when it tells the user
+ * something the requested id does not: a router, virtual, or fallback model
+ * that resolved to a different model. The value is provider-controlled text,
+ * so it is bounded and must be printable.
+ */
+export function concreteResponseModel(
+ message: { responseModel?: unknown },
+ requestedModelId: string,
+): string | undefined {
+ const raw = message.responseModel;
+ if (typeof raw !== "string") return undefined;
+ const responseModel = raw.trim();
+ if (!responseModel || responseModel.length > MAX_RESPONSE_MODEL_LENGTH) return undefined;
+ // Control characters (C0, DEL, C1) never belong in a model id.
+ if (/[\u0000-\u001f\u007f-\u009f]/.test(responseModel)) return undefined;
+ if (responseModel === requestedModelId) return undefined;
+ if (
+ responseModel.startsWith(requestedModelId) &&
+ DATED_SNAPSHOT_SUFFIX.test(responseModel.slice(requestedModelId.length))
+ ) {
+ return undefined;
+ }
+ return responseModel;
+}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index d374f6bf3..32e9e4e2c 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -7441,6 +7441,31 @@ describe("DesktopAgentRuntime response duration", () => {
}
});
+ it.each([
+ ["router/auto", "vendor/served-model", "vendor/served-model"],
+ ["router/auto", undefined, undefined],
+ ])("records the concrete served model on the finished turn (%s -> %s)", async (requested, served, expected) => {
+ const onEvent = vi.fn();
+ const runtime = createRuntime({ onEvent });
+ const internals = runtime as unknown as {
+ handleAgentEvent(event: unknown): Promise<void>;
+ provider: { modelId: string };
+ };
+ internals.provider = { ...internals.provider, modelId: requested };
+ await internals.handleAgentEvent({ type: "message_start", message: { role: "assistant", content: [] } });
+ await internals.handleAgentEvent({
+ type: "message_end",
+ message: { ...assistantMessage({ content: [{ type: "text", text: "answer" }] }), ...(served ? { responseModel: served } : {}) },
+ });
+ const terminal = onEvent.mock.calls
+ .map(([envelope]) => envelope as any)
+ .find(({ event }) => event.type === "message_end")?.event.message;
+ expect(terminal).toMatchObject({ modelId: requested, status: "complete" });
+ if (expected) expect(terminal.responseModelId).toBe(expected);
+ else expect(terminal).not.toHaveProperty("responseModelId");
+ await runtime.dispose();
+ });
+
it("accumulates request and stream timing across a provider retry", async () => {
vi.useFakeTimers();
try {
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 980c844c0..5cc1e776d 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -6,6 +6,7 @@ import {
} from "./mutation-recovery.js";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
import { resolveMcpToolSelection } from "./mcp-tool-selection.js";
+import { concreteResponseModel } from "./response-model.js";
import { BatchPlanner, withBatchTurn } from "./batch-planner.js";
import { TOOL_EXECUTION_SPECS, resolveBatchExecutionMode, toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";
import { AsyncLocalStorage } from "node:async_hooks";
@@ -51,7 +52,6 @@ import {
getCurrentTools,
getToolStateChanges,
toToolDeclaration,
- Type,
type Api,
type AssistantMessage,
type ImageContent,
@@ -62,6 +62,7 @@ import {
type Usage,
type UserMessage,
} from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import {
DEFAULT_COMMAND_TIMEOUT_MS,
OAUTH_AUTH_KIND,
@@ -8804,6 +8805,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
: "complete",
modelId: this.provider.modelId,
providerId: this.provider.id,
+ responseModelId: concreteResponseModel(event.message, this.provider.modelId),
...(usage ? { usage } : {}),
...(responseDurationMs !== undefined ? { responseDurationMs } : {}),
...(streamMs !== undefined ? { modelStreamDurationMs } : {}),
@@ -8826,6 +8828,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
),
};
if (!this.currentAssistant.providerReplay) delete this.currentAssistant.providerReplay;
+ if (!this.currentAssistant.responseModelId) delete this.currentAssistant.responseModelId;
this.emit({ type: "message_end", message: this.currentAssistant });
this.activeProviderRetryAttempt = 0;
this.streamStartedAt = undefined;
diff --git a/packages/agent-runtime/src/scheduled-tools.ts b/packages/agent-runtime/src/scheduled-tools.ts
index 32cefc676..676f59dcf 100644
--- a/packages/agent-runtime/src/scheduled-tools.ts
+++ b/packages/agent-runtime/src/scheduled-tools.ts
@@ -1,4 +1,4 @@
-import { Type } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
const schedule = Type.Object({
hour: Type.Integer({ minimum: 0, maximum: 23 }),
diff --git a/packages/agent-runtime/src/system-transcript-journal.test.ts b/packages/agent-runtime/src/system-transcript-journal.test.ts
index 443a035e5..267fe7347 100644
--- a/packages/agent-runtime/src/system-transcript-journal.test.ts
+++ b/packages/agent-runtime/src/system-transcript-journal.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, it, vi } from "vitest";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { MessageEntry, CompactionEntry } from "./pi-runtime-types.js";
import type { UiMessage } from "@pi-desktop/shared";
-import { getCurrentTools, Type, type SystemMessage } from "@earendil-works/pi-ai";
+import { getCurrentTools, type SystemMessage } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { orderSystemRows, readSystemMessage, SystemTranscriptJournal } from "./system-transcript-journal.js";
import { buildSessionContext } from "./session-context.js";
import { CONTEXT_BUDGET_SECTION, syncSystemSections, systemTranscriptCheckpoint } from "./system-transcript.js";
diff --git a/packages/agent-runtime/src/system-transcript-journal.ts b/packages/agent-runtime/src/system-transcript-journal.ts
index d7948778a..72f5c0cc1 100644
--- a/packages/agent-runtime/src/system-transcript-journal.ts
+++ b/packages/agent-runtime/src/system-transcript-journal.ts
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
-import { LocalRequestError, Type, contentText, toToolDeclaration, type SystemMessage } from "@earendil-works/pi-ai";
+import { LocalRequestError, contentText, toToolDeclaration, type SystemMessage } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { MessageEntry } from "./pi-runtime-types.js";
import type { UiMessage } from "@pi-desktop/shared";
diff --git a/packages/agent-runtime/src/system-transcript-order.test.ts b/packages/agent-runtime/src/system-transcript-order.test.ts
index 65e127c11..28296feb2 100644
--- a/packages/agent-runtime/src/system-transcript-order.test.ts
+++ b/packages/agent-runtime/src/system-transcript-order.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { Agent, type AgentTool, type AgentMessage } from "@earendil-works/pi-agent-core";
-import { createAssistantMessageEventStream, Type, getCurrentTools, type SystemMessage } from "@earendil-works/pi-ai";
+import { createAssistantMessageEventStream, getCurrentTools, type SystemMessage } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { rebuildSystemTranscript } from "./system-transcript.js";
const read = { name: "Read", description: "Read a file", parameters: Type.Object({}) };
diff --git a/packages/agent-runtime/src/system-transcript.test.ts b/packages/agent-runtime/src/system-transcript.test.ts
index f83ad2f9f..354ee1251 100644
--- a/packages/agent-runtime/src/system-transcript.test.ts
+++ b/packages/agent-runtime/src/system-transcript.test.ts
@@ -6,11 +6,11 @@ import {
getCurrentSystemPrompt,
getCurrentTools,
toToolDeclaration,
- Type,
type AssistantMessage,
type SystemMessage,
type Tool,
} from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { estimateContextTokens as estimateTranscriptTokens } from "@earendil-works/pi-ai/utils/estimate";
import { convertToLlm } from "./pi-runtime-messages.js";
import {
diff --git a/packages/agent-runtime/src/todo-tool.ts b/packages/agent-runtime/src/todo-tool.ts
index 3ed19fa6d..83e416aff 100644
--- a/packages/agent-runtime/src/todo-tool.ts
+++ b/packages/agent-runtime/src/todo-tool.ts
@@ -1,4 +1,4 @@
-import { Type } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
export const todoWriteDescription =
"Write the task checklist for the current session so the user can see progress on multi-step work. Use for work that needs 3+ distinct steps or spans multiple files/subsystems; do not use for a single-step action, a question, a read, or a review. Every call replaces the full list in display order. States are pending, in_progress, completed, and cancelled; only one item may be in_progress. Keep items short and concrete, update the list as work starts and finishes, and never leave pending items when the task is done. Content longer than 500 Unicode characters is truncated by the host with a warning.";
diff --git a/packages/agent-runtime/src/transcript-payload.test.ts b/packages/agent-runtime/src/transcript-payload.test.ts
index 0cd77f8b2..9f7a45ffd 100644
--- a/packages/agent-runtime/src/transcript-payload.test.ts
+++ b/packages/agent-runtime/src/transcript-payload.test.ts
@@ -1,5 +1,6 @@
import { expect, it } from "vitest";
-import { normalizeContext, Type, type Message, type Model } from "@earendil-works/pi-ai";
+import { normalizeContext, type Message, type Model } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
import { stream } from "@earendil-works/pi-ai/api/openai-completions";
import { genericModelConfig } from "./model-capabilities.js";
import { buildProviderModel } from "./provider-binding.js";
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 1c2459eac..c3a1cf306 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -460,6 +460,7 @@ export const de = {
"copyErrorDetails": "Details kopieren",
"errorProvider": "KI-Anbieter",
"errorModel": "Modell",
+ "servedByModel": "Angefordert: {{requested}}; ausgeführt von {{served}}",
"previewFile": "Vorschau im Seitenbereich",
"fileRefMissing": "Keine Datei entspricht {{name}}",
"fileRefRestricted": "{{name}} liegt außerhalb der für die App zugänglichen Orte",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 1991b3d83..c97404057 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -475,6 +475,7 @@ export const en = {
actionSlotMore: "More actions",
errorProvider: "AI provider",
errorModel: "Model",
+ servedByModel: "Requested {{requested}}; served by {{served}}",
previewFile: "Preview in the side panel",
fileRefMissing: "No file matches {{name}}",
fileRefRestricted: "{{name}} is outside the locations this app can access",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index c5f0cc44b..522d6719d 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -460,6 +460,7 @@ export const es = {
"copyErrorDetails": "Copiar detalles",
"errorProvider": "Proveedor de IA",
"errorModel": "Modelo",
+ "servedByModel": "Solicitado: {{requested}}; atendido por {{served}}",
"previewFile": "Vista previa en el panel lateral",
"fileRefMissing": "Ningún archivo coincide con {{name}}",
"fileRefRestricted": "{{name}} está fuera de las ubicaciones a las que puede acceder la aplicación",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index fa0a5bf7c..bd4faf4a7 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -460,6 +460,7 @@ export const fr = {
"copyErrorDetails": "Copier les détails",
"errorProvider": "Fournisseur d'IA",
"errorModel": "Modèle",
+ "servedByModel": "Demandé : {{requested}} ; servi par {{served}}",
"previewFile": "Aperçu dans le panneau latéral",
"fileRefMissing": "Aucun fichier ne correspond à {{name}}",
"fileRefRestricted": "{{name}} se trouve hors des emplacements accessibles à l'application",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 827328e22..d92a183a6 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -472,6 +472,7 @@ export const ko = {
copyErrorDetails: "세부 정보 복사",
errorProvider: "AI 프로바이더",
errorModel: "모델",
+ servedByModel: "요청: {{requested}}; 실제 응답 모델: {{served}}",
previewFile: "사이드 패널에서 미리 보기",
fileRefMissing: "{{name}}과(와) 일치하는 파일이 없습니다",
fileRefRestricted: "{{name}}은(는) 앱이 접근할 수 있는 위치 밖에 있습니다",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 5571859e5..c7e53dfae 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -462,6 +462,7 @@ export const ptBR = {
actionSlotMore: "Mais ações",
errorProvider: "Provedor de IA",
errorModel: "Modelo",
+ servedByModel: "Solicitado: {{requested}}; atendido por {{served}}",
previewFile: "Pré-visualizar no painel lateral",
fileRefMissing: "Nenhum arquivo corresponde a {{name}}",
fileRefRestricted: "{{name}} está fora dos locais que o aplicativo pode acessar",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 17e9cd2c5..8f33e7d89 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -472,6 +472,7 @@ export const tr = {
copyErrorDetails: "Ayrıntıları kopyala",
errorProvider: "AI servisi",
errorModel: "Model",
+ servedByModel: "İstenen: {{requested}}; yanıtlayan: {{served}}",
previewFile: "Yan panelde önizle",
fileRefMissing: "{{name}} ile eşleşen dosya yok",
fileRefRestricted: "{{name}} uygulamanın erişebildiği konumların dışında",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 027aff523..1af0de723 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -465,6 +465,7 @@ export const zhCN = {
copyErrorDetails: "复制详情",
errorProvider: "AI 服务",
errorModel: "模型",
+ servedByModel: "请求 {{requested}},实际由 {{served}} 响应",
previewFile: "在侧边面板预览",
fileRefMissing: "没有匹配 {{name}} 的文件",
fileRefRestricted: "{{name}} 不在应用允许访问的范围内",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 01aa77fe0..1a8f0b34e 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -465,6 +465,7 @@ export const zhTW = {
copyErrorDetails: "複製詳情",
errorProvider: "AI 服務",
errorModel: "模型",
+ servedByModel: "請求 {{requested}},實際由 {{served}} 回應",
previewFile: "在側邊面板預覽",
fileRefMissing: "沒有匹配 {{name}} 的檔案",
fileRefRestricted: "{{name}} 不在應用程式允許存取的範圍內",
diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.ts
index 5a25639df..ca57153f6 100644
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@ -115,6 +115,11 @@ export type UiMessage = {
/** Provider/model that produced this assistant turn, when known. */
modelId?: string;
providerId?: string;
+ /**
+ * Concrete model the provider reports serving this turn, present only when
+ * it differs from `modelId` (for example a router or fallback model).
+ */
+ responseModelId?: string;
/** Token usage for the assistant turn, when the provider reported it. */
usage?: MessageUsage;
/** Elapsed assistant response duration used to calculate output throughput. */
diff --git a/patches/@[email protected] b/patches/@[email protected]
similarity index 100%
rename from patches/@[email protected]
rename to patches/@[email protected]
diff --git a/patches/@[email protected] b/patches/@[email protected]
similarity index 88%
rename from patches/@[email protected]
rename to patches/@[email protected]
index c12f0c691..05e7c6013 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -1,5 +1,5 @@
diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js
-index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f5627094f309a3 100644
+index de2b2d8c209f5576c18b020de297d4ef5fad5960..037ecdaea6efcb76f827ba2dd69bc3a09a3d78f7 100644
--- a/dist/api/anthropic-messages.js
+++ b/dist/api/anthropic-messages.js
@@ -1,3 +1,6 @@
@@ -9,7 +9,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
import Anthropic, {} from "@anthropic-ai/sdk";
import { ANTHROPIC_FEDERATION_RULE_ID_ENV, ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, ANTHROPIC_ORGANIZATION_ID_ENV, ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, ANTHROPIC_WORKSPACE_ID_ENV, } from "../env-api-keys.js";
import { calculateCost } from "../models.js";
-@@ -375,8 +378,6 @@ async function* iterateAnthropicEvents(response, signal) {
+@@ -377,8 +380,6 @@ async function* iterateAnthropicEvents(response, signal) {
}
export const stream = (model, context, options) => {
const stream = new AssistantMessageEventStream();
@@ -18,7 +18,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
(async () => {
const output = {
role: "assistant",
-@@ -395,7 +396,11 @@ export const stream = (model, context, options) => {
+@@ -397,7 +398,11 @@ export const stream = (model, context, options) => {
stopReason: "pending",
timestamp: Date.now(),
};
@@ -30,7 +30,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
let client;
let isOAuth;
let usageModel = model;
-@@ -431,6 +436,7 @@ export const stream = (model, context, options) => {
+@@ -433,6 +438,7 @@ export const stream = (model, context, options) => {
let disablePreferredStrictTools = false;
let response;
for (;;) {
@@ -38,7 +38,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
options?.signal?.throwIfAborted();
const built = buildParams(model, normalizedContext, isOAuth, options, disablePreferredStrictTools);
if (built.providerThinkingLevel)
-@@ -440,6 +446,8 @@ export const stream = (model, context, options) => {
+@@ -442,6 +448,8 @@ export const stream = (model, context, options) => {
if (nextParams !== undefined) {
params = { ...nextParams, stream: true };
}
@@ -47,8 +47,8 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
try {
response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {
maxRetries: options?.maxRetries,
-@@ -552,17 +560,50 @@ export const stream = (model, context, options) => {
- output.content.push(block);
+@@ -550,38 +558,83 @@ export const stream = (model, context, options) => {
+ });
stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
}
+ // Hosted web search (PI-Desktop): server-side search blocks
@@ -57,73 +57,69 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
+ // the hostedSearch block so multi-turn conversations keep
+ // their grounding (encrypted content included).
+ else if (event.content_block.type === "server_tool_use") {
-+ const block = {
++ output.content.push({
+ 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);
++ });
++ openBlocks.set(event.index, {
++ contentIndex: output.content.length - 1,
++ arguments: new ToolCallArgumentsStream(),
++ });
+ 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 = {
++ output.content.push({
+ 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);
++ });
++ openBlocks.set(event.index, { contentIndex: output.content.length - 1 });
+ stream.push({ type: "hosted_search_update", contentIndex: output.content.length - 1, partial: output });
+ }
}
else if (event.type === "content_block_delta") {
+ const open = openBlock(event.index);
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 ?? "";
+ if (open?.block.type === "text") {
+- open.block.text += event.delta.text;
++ open.block.text += event.delta.text ?? "";
stream.push({
type: "text_delta",
- contentIndex: index,
+ contentIndex: open.contentIndex,
- delta: event.delta.text,
+ delta: event.delta.text ?? "",
partial: output,
});
}
-@@ -571,11 +612,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 ?? "";
+ }
+ else if (event.delta.type === "thinking_delta") {
+ if (open?.block.type === "thinking") {
+- open.block.thinking += event.delta.thinking;
++ open.block.thinking += event.delta.thinking ?? "";
stream.push({
type: "thinking_delta",
- contentIndex: index,
+ contentIndex: open.contentIndex,
- delta: event.delta.thinking,
+ delta: event.delta.thinking ?? "",
partial: output,
});
}
-@@ -584,12 +625,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);
+ }
+ else if (event.delta.type === "input_json_delta") {
+ if (open?.block.type === "toolCall" && open.arguments !== undefined) {
+- open.block.arguments = open.arguments.append(event.delta.partial_json);
++ open.block.arguments = open.arguments.append(event.delta.partial_json ?? "");
stream.push({
type: "toolcall_delta",
- contentIndex: index,
+ contentIndex: open.contentIndex,
- delta: event.delta.partial_json,
+ delta: event.delta.partial_json ?? "",
+ partial: output,
@@ -132,21 +128,21 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
+ // 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);
++ else if (open?.block.type === "hostedSearch" && open.block.phase === "server_tool_use" &&
++ open.arguments !== undefined) {
++ open.block.input = open.arguments.append(event.delta.partial_json ?? "");
+ stream.push({
+ type: "hosted_search_update",
-+ contentIndex: index,
++ contentIndex: open.contentIndex,
partial: output,
});
}
-@@ -599,7 +652,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 ?? "";
+@@ -589,7 +642,19 @@ export const stream = (model, context, options) => {
+ else if (event.delta.type === "signature_delta") {
+ if (open?.block.type === "thinking") {
+ open.block.thinkingSignature = open.block.thinkingSignature || "";
+- open.block.thinkingSignature += event.delta.signature;
++ open.block.thinkingSignature += event.delta.signature ?? "";
+ }
+ }
+ // Hosted web search (PI-Desktop): citations arrive as deltas
@@ -162,20 +158,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
}
}
}
-@@ -636,6 +701,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") {
-@@ -708,13 +779,18 @@ export const stream = (model, context, options) => {
+@@ -700,8 +765,13 @@ export const stream = (model, context, options) => {
stream.end();
}
catch (error) {
@@ -184,18 +167,13 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
+ 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();
}
-@@ -742,7 +818,7 @@ function mapThinkingLevelToEffort(model, level) {
+@@ -729,7 +799,7 @@ function mapThinkingLevelToEffort(model, level) {
return "high";
}
}
@@ -204,7 +182,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
if (!getAnthropicFederation(model, options?.apiKey, options?.headers, options?.env)) {
assertRequestAuth(model.provider, options?.apiKey, options?.headers);
}
-@@ -776,7 +852,7 @@ export const streamSimple = (model, context, options) => {
+@@ -763,7 +833,7 @@ export const streamSimple = (model, context, options) => {
thinkingEnabled: true,
thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),
});
@@ -213,7 +191,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
function isOAuthToken(apiKey) {
return apiKey.includes("sk-ant-oat");
}
-@@ -972,6 +1048,15 @@ function buildParams(model, context, isOAuthToken, options, disablePreferredStri
+@@ -956,6 +1026,15 @@ function buildParams(model, context, isOAuthToken, options, disablePreferredStri
params.tools = convertToolDefinitions(tools, toolCacheControl);
}
}
@@ -229,7 +207,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
if (thinkingDisabled) {
// No effort is sent, so the model default applies. Anthropic rejects `block_binding`
// with disabled thinking.
-@@ -1173,6 +1258,15 @@ convertToolDefinitions) {
+@@ -1161,6 +1240,15 @@ convertToolDefinitions) {
input: block.arguments ?? {},
});
}
@@ -246,7 +224,7 @@ index 841da8964d2b403c45a18d4d1735c1fabc441a9a..02f20bdcd2c1d294754ca05579f56270
if (blocks.length === 0)
continue;
diff --git a/dist/api/azure-openai-responses.js b/dist/api/azure-openai-responses.js
-index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd1975c2e18a9 100644
+index e6a50f20ab31a3f3de0d2a71190dd98b6f1d401d..8620aa5ecb7cd7c4220347792e6e119408e3a497 100644
--- a/dist/api/azure-openai-responses.js
+++ b/dist/api/azure-openai-responses.js
@@ -1,3 +1,5 @@
@@ -286,7 +264,7 @@ index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd197
const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
maxRetries: options?.maxRetries,
maxRetryDelayMs: options?.maxRetryDelayMs,
-@@ -85,6 +90,11 @@ export const stream = (model, context, options) => {
+@@ -85,15 +90,20 @@ export const stream = (model, context, options) => {
stream.end();
}
catch (error) {
@@ -295,12 +273,6 @@ index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd197
+ 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.
-@@ -92,14 +102,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);
@@ -315,7 +287,7 @@ index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd197
const apiKey = options?.apiKey;
if (!apiKey) {
throw new Error(`No API key for provider: ${model.provider}`);
-@@ -114,7 +124,7 @@ export const streamSimple = (model, context, options) => {
+@@ -108,7 +118,7 @@ export const streamSimple = (model, context, options) => {
...base,
reasoningEffort,
});
@@ -324,7 +296,7 @@ index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd197
function createClient(model, apiKey, options) {
const headers = { ...getIdentityHeaders(model, options?.identity), ...model.headers };
if (options?.headers) {
-@@ -167,6 +177,10 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
+@@ -161,6 +171,10 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
supportsOpenAIGrammarTools: model.compat?.supportsOpenAIGrammarTools ?? false,
});
}
@@ -335,7 +307,7 @@ index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd197
if (options?.toolChoice !== undefined) {
params.tool_choice = options.toolChoice;
}
-@@ -188,6 +202,10 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
+@@ -182,6 +196,10 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr
};
}
}
@@ -347,10 +319,10 @@ index c88f27ee93a6f267f6abf9f69b13d0ad2303c8b2..e557d917026f8c315f56a95ce03bd197
const samplingParams = resolveSamplingParams(model, reasoningEffort ?? "off", options?.samplingParams);
if (samplingParams) {
diff --git a/dist/api/mistral-conversations.js b/dist/api/mistral-conversations.js
-index 193e8e42a40402a33d208e1f9c18e7cff893ce47..53af5c2911b253144c3b9391e95c324d4fb47404 100644
+index 51de5ed18b59979d0e7aa883f46ecdc05ab274a7..da385ff92649735f8850b6ac6511f46d61b0e03f 100644
--- a/dist/api/mistral-conversations.js
+++ b/dist/api/mistral-conversations.js
-@@ -674,6 +674,9 @@ function toChatMessages(messages, supportsImages) {
+@@ -647,6 +647,9 @@ function toChatMessages(messages, supportsImages) {
}
continue;
}
@@ -361,10 +333,10 @@ index 193e8e42a40402a33d208e1f9c18e7cff893ce47..53af5c2911b253144c3b9391e95c324d
id: block.id,
type: "function",
diff --git a/dist/api/openai-codex-responses.js b/dist/api/openai-codex-responses.js
-index 45bcd08b85b478f0f96006881d489820f1264d2c..24d06138833cd9cad81bb519ce5dc58481be7fda 100644
+index 427df0a7054cc4b2071c8e5c2dc2ac1a82ea166a..fce4d2181faaec2e18357c20eade7da2cecd3c29 100644
--- a/dist/api/openai-codex-responses.js
+++ b/dist/api/openai-codex-responses.js
-@@ -418,6 +418,12 @@ function buildRequestBody(model, context, options, cacheSessionId, grammarToolIn
+@@ -413,6 +413,12 @@ function buildRequestBody(model, context, options, cacheSessionId, grammarToolIn
supportsOpenAIGrammarTools,
});
}
@@ -378,10 +350,10 @@ index 45bcd08b85b478f0f96006881d489820f1264d2c..24d06138833cd9cad81bb519ce5dc584
const effort = options.reasoningEffort === "none"
? model.thinkingLevelMap?.off === undefined
diff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js
-index 793ed0a6060e5d2e61b09e2d93514610527873df..78c6a829151d8bb57357d9a379997da4a5f03fbd 100644
+index 12ec37eaf976340d2b29234dab2f17964ed56c91..02d3cdec478f40f40c312dea4d412f9e7c24003b 100644
--- a/dist/api/openai-completions.js
+++ b/dist/api/openai-completions.js
-@@ -1052,21 +1052,27 @@ export function convertMessages(model, context, compat, options) {
+@@ -1034,21 +1034,27 @@ export function convertMessages(model, context, compat, options) {
if (preservedReasoningDetails) {
assistantMsg.reasoning_details = preservedReasoningDetails;
}
@@ -415,7 +387,7 @@ index 793ed0a6060e5d2e61b09e2d93514610527873df..78c6a829151d8bb57357d9a379997da4
}
params.push(assistantMsg);
}
-@@ -1134,6 +1140,49 @@ export function convertMessages(model, context, compat, options) {
+@@ -1116,6 +1122,49 @@ export function convertMessages(model, context, compat, options) {
}
lastRole = msg.role;
}
@@ -465,7 +437,7 @@ index 793ed0a6060e5d2e61b09e2d93514610527873df..78c6a829151d8bb57357d9a379997da4
return params;
}
function convertTools(tools, compat) {
-@@ -1278,6 +1327,9 @@ function detectCompat(model) {
+@@ -1266,6 +1315,9 @@ function detectCompat(model) {
requiresAssistantAfterToolResult: false,
requiresThinkingAsText: false,
requiresReasoningContentOnAssistantMessages: isDeepSeek,
@@ -475,7 +447,7 @@ index 793ed0a6060e5d2e61b09e2d93514610527873df..78c6a829151d8bb57357d9a379997da4
thinkingFormat: isDeepSeek
? "deepseek"
: isZai
-@@ -1331,6 +1383,8 @@ function getCompat(model) {
+@@ -1319,6 +1371,8 @@ function getCompat(model) {
requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ??
detected.requiresReasoningContentOnAssistantMessages,
@@ -485,14 +457,14 @@ index 793ed0a6060e5d2e61b09e2d93514610527873df..78c6a829151d8bb57357d9a379997da4
openRouterRouting: model.compat.openRouterRouting ?? {},
vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-shared.js
-index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448ff0ca7f37 100644
+index 3901bfc4bc6dee0eb45a209dbcbdb59d6c55d054..60b63766576f463b83a964ef9b16d39472222693 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, parseToolCallArguments } from "../utils/json-parse.js";
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
@@ -90,6 +91,7 @@ function renderToolRemovalNotice(names) {
}
export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
@@ -515,7 +487,7 @@ index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448f
else if (block.type === "toolCall") {
const toolCall = block;
const [callId, itemIdRaw] = toolCall.id.split("|");
-@@ -471,6 +480,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
+@@ -458,6 +467,28 @@ export async function processResponsesStream(openaiStream, output, stream, model
stream.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
return slot;
}
@@ -544,7 +516,7 @@ index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448f
return undefined;
};
const getOrCreateSlot = (outputIndex, item) => {
-@@ -552,11 +583,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
+@@ -539,11 +570,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "thinking");
if (!slot)
continue;
@@ -558,7 +530,7 @@ index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448f
partial: output,
});
}
-@@ -576,11 +607,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
+@@ -563,11 +594,11 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "thinking");
if (!slot)
continue;
@@ -572,7 +544,7 @@ index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448f
partial: output,
});
}
-@@ -588,23 +619,44 @@ export async function processResponsesStream(openaiStream, output, stream, model
+@@ -575,23 +606,44 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "text");
if (!slot)
continue;
@@ -621,19 +593,18 @@ index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448f
partial: output,
});
}
-@@ -612,9 +664,9 @@ export async function processResponsesStream(openaiStream, output, stream, model
+@@ -599,8 +651,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
const slot = getSlot(event.output_index, "toolCall");
- if (!slot || slot.block.partialJson === undefined)
+ if (slot?.input.kind !== "json")
continue;
-- slot.block.partialJson += event.delta;
-+ slot.block.partialJson += event.delta ?? "";
- slot.block.arguments = parseStreamingJson(slot.block.partialJson);
+- slot.block.arguments = slot.input.arguments.append(event.delta);
- pushToolCallDelta(slot, event.delta);
++ slot.block.arguments = slot.input.arguments.append(event.delta ?? "");
+ pushToolCallDelta(slot, event.delta ?? "");
}
else if (event.type === "response.function_call_arguments.done") {
const slot = getSlot(event.output_index, "toolCall");
-@@ -700,9 +752,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
+@@ -680,9 +732,25 @@ export async function processResponsesStream(openaiStream, output, stream, model
});
outputSlots.delete(event.output_index);
}
@@ -660,7 +631,7 @@ index b7b27ca98c8f4069a806a01913632a2d9200379c..da6ba8ba9abc8e897c9a72383038448f
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 b418bfb7ca4e378b5b5c3115b79a6bcc7af17775..17cb84b3ba3f42ae602030680112edf84f3fdf5e 100644
+index 7b3b0d733c3495fd0815f563212acac457224dc0..c9e536a33e7e955db48c3c2e2dc7667b41da85d4 100644
--- a/dist/api/openai-responses.js
+++ b/dist/api/openai-responses.js
@@ -1,3 +1,5 @@
@@ -697,7 +668,7 @@ index b418bfb7ca4e378b5b5c3115b79a6bcc7af17775..17cb84b3ba3f42ae602030680112edf8
const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
maxRetries: options?.maxRetries,
maxRetryDelayMs: options?.maxRetryDelayMs,
-@@ -172,6 +178,11 @@ export const stream = (model, context, options) => {
+@@ -172,8 +178,13 @@ export const stream = (model, context, options) => {
stream.end();
}
catch (error) {
@@ -706,19 +677,13 @@ index b418bfb7ca4e378b5b5c3115b79a6bcc7af17775..17cb84b3ba3f42ae602030680112edf8
+ 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.
-@@ -179,7 +190,7 @@ export const stream = (model, context, options) => {
- delete block.customInput;
- }
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
- const errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);
+ const errorMessage = errorDetails?.message ?? formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);
// Sign in with ChatGPT shares the subscription's usage limit with other apps.
// On ChatGPT Business plans, the workspace admin also sets a per-user limit.
if (errorMessage.includes("subscription_sharing_usage_limit_exceeded")) {
-@@ -197,7 +208,7 @@ export const stream = (model, context, options) => {
+@@ -191,7 +202,7 @@ export const stream = (model, context, options) => {
})();
return stream;
};
@@ -727,7 +692,7 @@ index b418bfb7ca4e378b5b5c3115b79a6bcc7af17775..17cb84b3ba3f42ae602030680112edf8
getClientApiKey(model.provider, options?.apiKey, options?.headers);
const base = {
...buildBaseOptions(model, context, options, options?.apiKey),
-@@ -209,7 +220,7 @@ export const streamSimple = (model, context, options) => {
+@@ -203,7 +214,7 @@ export const streamSimple = (model, context, options) => {
...base,
reasoningEffort,
});
@@ -736,7 +701,7 @@ index b418bfb7ca4e378b5b5c3115b79a6bcc7af17775..17cb84b3ba3f42ae602030680112edf8
function createClient(model, context, apiKey, optionsHeaders, identity, fetch, sessionId) {
const compat = getCompat(model);
const headers = { ...getIdentityHeaders(model, identity), ...model.headers };
-@@ -284,6 +295,12 @@ function buildParams(model, context, options, compat, grammarToolInputProperties
+@@ -278,6 +289,12 @@ function buildParams(model, context, options, compat, grammarToolInputProperties
supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,
});
}
@@ -749,7 +714,7 @@ index b418bfb7ca4e378b5b5c3115b79a6bcc7af17775..17cb84b3ba3f42ae602030680112edf8
if (options?.toolChoice !== undefined) {
params.tool_choice = options.toolChoice;
}
-@@ -308,6 +325,10 @@ function buildParams(model, context, options, compat, grammarToolInputProperties
+@@ -302,6 +319,10 @@ function buildParams(model, context, options, compat, grammarToolInputProperties
if (model.provider === "xai")
params.include = ["reasoning.encrypted_content"];
}
@@ -773,7 +738,7 @@ index ed753df7ea29238c5ef2f1543c3568173be00df7..0a1621a162bc6cff3b81550395c0efea
return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));
}
export function resolveSamplingParams(model, thinkingLevel, requestParams) {
-@@ -31,6 +32,7 @@ export function buildBaseOptions(model, context, options, apiKey) {
+@@ -31,6 +31,7 @@ export function buildBaseOptions(model, context, options, apiKey) {
headers: options?.headers,
identity: options?.identity,
onPayload: options?.onPayload,
@@ -782,7 +747,7 @@ index ed753df7ea29238c5ef2f1543c3568173be00df7..0a1621a162bc6cff3b81550395c0efea
onProviderStreamEvent: options?.onProviderStreamEvent,
timeoutMs: options?.timeoutMs,
diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js
-index 0823512eb83d74167335cde72ae21ea32384572e..43d4cae89da499e481ee671c8fc2cccfcdde3dd4 100644
+index 0823512eb83d74167335cde72ae21ea32384572e..338b1571d1e5e2cd6596b98f4ae6c3ffaf343676 100644
--- a/dist/auth/oauth/anthropic.js
+++ b/dist/auth/oauth/anthropic.js
@@ -4,6 +4,7 @@
@@ -939,11 +904,11 @@ index 0823512eb83d74167335cde72ae21ea32384572e..43d4cae89da499e481ee671c8fc2cccf
return {
type: "oauth",
diff --git a/dist/index.d.ts b/dist/index.d.ts
-index 226fa3e6578dacc5744ce5c9271dd20d4a3b5b23..90cda08400b4a49fda02989b3c4a2f9b75494713 100644
+index 5f531d7dbaf7a79972629f7cb5e096af75116d02..f8d9596dffdc83fb087e5d9ab1f3aea8caac7e84 100644
--- a/dist/index.d.ts
+++ b/dist/index.d.ts
-@@ -33,5 +33,8 @@ export * from "./utils/transcript.ts";
- export * from "./utils/typebox-helpers.ts";
+@@ -32,5 +32,8 @@ export { contentText, getSystemMessageText, renderSystemMessageUpdate } from "./
+ export * from "./utils/transcript.ts";
export { uuidv7 } from "./utils/uuid.ts";
export * from "./utils/validation.ts";
+export { LocalRequestError, localRequestErrorDetails } from "./utils/local-request-error.ts";
@@ -951,42 +916,60 @@ index 226fa3e6578dacc5744ce5c9271dd20d4a3b5b23..90cda08400b4a49fda02989b3c4a2f9b
+export * from "./utils/hosted-search.ts";
export { PI_AI_VERSION } from "./utils/version.ts";
//# sourceMappingURL=index.d.ts.map
+\ No newline at end of file
diff --git a/dist/index.js b/dist/index.js
-index d8d81e85328ff551562c9da1d645339a2ddf9f93..d508f96f3af3798fb166e6d7ff294b6c527551bd 100644
+index d1ec9f0c1d3cbe644ba80e81e61cb58becc9ae2d..062642acfad612f54ae0b05af168017501e4e795 100644
--- a/dist/index.js
+++ b/dist/index.js
-@@ -20,5 +20,7 @@ export * from "./utils/transcript.js";
- export * from "./utils/typebox-helpers.js";
+@@ -20,5 +20,7 @@ export { contentText, getSystemMessageText, renderSystemMessageUpdate } from "./
+ export * from "./utils/transcript.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";
export { PI_AI_VERSION } from "./utils/version.js";
//# sourceMappingURL=index.js.map
+\ No newline at end of file
diff --git a/dist/providers/compat-schema.d.ts b/dist/providers/compat-schema.d.ts
-index 681c7d626372d485351672fc7e4c11e3ed2351ee..5d160ed3cf657852ee22416a98653b5fe178443f 100644
+index 0e906dc7d9fa39dad8d52d0c0e6da63351cbeb45..f7e64e2c207605835d81ee094c776fe17d92a73c 100644
--- a/dist/providers/compat-schema.d.ts
+++ b/dist/providers/compat-schema.d.ts
-@@ -71,6 +71,7 @@ export declare const OpenAICompletionsCompatSchema: Type.TObject<{
- requiresAssistantAfterToolResult: Type.TOptional<Type.TBoolean>;
- requiresThinkingAsText: Type.TOptional<Type.TBoolean>;
- requiresReasoningContentOnAssistantMessages: Type.TOptional<Type.TBoolean>;
-+ requiresNonEmptyReasoningReplay: Type.TOptional<Type.TBoolean>;
- thinkingFormat: Type.TOptional<Type.TUnion<[Type.TLiteral<"openai">, Type.TLiteral<"openrouter">, Type.TLiteral<"deepseek">, Type.TLiteral<"together">, Type.TLiteral<"baseten">, Type.TLiteral<"zai">, Type.TLiteral<"qwen">, Type.TLiteral<"chat-template">, Type.TLiteral<"qwen-chat-template">, Type.TLiteral<"string-thinking">, Type.TLiteral<"ant-ling">]>>;
- chatTemplateKwargs: Type.TOptional<Type.TRecord<"^.*$", Type.TUnion<[Type.TString, Type.TNumber, Type.TBoolean, Type.TNull, Type.TObject<{
- $var: Type.TUnion<[Type.TLiteral<"thinking.enabled">, Type.TLiteral<"thinking.effort">, Type.TLiteral<"thinking.budget">]>;
+@@ -71,6 +71,7 @@ export declare const OpenAICompletionsCompatSchema: import("@earendil-works/pi-s
+ requiresAssistantAfterToolResult?: boolean | undefined;
+ requiresThinkingAsText?: boolean | undefined;
+ requiresReasoningContentOnAssistantMessages?: boolean | undefined;
++ requiresNonEmptyReasoningReplay?: boolean | undefined;
+ thinkingFormat?: "ant-ling" | "baseten" | "chat-template" | "deepseek" | "openai" | "openrouter" | "qwen" | "qwen-chat-template" | "string-thinking" | "together" | "zai" | undefined;
+ chatTemplateKwargs?: Record<string, string | number | boolean | {
+ $var: "thinking.budget" | "thinking.effort" | "thinking.enabled";
+@@ -198,6 +199,7 @@ export declare const CompatSchemasByApi: {
+ requiresAssistantAfterToolResult?: boolean | undefined;
+ requiresThinkingAsText?: boolean | undefined;
+ requiresReasoningContentOnAssistantMessages?: boolean | undefined;
++ requiresNonEmptyReasoningReplay?: boolean | undefined;
+ thinkingFormat?: "ant-ling" | "baseten" | "chat-template" | "deepseek" | "openai" | "openrouter" | "qwen" | "qwen-chat-template" | "string-thinking" | "together" | "zai" | undefined;
+ chatTemplateKwargs?: Record<string, string | number | boolean | {
+ $var: "thinking.budget" | "thinking.effort" | "thinking.enabled";
+@@ -353,6 +355,7 @@ export declare const ProviderCompatSchema: import("@earendil-works/pi-schema").S
+ requiresAssistantAfterToolResult?: boolean | undefined;
+ requiresThinkingAsText?: boolean | undefined;
+ requiresReasoningContentOnAssistantMessages?: boolean | undefined;
++ requiresNonEmptyReasoningReplay?: boolean | undefined;
+ thinkingFormat?: "ant-ling" | "baseten" | "chat-template" | "deepseek" | "openai" | "openrouter" | "qwen" | "qwen-chat-template" | "string-thinking" | "together" | "zai" | undefined;
+ chatTemplateKwargs?: Record<string, string | number | boolean | {
+ $var: "thinking.budget" | "thinking.effort" | "thinking.enabled";
diff --git a/dist/providers/compat-schema.js b/dist/providers/compat-schema.js
-index 33d82ac41790de38f7affdbcc2635d6e746c490a..35304bdd315cdfac4592b2ce9649f4c961e8a1af 100644
+index cc9e60a5f8ef12c976984a8a4c8f55eb588896f5..a9dafd908c5cca6cc275985853d7acccaef74709 100644
--- a/dist/providers/compat-schema.js
+++ b/dist/providers/compat-schema.js
-@@ -106,6 +106,9 @@ function optionalSessionAffinityFormat(options) {
- return Type.Optional(sessionAffinityFormat(options));
+@@ -111,6 +111,9 @@ function optionalSessionAffinityFormat(options) {
+ return opt(sessionAffinityFormat(options));
}
- export const OpenAICompletionsCompatSchema = Type.Object({
-+ requiresNonEmptyReasoningReplay: Type.Optional(Type.Boolean({
+ const OpenAICompletionsCompatProperties = {
++ requiresNonEmptyReasoningReplay: opt(bool({
+ description: "Whether assistant replay without reasoning requires a non-empty placeholder. Explicit endpoint opt-in only.",
+ })),
- supportsStore: Type.Optional(Type.Boolean({
+ supportsStore: opt(bool({
description: "Whether the provider supports the store field. Default: auto-detected from URL.",
})),
diff --git a/dist/providers/data/deepseek.json b/dist/providers/data/deepseek.json
@@ -997,7 +980,7 @@ index 1443bb592b2913ba09579f3f555a2b09456e63cf..5fc0625778014863aa267ac5186db2cd
-{"openai-completions":{"chat:deepseek-flash":{"id":"deepseek-flash","name":"DeepSeek V4.1 Flash","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"thinkingLevelMap":{"minimal":null,"low":"low","medium":null,"high":"high","max":"max"},"input":["text","image"],"cost":{"input":0.3,"output":1.2,"cacheRead":0.006,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:deepseek-v4-pro":{"id":"deepseek-v4-pro","name":"DeepSeek V4 Pro","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"input":["text"],"cost":{"input":1.32,"output":3.96,"cacheRead":0.044,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true,"supportsMidConvoSystemMessages":true},"thinkingLevelMap":{"minimal":null,"low":null,"medium":null,"high":"high","max":"max"},"type":"chat"}}}
+{"openai-completions":{"chat:deepseek-flash":{"id":"deepseek-flash","name":"DeepSeek V4.1 Flash","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"thinkingLevelMap":{"minimal":null,"low":"low","medium":null,"high":"high","max":"max"},"input":["text","image"],"cost":{"input":0.3,"output":1.2,"cacheRead":0.006,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true,"supportsMidConvoSystemMessages":true},"inputLimits":{"images":{"resize":{"maxWidth":2000,"maxHeight":2000,"maxBytes":4718592,"jpegQuality":80}}},"type":"chat"},"chat:deepseek-v4-pro":{"id":"deepseek-v4-pro","name":"DeepSeek V4 Pro","api":"openai-completions","baseUrl":"https://api.deepseek.com","provider":"deepseek","reasoning":true,"input":["text"],"cost":{"input":1.32,"output":3.96,"cacheRead":0.044,"cacheWrite":0},"contextWindow":1000000,"maxTokens":384000,"compat":{"supportsStore":false,"supportsDeveloperRole":false,"maxTokensField":"max_tokens","requiresReasoningContentOnAssistantMessages":true,"thinkingFormat":"deepseek","supportsStrictMode":true,"supportsMidConvoSystemMessages":true},"thinkingLevelMap":{"minimal":null,"low":null,"medium":null,"high":"high","max":"max"},"type":"chat"}}}
diff --git a/dist/types.d.ts b/dist/types.d.ts
-index e92eefd0889876a84929584675ef2ec441051a2b..7b00dcd6e9e7b84962675d23ea442c08b437ea6d 100644
+index 2d650ea3ece9ed470dc6c60538409e2b84f06f32..c814ef7e9187fd57b26cbefc8722c81ed5e68159 100644
--- a/dist/types.d.ts
+++ b/dist/types.d.ts
@@ -240,6 +240,8 @@ export interface SimpleStreamOptions extends StreamOptions {
@@ -1040,7 +1023,7 @@ index e92eefd0889876a84929584675ef2ec441051a2b..7b00dcd6e9e7b84962675d23ea442c08
export interface Usage {
input: number;
output: number;
-@@ -367,7 +393,7 @@ export interface UserMessage {
+@@ -374,7 +400,7 @@ export interface UserMessage {
}
export interface AssistantMessage {
role: "assistant";
@@ -1049,7 +1032,7 @@ index e92eefd0889876a84929584675ef2ec441051a2b..7b00dcd6e9e7b84962675d23ea442c08
api: Api;
provider: ProviderId;
model: string;
-@@ -382,6 +408,8 @@ export interface AssistantMessage {
+@@ -389,6 +415,8 @@ export interface AssistantMessage {
stopReason: StopReason;
deferred?: DeferredHandle;
errorMessage?: string;
@@ -1058,7 +1041,7 @@ index e92eefd0889876a84929584675ef2ec441051a2b..7b00dcd6e9e7b84962675d23ea442c08
rawStopReason?: string;
/**
* Provider indication of whether the model explicitly ended its turn.
-@@ -617,6 +645,10 @@ export type AssistantMessageEvent = {
+@@ -627,6 +655,10 @@ export type AssistantMessageEvent = {
contentIndex: number;
toolCall: ToolCall;
partial: AssistantMessage;
@@ -1069,7 +1052,7 @@ index e92eefd0889876a84929584675ef2ec441051a2b..7b00dcd6e9e7b84962675d23ea442c08
} | {
type: "done";
reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;
-@@ -648,6 +680,8 @@ export interface Model<TApi extends Api> extends BaseModel<TApi> {
+@@ -658,6 +690,8 @@ export interface Model<TApi extends Api> extends BaseModel<TApi> {
*/
type?: "chat";
reasoning: boolean;
diff --git a/patches/@[email protected] b/patches/@[email protected]
similarity index 95%
rename from patches/@[email protected]
rename to patches/@[email protected]
index daa0f46f1..0c89c5077 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -1,8 +1,8 @@
diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js
-index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cdc5a16738 100644
+index ccbb5a96b093a95499f1caa4a30371c3ebd4102a..d423f0fd3348981f738b4229ad5c9f43b72e380b 100644
--- a/dist/core/agent-session.js
+++ b/dist/core/agent-session.js
-@@ -69,10 +69,10 @@ function withoutDeletedHeaders(headers) {
+@@ -79,10 +79,10 @@ function withoutDeletedHeaders(headers) {
? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
: undefined;
}
@@ -15,7 +15,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
}
return tokens;
}
-@@ -418,7 +418,7 @@ export class AgentSession {
+@@ -431,7 +431,7 @@ export class AgentSession {
_exceedsCompactionThreshold(model, projection) {
if (model.contextWindow <= 0)
return false;
@@ -24,7 +24,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
}
async _compactBeforeNextAssistantResponse(context) {
const projection = this.sessionManager.buildSessionProjection();
-@@ -590,7 +590,7 @@ export class AgentSession {
+@@ -603,7 +603,7 @@ export class AgentSession {
entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
break;
case "compaction": {
@@ -33,7 +33,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, draft.details, true, draft.usage);
break;
}
-@@ -2240,7 +2240,7 @@ export class AgentSession {
+@@ -2258,7 +2258,7 @@ export class AgentSession {
}
const settings = this.settingsManager.getCompactionSettings(model);
const pathEntries = this.sessionManager.getBranch();
@@ -42,7 +42,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
if (!preparation) {
// Check why we can't compact
const lastEntry = pathEntries[pathEntries.length - 1];
-@@ -2297,7 +2297,7 @@ export class AgentSession {
+@@ -2315,7 +2315,7 @@ export class AgentSession {
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
const newEntries = this.sessionManager.getEntries();
this._refreshFinalizedContext();
@@ -51,7 +51,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
// Get the saved compaction entry for the extension event
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
if (this._extensionRunner && savedCompactionEntry) {
-@@ -2480,11 +2480,11 @@ export class AgentSession {
+@@ -2498,11 +2498,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) {
@@ -65,7 +65,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
// 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) {
-@@ -2530,7 +2530,7 @@ export class AgentSession {
+@@ -2548,7 +2548,7 @@ export class AgentSession {
return false;
}
const pathEntries = this.sessionManager.getBranch();
@@ -74,7 +74,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
if (!preparation) {
return false;
}
-@@ -2586,7 +2586,7 @@ export class AgentSession {
+@@ -2604,7 +2604,7 @@ export class AgentSession {
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
const newEntries = this.sessionManager.getEntries();
this._refreshFinalizedContext();
@@ -83,7 +83,7 @@ index 8728a3e0d31f478f28d707cbf313225da4035aca..51f3c5bf0de0c5fedd3144e8d24957cd
// Get the saved compaction entry for the extension event
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
if (this._extensionRunner && savedCompactionEntry) {
-@@ -3524,7 +3524,7 @@ export class AgentSession {
+@@ -3542,7 +3542,7 @@ export class AgentSession {
if (!hasPostCompactionUsage)
return { tokens: null, contextWindow, percent: null };
}
@@ -121,19 +121,19 @@ index bc4af31b57f4a8696a68d4f2a529a26669955382..24a4f8e28624523112cac6c73464e93f
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 12cb88ef5398b2365d5823597b7ccf063af567d6..6ff73567bbd5289b8b3f2fb82f923a5b5dc7860e 100644
+index 4203f63b0f3d8d40421e6f6555e2ed2d6a189254..8d8a995ac0d112a28c69de407991b3215a951514 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 { AgentMessage, StreamFn, ThinkingLevel } 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 ReadonlySessionManager, type SessionEntry } from "../session-manager.ts";
import { type FileOperations } from "./utils.ts";
export interface BranchSummaryResult {
-@@ -87,7 +87,7 @@ export declare function collectEntriesForBranchSummary(session: ReadonlySessionM
+@@ -89,7 +89,7 @@ export declare function collectEntriesForBranchSummary(session: ReadonlySessionM
* @param entries - Entries in chronological order
* @param tokenBudget - Maximum tokens to include (0 = no limit)
*/
@@ -143,10 +143,10 @@ index 12cb88ef5398b2365d5823597b7ccf063af567d6..6ff73567bbd5289b8b3f2fb82f923a5b
* Generate a summary of abandoned branch entries.
*
diff --git a/dist/core/compaction/branch-summarization.js b/dist/core/compaction/branch-summarization.js
-index dba3462974d41ae6201ccf12a775c75ec6c7de5e..3c02d5cb0ae96362130b3c87967e55bb948028b2 100644
+index 9952cf5caeebb5d26782b7f0368175ffa41ec31d..22b959b2fbb956fd91eecc38d9c1f8cfff9dabdc 100644
--- a/dist/core/compaction/branch-summarization.js
+++ b/dist/core/compaction/branch-summarization.js
-@@ -95,7 +95,7 @@ function getMessageFromEntry(entry) {
+@@ -98,7 +98,7 @@ function getMessageFromEntry(entry, edit) {
* @param entries - Entries in chronological order
* @param tokenBudget - Maximum tokens to include (0 = no limit)
*/
@@ -155,7 +155,7 @@ index dba3462974d41ae6201ccf12a775c75ec6c7de5e..3c02d5cb0ae96362130b3c87967e55bb
const messages = [];
const fileOps = createFileOps();
let totalTokens = 0;
-@@ -125,7 +125,7 @@ export function prepareBranchEntries(entries, tokenBudget = 0) {
+@@ -134,7 +134,7 @@ export function prepareBranchEntries(entries, tokenBudget = 0) {
continue;
// Extract file ops from assistant messages (tool calls)
extractFileOpsFromMessage(message, fileOps);
@@ -164,7 +164,7 @@ index dba3462974d41ae6201ccf12a775c75ec6c7de5e..3c02d5cb0ae96362130b3c87967e55bb
// 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) {
+@@ -198,7 +198,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;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4c2a2196e..4c0fc7b36 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -205,9 +205,9 @@ overrides:
vite@5: '>=6.4.3 <7'
patchedDependencies:
- '@earendil-works/[email protected]': f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da
- '@earendil-works/[email protected]': 718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a
- '@earendil-works/[email protected]': 1f1a1efed2ccd6fccef2608bf0cd304cd6af4c91824839189c73ab88953e5635
+ '@earendil-works/[email protected]': f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da
+ '@earendil-works/[email protected]': 07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4
+ '@earendil-works/[email protected]': 1d20a271da819982a9d458d6064c51e5e06fc28637c2efa94d5683e5b3867d90
importers:
@@ -233,11 +233,11 @@ importers:
version: 0.2.2
devDependencies:
'@earendil-works/pi-ai':
- specifier: 1.4.0
- version: 1.4.0(patch_hash=718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ specifier: 1.5.0
+ version: 1.5.0(patch_hash=07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-mcp':
- specifier: 1.4.0
- version: 1.4.0
+ specifier: 1.5.0
+ version: 1.5.0
'@pi-desktop/agent-host':
specifier: workspace:*
version: link:../../packages/agent-host
@@ -431,14 +431,14 @@ importers:
packages/agent-runtime:
dependencies:
'@earendil-works/pi-agent-core':
- specifier: 1.4.0
- version: 1.4.0(patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ specifier: 1.5.0
+ version: 1.5.0(patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-ai':
- specifier: 1.4.0
- version: 1.4.0(patch_hash=718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ specifier: 1.5.0
+ version: 1.5.0(patch_hash=07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
'@earendil-works/pi-coding-agent':
- specifier: 1.4.0
- version: 1.4.0(patch_hash=1f1a1efed2ccd6fccef2608bf0cd304cd6af4c91824839189c73ab88953e5635)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
+ specifier: 1.5.0
+ version: 1.5.0(patch_hash=1d20a271da819982a9d458d6064c51e5e06fc28637c2efa94d5683e5b3867d90)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])
'@pi-desktop/shared':
specifier: workspace:*
version: link:../shared
@@ -449,8 +449,8 @@ importers:
specifier: 1.3.27
version: 1.3.27
undici:
- specifier: 8.10.2
- version: 8.10.2
+ specifier: 8.12.3
+ version: 8.12.3
yaml:
specifier: 2.9.0
version: 2.9.0
@@ -966,34 +966,38 @@ packages:
search-insights:
optional: true
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-PoKY84SKUwnt7S5QBZaGUqfNO1kjP3KHpHUA9QpFTj4cOjaVWMYIcBPJ6FDRCdE8Zen9OSECQUd0uUfVgtSmgA==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-FOj+jXj48DbzMycR/ghNa2KcsqWmvOln24e0FnQOVgnd8vn5H79g335WdHaZUVdRo+zCeogb40/qPPlCWFuvmA==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-hQM/C4+1w8rHYACzDDf+0vQMnEnpzIop1tptIERVgR3ZeT/hHSzBNG8PaWPgxWQjqSeKCyBZSyp8uTT6eKK1pQ==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-VeWxNqTHSqRCf8AcY/6kvNwh+neRL6MPxZPePVztIQy6qqK9MR/YoCSN/ZgDnIyCD3pqEXgRyQbzk4KV4uvjbg==}
engines: {node: '>=22.19.0'}
hasBin: true
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-23CNAXpS9DuLzPMyYuvrXVVio46x4YhffCgCqaWmF7F5H8PooqjrQvX4ucF6M0BhUd+x2tV6r1J0dv8cCME4Cg==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-PLBJZ17AEWGzOlAAcFuOkw3PxkOti0JlFuZQyeF2GRTqbpuYo4k9t8YqUV2uOQVzrUnKdxahwaFUqc1eNS1WAg==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-Z41LpZ3yYHSC/UUps6Mr39UMFPwH8elhJBG9DY1P7kuzsE5qSK/6eMj2EHzO5evJRQWLbKSqUMw+4nCNtIyiQg==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-xNDZ5kqowO6Z03FS2gwAkPEGk1ssxVcYKQ6qZId84mFEvwACvvyc2l0vAMOS+c5zvxLRMLBE9r4y44IGYkMJaQ==}
engines: {node: '>=22.19.0'}
hasBin: true
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-92aZmmGsUpHHknYuKXZHRINQfahntw5hU9If0I0ZM49GojOaFHpkl5/GF3/aatqpt7v7GjZbBfpfSygGKW+pnw==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-DURw3IwHCTMHV8CzUJWVp9css27NowsCWfXt4xg2r09IZ+P1O/Uq58hp0hb9WJO0dbkaKGXKBIkV4LVXcu2nlg==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-MLIfowwUYIY65jSjMX82paZOrX/NTvLk6D08h+3Jq42a99RzUOewzuCR0zOlPul3D6UBfddat76VT6LvsHEs1w==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-RW0MbT2tR65OY6xMsgB/yVBb7m/RTNwA+9hurSN1vVXfHZRVmVnXbruBPrx/PzbrQnW5yLVlMRWxErGDQtF1Hg==}
engines: {node: '>=22.19.0'}
- '@earendil-works/[email protected]':
- resolution: {integrity: sha512-4obPOjgOD7g4mGSlngIvxyujC1UPdmyI9zdVthbr8GufacFEX+Ce0+scPgHg++k2xj5+QjESM2d5TxvIuzCVmg==}
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-VW3tcVdnNfl/Vk8wHPTzZdKkxcsCOM12ppiO4DXnd9wMxUCmOfLt/wvUnWeKWbTVlVSRg0uqKtnnhE2UCsG2Bw==}
+ engines: {node: '>=22.19.0'}
+
+ '@earendil-works/[email protected]':
+ resolution: {integrity: sha512-56KqrDVeLF18k+syppVbT35Ai1opbM44ot+sL7O3K40CaWwXCiwOpqEFugDBAILtAhseZh6uYIuYxPPOJHLFAA==}
engines: {node: '>=22.19.0'}
'@electron-internal/[email protected]':
@@ -1388,6 +1392,9 @@ packages:
resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}
engines: {node: '>=18.0.0'}
+ '@isaacs/[email protected]':
+ resolution: {integrity: sha512-SI7kyKHq4XXDRozw+r9GlRZkia1ZkFrpLW98r2IC2Bpr8YkFGE3fvjzmxCG0x78A++69HmDNrDvSMYBZmHGpKA==}
+
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -3628,6 +3635,10 @@ packages:
resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}
engines: {node: 18 || 20 || >=22}
+ resolution: {integrity: sha512-iny/40PEGkNJQ5/Pv6z3nm6FbRAby32GeZRjCUJk2WnNDbgPSTcdI+DDvLqsgBdD4cD5sMtMheqPPnehCCa8Nw==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}
@@ -4275,8 +4286,8 @@ packages:
resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==}
engines: {node: '>=20.18.1'}
- resolution: {integrity: sha512-/y4/bH9YNU5hi9NIrpOuvGXFcxrj3CMrV+/AYpowAYTpHn8gX/XPFjNy766FPoYY0miQhdW977JFWKGNhBdwyQ==}
+ resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==}
engines: {node: '>=22.19.0'}
@@ -5092,10 +5103,10 @@ snapshots:
transitivePeerDependencies:
- '@algolia/client-search'
- '@earendil-works/[email protected](patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
- '@earendil-works/pi-ai': 1.4.0(patch_hash=718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- typebox: 1.3.27
+ '@earendil-works/pi-ai': 1.5.0(patch_hash=07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ '@earendil-works/pi-schema': 1.5.0
transitivePeerDependencies:
- '@aws-sdk/credential-provider-node'
- '@modelcontextprotocol/sdk'
@@ -5109,18 +5120,18 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected](patch_hash=718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.129.0([email protected])
'@aws-sdk/client-bedrock-runtime': 3.1127.0
- '@earendil-works/pi-telemetry': 1.4.0
+ '@earendil-works/pi-schema': 1.5.0
+ '@earendil-works/pi-telemetry': 1.5.0
'@google/genai': 2.21.0([email protected])
'@smithy/node-http-handler': 4.12.1
http-proxy-agent: 9.1.0([email protected])
https-proxy-agent: 9.1.0([email protected])
partial-json: 0.1.7
- typebox: 1.3.27
transitivePeerDependencies:
- '@aws-sdk/credential-provider-node'
- '@modelcontextprotocol/sdk'
@@ -5134,18 +5145,18 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected](patch_hash=718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])':
dependencies:
'@anthropic-ai/sdk': 0.129.0([email protected])
'@aws-sdk/client-bedrock-runtime': 3.1127.0
- '@earendil-works/pi-telemetry': 1.4.0
+ '@earendil-works/pi-schema': 1.5.0
+ '@earendil-works/pi-telemetry': 1.5.0
'@google/genai': 2.21.0([email protected])
'@smithy/node-http-handler': 4.12.1
http-proxy-agent: 9.1.0([email protected])
https-proxy-agent: 9.1.0([email protected])
partial-json: 0.1.7
- typebox: 1.3.27
transitivePeerDependencies:
- '@aws-sdk/credential-provider-node'
- '@modelcontextprotocol/sdk'
@@ -5159,17 +5170,17 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected]':
+ '@earendil-works/[email protected]':
dependencies:
quickjs-wasi: 3.6.2
- '@earendil-works/[email protected](patch_hash=1f1a1efed2ccd6fccef2608bf0cd304cd6af4c91824839189c73ab88953e5635)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':
+ '@earendil-works/[email protected](patch_hash=1d20a271da819982a9d458d6064c51e5e06fc28637c2efa94d5683e5b3867d90)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':
dependencies:
- '@earendil-works/pi-agent-core': 1.4.0(patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- '@earendil-works/pi-ai': 1.4.0(patch_hash=718245c1ead731e1a464ec029f877b568827d58ffe1f3209994faeca44a4ca0a)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
- '@earendil-works/pi-codemode': 1.4.0
- '@earendil-works/pi-mcp': 1.4.0
- '@earendil-works/pi-tui': 1.4.0
+ '@earendil-works/pi-agent-core': 1.5.0(patch_hash=f7df81a6d069cd0287276085d46d531684234acb7243dc032b1a1d73b17019da)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ '@earendil-works/pi-ai': 1.5.0(patch_hash=07ea52be73bf9e7a5484acf9016967785b68fadc0c3b2fc68666a6b84e6609d4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ '@earendil-works/pi-codemode': 1.5.0
+ '@earendil-works/pi-mcp': 1.5.0
+ '@earendil-works/pi-tui': 1.5.0
'@silvia-odwyer/photon-node': 0.3.4
brace-expansion: 5.0.12
chalk: 6.0.0
@@ -5180,12 +5191,12 @@ snapshots:
hosted-git-info: 9.0.3
ignore: 7.0.8
jiti: 2.7.0
- minimatch: 10.2.6
+ minimatch: 11.0.3
proper-lockfile: 4.1.2
quickjs-wasi: 3.6.2
semver: 7.8.5
typebox: 1.3.27
- undici: 8.10.2
+ undici: 8.12.3
yaml: 2.9.0
transitivePeerDependencies:
- '@aws-sdk/credential-provider-node'
@@ -5199,13 +5210,15 @@ snapshots:
- ws
- zod
- '@earendil-works/[email protected]':
+ '@earendil-works/[email protected]':
dependencies:
cross-spawn: 7.0.6
- '@earendil-works/[email protected]': {}
+ '@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
@@ -5508,6 +5521,8 @@ snapshots:
dependencies:
minipass: 7.1.3
+ '@isaacs/[email protected]': {}
+
'@jridgewell/[email protected]':
dependencies:
'@jridgewell/sourcemap-codec': 1.6.0
@@ -8161,6 +8176,11 @@ snapshots:
dependencies:
brace-expansion: 5.0.12
+ dependencies:
+ '@isaacs/nonrecursive-glob-match': 1.0.3
+ brace-expansion: 5.0.12
+
dependencies:
brace-expansion: 1.1.21
@@ -8273,11 +8293,11 @@ snapshots:
ws: 8.21.1
zod: 4.4.3
optionalDependencies:
'@aws-sdk/credential-provider-node': 3.972.83
'@smithy/signature-v4': 5.7.3
- undici: 8.10.2
+ undici: 8.12.3
ws: 8.21.1
zod: 4.4.3
@@ -8855,7 +8875,7 @@ snapshots:
optional: true
dependencies:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 34650a974..861f04ad7 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -13,16 +13,17 @@ allowBuilds:
# binary; its from-source install script was never approved and is not needed.
koffi: false
# pnpm records exact-version exclusions for the current, explicitly requested
-# Pi 1.4.0 release while it is inside the minimum release age window. Keep these
+# Pi 1.5.0 release while it is inside the minimum release age window. Keep these
# entries exact; do not widen them to package names or ranges.
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]'
+ - '@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.
@@ -58,9 +59,9 @@ overrides:
# every range to its floor — silently downgrading dependencies instead of
# refreshing them. Pin the intent: `pnpm update` means "newest within range".
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]
resolutionMode: highest
# shamefully-hoist also lives in .npmrc, but pnpm 12 applies it only from
# here; without it public hoisting is empty and examples/ plugins cannot
diff --git a/scripts/check-pi-dependencies.mjs b/scripts/check-pi-dependencies.mjs
index 1b8fe57e3..764682dbb 100644
--- a/scripts/check-pi-dependencies.mjs
+++ b/scripts/check-pi-dependencies.mjs
@@ -25,7 +25,7 @@ function parseArgs(argv) {
}
const root = parseArgs(process.argv.slice(2));
-const targetVersion = "1.4.0";
+const targetVersion = "1.5.0";
function readJson(path) {
return JSON.parse(readFileSync(join(root, path), "utf8"));
@@ -69,7 +69,7 @@ for (const packageName of ["@earendil-works/pi-ai", "@earendil-works/pi-mcp"]) {
const lockfile = readFileSync(join(root, "pnpm-lock.yaml"), "utf8");
for (const packageName of ["pi-agent-core", "pi-ai", "pi-coding-agent", "pi-mcp"]) {
- if (new RegExp(`@earendil-works/${packageName}@1\\.[0-3]\\.\\d+(?:[(:]|$)`).test(lockfile)) {
+ if (new RegExp(`@earendil-works/${packageName}@1\\.[0-4]\\.\\d+(?:[(:]|$)`).test(lockfile)) {
throw new Error(`pnpm-lock.yaml still contains an outdated @earendil-works/${packageName}`);
}
}
@@ -81,16 +81,17 @@ const actualReleaseAgeExclusions = [...releaseAgeExclusions.matchAll(/^[ \t]+-[
.map((match) => match[1])
.sort();
const expectedReleaseAgeExclusions = [
- "@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]",
+ "@earendil-works/[email protected]",
+ "@earendil-works/[email protected]",
+ "@earendil-works/[email protected]",
].sort();
if (JSON.stringify(actualReleaseAgeExclusions) !== JSON.stringify(expectedReleaseAgeExclusions)) {
- throw new Error("Pi minimumReleaseAgeExclude entries must match only the exact 1.4.0 release packages");
+ throw new Error("Pi minimumReleaseAgeExclude entries must match only the exact 1.5.0 release packages");
}
process.stdout.write(`Pi direct pins and installed package instances are aligned at ${targetVersion}.\n`);
diff --git a/scripts/check-pi-patches.mjs b/scripts/check-pi-patches.mjs
index 0bbaa077b..671c82714 100644
--- a/scripts/check-pi-patches.mjs
+++ b/scripts/check-pi-patches.mjs
@@ -25,7 +25,7 @@ function parseArgs(argv) {
}
const root = parseArgs(process.argv.slice(2));
-const targetVersion = "1.4.0";
+const targetVersion = "1.5.0";
const entries = [
{
name: "@earendil-works/pi-agent-core",
diff --git a/scripts/pi-patch-hash.test.mjs b/scripts/pi-patch-hash.test.mjs
index 465b65e0f..a60d1dfbe 100644
--- a/scripts/pi-patch-hash.test.mjs
+++ b/scripts/pi-patch-hash.test.mjs
@@ -11,7 +11,7 @@ const here = dirname(fileURLToPath(import.meta.url));
const patchDependencyCheck = join(here, "check-pi-dependencies.mjs");
const patchCheck = join(here, "check-pi-patches.mjs");
-const TARGET = "1.4.0";
+const TARGET = "1.5.0";
const PATCHED = [
{
name: "@earendil-works/pi-agent-core",
@@ -44,6 +44,7 @@ const RELEASE_AGE_EXCLUDE = [
"pi-codemode",
"pi-coding-agent",
"pi-mcp",
+ "pi-schema",
"pi-telemetry",
"pi-tui",
].map((name) => `@earendil-works/${name}@${TARGET}`);