Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(runtime): keep provider thinking signatures across runtime rebuilds
zszz3b2e708db88b4
diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rsindex c45da1878..27ce49108 100644--- a/crates/host-core/src/plugin_sessions.rs+++ b/crates/host-core/src/plugin_sessions.rs@@ -261,6 +261,7 @@ fn parse_message(agent_name: None,hosted_search: None,model_system: None,+ provider_replay: None,session_message: None,})}diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex c87ee3900..6f3ff34cb 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -277,6 +277,11 @@ pub struct UiMessage {/// Internal model-context state, preserved outside visible message text.#[serde(default, skip_serializing_if = "Option::is_none")]pub model_system: Option<Value>,+ /// Opaque provider replay data (thinking/text block boundaries and+ /// signatures) for an assistant row. Stored in record meta; no SQL+ /// migration, and older builds ignore it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub provider_replay: Option<Value>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -393,6 +398,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<Stringif let Some(system) = &message.model_system {meta_obj.insert("modelSystem".into(), system.clone());}+ if let Some(replay) = &message.provider_replay {+ meta_obj.insert("providerReplay".into(), replay.clone());+ }if let Some(command) = &message.command {meta_obj.insert("command".into(), json!(command));}@@ -549,6 +557,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {};let meta = record.meta.unwrap_or(Value::Null);let model_system = meta.get("modelSystem").cloned();+ let provider_replay = meta.get("providerReplay").cloned();let command = meta.get("command").and_then(Value::as_str)@@ -727,6 +736,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {agent_name,hosted_search: hosted_search.clone(),model_system: None,+ provider_replay: None,}} else {let content = blocks@@ -772,6 +782,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {agent_name,hosted_search,model_system,+ provider_replay,}}}@@ -4452,6 +4463,7 @@ mod tests {agent_name: None,hosted_search: None,model_system: None,+ provider_replay: None,session_message: None,}}@@ -5415,6 +5427,7 @@ mod tests {agent_name: None,hosted_search: None,model_system: None,+ provider_replay: None,session_message: None,};append_message(&db, &session.id, &tool, None).unwrap();@@ -6217,6 +6230,7 @@ mod tests {agent_name: None,hosted_search: None,model_system: None,+ provider_replay: None,session_message: None,};append_message(&db, &session.id, &assistant, None).unwrap();@@ -6260,6 +6274,64 @@ mod tests {assert_eq!(detail.messages[0].response_output_tokens, Some(34));}+ #[test]+ fn assistant_provider_replay_roundtrips_in_record_meta() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let replay = json!({+ "version": 1,+ "blocks": [+ { "type": "thinking", "length": 3, "signature": "sig-a" },+ { "type": "text", "length": 6 }+ ]+ });+ let assistant: UiMessage = serde_json::from_value(json!({+ "id": "assistant-replay-1",+ "role": "assistant",+ "content": "answer",+ "thinking": "abc",+ "createdAt": "2025-05-01T00:00:01Z",+ "status": "complete",+ "providerReplay": replay,+ }))+ .unwrap();+ let plain: UiMessage = serde_json::from_value(json!({+ "id": "assistant-replay-2",+ "role": "assistant",+ "content": "plain",+ "createdAt": "2025-05-01T00:00:02Z",+ "status": "complete",+ }))+ .unwrap();+ append_message(&db, &session.id, &assistant, None).unwrap();+ append_message(&db, &session.id, &plain, None).unwrap();++ let records = transcripts::read_transcript(db.data_dir(), &session.id).unwrap();+ assert_eq!(+ records[0]+ .meta+ .as_ref()+ .and_then(|m| m.get("providerReplay")),+ Some(&replay)+ );+ // Replay data lives in meta only: the visible blocks are unchanged.+ assert_eq!(+ records[0].blocks,+ json!([{ "type": "thinking", "text": "abc" }, { "type": "text", "text": "answer" }])+ );+ assert!(records[1]+ .meta+ .as_ref()+ .and_then(|m| m.get("providerReplay"))+ .is_none());++ let detail = get_session(&db, &session.id).unwrap().unwrap();+ assert_eq!(detail.messages[0].provider_replay, Some(replay));+ assert_eq!(detail.messages[0].thinking.as_deref(), Some("abc"));+ assert_eq!(detail.messages[0].content, "answer");+ assert_eq!(detail.messages[1].provider_replay, None);+ }+#[test]fn assistant_hosted_search_roundtrips_as_canonical_blocks() {let db = test_db();@@ -6297,6 +6369,7 @@ mod tests {nested_parent_tool_call_id: None,agent_name: None,model_system: None,+ provider_replay: None,hosted_search: Some(json!({"status": "completed","rounds": [diff --git a/docs/project/unreleased.md b/docs/project/unreleased.mdindex 1135d7308..086229dd8 100644--- a/docs/project/unreleased.md+++ b/docs/project/unreleased.md@@ -1,5 +1,11 @@# Unreleased changes+- Fixed prompt cache misses after a conversation's agent runtime is rebuilt+ (#1972). Rebuilding happens after a restart or when the thinking level, mode,+ project rules, or model settings change. Assistant replies now keep the+ provider's thinking and reasoning signatures in the transcript, so Claude,+ OpenAI Responses, Gemini, and other reasoning models receive the same history+ as before the rebuild instead of a rewritten one.- Fixed duplicate `/、` when opening slash commands with a Chinese IME in anempty composer. Keep pre-edit text intact and apply the slash alias onlyafter composition commits, preserving recovery from a missing end event.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex a2924565a..fb13ae87f 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -302,6 +302,21 @@ precedence, then a preceding anchor, then the record's continuation position.Forks remap surviving anchor IDs. Normal system notices remain visible; internalmodel-state rows do not produce transcript bubbles or search text.+Assistant rows may carry `meta.providerReplay = { version: 1, blocks: [...] }`+(#1972). Each block is `{ type: "thinking", length, signature?, redacted? }` or+`{ type: "text", length, signature? }` in content order; `length` counts UTF-16+units of that block's text inside the row's concatenated `thinking` or answer+text, which are not duplicated here. The signatures are the provider replay+data pi-ai keeps on content blocks (Anthropic thinking signatures and redacted+payloads, Responses reasoning items and message ids, Gemini thought signatures,+Completions reasoning field names). The field is written only when a block+carries one, is never rendered or searched, and needs no migration; older+builds ignore it. When a runtime is rebuilt from the transcript, the row's+blocks are restored with their signatures so the replayed request matches the+live one and keeps the provider prompt cache. If the stored lengths no longer+add up to the row's text, or the reasoning text was cleaned on replay, the row+falls back to the plain thinking-and-text rebuild.+Compaction details may include one `systemMessageJson` checkpoint. It replaces oldsystem updates in the retained tail and is restored before the summary. Theseoptional metadata fields use the existing JSONL/SQLite index and require nodiff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 77023c8c3..dad4655f5 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -810,6 +810,16 @@ meta.agentName?: string // the definition name, e.g. "code-reviewer"无列、无表、无迁移:属性是有关消息的元数据,并且推广它会引起没人提出的疑问。+assistant 行还可以带 `meta.providerReplay = { version: 1, blocks: [...] }`+(#1972)。每个块按内容顺序记录为 `{ type: "thinking", length, signature?, redacted? }`+或 `{ type: "text", length, signature? }`;`length` 是该块文本在行内拼接后的+`thinking` 或正文中的 UTF-16 长度,文本本身不重复保存。签名就是 pi-ai 挂在内容块上+的 provider 回放数据(Anthropic thinking 签名与 redacted 载荷、Responses 的+reasoning item 与 message id、Gemini thought signature、Completions 推理字段名)。+只有块上确实带签名时才写入;不渲染、不参与搜索、无需迁移,旧版本会忽略它。+runtime 从转录重建时按原块和签名还原,使重放请求与在线请求一致,保住 provider 的+prompt cache。长度对不上,或推理文本在回放时被清理过,就退回原来的纯文本重建。+这两个字段都可以在重新加载后保存下来,这就是恢复会话嵌套的原因就像现场一样(`04-ux/08-component-spec.md` §9.9)。两位消费者阅读了它们:diff --git a/packages/agent-runtime/src/assistant-provider-replay.test.ts b/packages/agent-runtime/src/assistant-provider-replay.test.tsnew file mode 100644index 000000000..a96eee989--- /dev/null+++ b/packages/agent-runtime/src/assistant-provider-replay.test.ts@@ -0,0 +1,241 @@+import { describe, expect, it, vi } from "vitest";+import type { Agent } from "@earendil-works/pi-agent-core";+import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";+import type { CommandShellOption, UiMessage } from "@pi-desktop/shared";++import {+ captureAssistantProviderReplay,+ restoreAssistantProviderReplay,+} from "./assistant-provider-replay.js";+import { assistantContent } from "./agent-messages.js";+import { DesktopAgentRuntime, type RuntimeProviderConfig } from "./runtime.js";++/**+ * A rebuilt runtime replays persisted rows. Without the provider signatures,+ * pi-ai sends Anthropic thinking as plain text and drops Responses reasoning+ * items, which rewrites the request prefix and loses the prompt cache (#1972).+ */++const signedContent: AssistantMessage["content"] = [+ { type: "thinking", thinking: "plan A", thinkingSignature: "sig-1" },+ { type: "thinking", thinking: "", thinkingSignature: "opaque", redacted: true },+ { type: "text", text: "Hello ", textSignature: "msg-1" },+ { type: "thinking", thinking: "plan B", thinkingSignature: "sig-2" },+ { type: "text", text: "world" },+];++describe("assistant provider replay", () => {+ it("restores the exact signed blocks from the persisted text", () => {+ const replay = captureAssistantProviderReplay(signedContent);+ const { text, thinking } = assistantContent(signedContent);+ // The row keeps boundaries and signatures only, never the texts.+ expect(JSON.stringify(replay)).not.toContain("plan A");+ expect(restoreAssistantProviderReplay(replay, thinking, text)).toEqual([+ { type: "thinking", thinking: "plan A", thinkingSignature: "sig-1" },+ { type: "thinking", thinking: "", thinkingSignature: "opaque", redacted: true },+ { type: "text", text: "Hello ", textSignature: "msg-1" },+ { type: "thinking", thinking: "plan B", thinkingSignature: "sig-2" },+ { type: "text", text: "world" },+ ]);+ });++ it("records nothing when no block carries a signature", () => {+ expect(+ captureAssistantProviderReplay([+ { type: "thinking", thinking: "plain" },+ { type: "text", text: "answer" },+ ]),+ ).toBeUndefined();+ expect(captureAssistantProviderReplay("text only")).toBeUndefined();+ });++ it("falls back when the stored lengths no longer match the row", () => {+ const replay = captureAssistantProviderReplay(signedContent);+ expect(restoreAssistantProviderReplay(replay, "plan Aplan B", "Hello world!")).toBeUndefined();+ expect(restoreAssistantProviderReplay(replay, "edited", "Hello world")).toBeUndefined();+ expect(restoreAssistantProviderReplay(undefined, "", "")).toBeUndefined();+ expect(restoreAssistantProviderReplay({ version: 2, blocks: [] }, "", "")).toBeUndefined();+ expect(+ restoreAssistantProviderReplay(+ { version: 1, blocks: [{ type: "text", length: -1 }] },+ "",+ "",+ ),+ ).toBeUndefined();+ });+});++const commandShell: CommandShellOption = {+ id: "bash",+ label: "Bash",+ dialect: "posix",+ available: true,+ isDefault: true,+};++const responsesProvider: RuntimeProviderConfig = {+ id: "relay",+ name: "Relay",+ baseUrl: "https://relay.example.com/v1",+ modelId: "gpt-test",+ apiKey: "sk-test",+ authKind: "none",+ supportsReasoning: true,+ supportedThinkingLevels: ["off", "medium"],+ modelConfig: {+ source: "generic",+ api: "responses",+ name: "GPT Test",+ baseUrl: "https://relay.example.com/v1",+ reasoning: true,+ input: ["text"],+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },+ contextWindow: 128_000,+ maxTokens: 8_192,+ },+};++const reasoningItem = {+ type: "reasoning",+ id: "rs_1",+ summary: [{ type: "summary_text", text: "think" }],+ encrypted_content: "enc-1",+};++function historyRow(overrides: Partial<UiMessage> = {}): UiMessage[] {+ const live: AssistantMessage["content"] = [+ { type: "thinking", thinking: "think", thinkingSignature: JSON.stringify(reasoningItem) },+ {+ type: "text",+ text: "answer",+ textSignature: JSON.stringify({ v: 1, id: "msg_real_1" }),+ },+ ];+ return [+ { id: "u1", role: "user", content: "question", createdAt: "2026-01-01T00:00:00.000Z" },+ {+ id: "a1",+ role: "assistant",+ content: "answer",+ thinking: "think",+ createdAt: "2026-01-01T00:00:01.000Z",+ status: "complete",+ providerReplay: captureAssistantProviderReplay(live),+ ...overrides,+ },+ ];+}++function createRuntime(history: UiMessage[], onEvent = vi.fn()) {+ return new DesktopAgentRuntime({+ host: {+ call: vi.fn(async () => ({})),+ onNotification: vi.fn(() => () => {}),+ } as never,+ sessionId: "session-1",+ mode: "agent",+ provider: responsesProvider,+ thinkingLevel: "medium",+ commandShell,+ history,+ onEvent,+ });+}++async function firstRequestInput(history: UiMessage[]): Promise<unknown[]> {+ const runtime = createRuntime(history);+ const internals = runtime as unknown as {+ agent: Agent;+ model: Model<Api>;+ fullEntries: { message: unknown }[];+ };+ const bodies: Record<string, unknown>[] = [];+ const fetch: typeof globalThis.fetch = async (_url, init) => {+ bodies.push(JSON.parse(String(init?.body)) as Record<string, unknown>);+ return new Response(JSON.stringify({ error: { message: "fixture" } }), {+ status: 401,+ headers: { "content-type": "application/json" },+ });+ };+ const messages = [+ ...internals.fullEntries.map((entry) => entry.message),+ { role: "user", content: "next", timestamp: 2 },+ ];+ const stream = await internals.agent.streamFunction(+ internals.model,+ { messages } as never,+ { apiKey: "sk-test", fetch },+ );+ // The fixture fails the request; only the captured body is under test.+ await stream.result().catch(() => undefined);+ await runtime.dispose();+ expect(bodies).toHaveLength(1);+ return bodies[0].input as unknown[];+}++describe("rebuilt runtime request", () => {+ it("replays the persisted reasoning item and message id", async () => {+ const input = await firstRequestInput(historyRow());+ expect(input).toContainEqual(expect.objectContaining({ type: "reasoning", id: "rs_1", encrypted_content: "enc-1" }));+ expect(input).toContainEqual(expect.objectContaining({ type: "message", role: "assistant", id: "msg_real_1" }));+ });++ it("keeps the previous rebuild for rows without replay data", async () => {+ const input = await firstRequestInput(historyRow({ providerReplay: undefined }));+ expect(input.some((item) => (item as { type?: string }).type === "reasoning")).toBe(false);+ expect(input).toContainEqual(expect.objectContaining({ type: "message", role: "assistant", id: "msg_pi_1" }));+ });+});++describe("live response to rebuilt request", () => {+ it("persists the replay data a later runtime needs", async () => {+ const onEvent = vi.fn();+ const live = createRuntime([], onEvent);+ const handleAgentEvent = (live as unknown as {+ handleAgentEvent: (event: unknown) => Promise<void>;+ }).handleAgentEvent.bind(live);+ const message = {+ role: "assistant",+ content: [] as AssistantMessage["content"],+ api: "openai-responses",+ provider: "relay",+ model: "gpt-test",+ usage: {+ input: 1,+ output: 1,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 2,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: "stop",+ timestamp: 1,+ };+ await handleAgentEvent({ type: "message_start", message });+ await handleAgentEvent({+ type: "message_end",+ message: {+ ...message,+ content: [+ { type: "thinking", thinking: "think", thinkingSignature: JSON.stringify(reasoningItem) },+ { type: "text", text: "answer", textSignature: JSON.stringify({ v: 1, id: "msg_real_1" }) },+ ],+ },+ });+ await live.dispose();++ const ended = onEvent.mock.calls+ .map(([envelope]) => (envelope as { event: { type: string; message?: UiMessage } }).event)+ .find((event) => event.type === "message_end" && event.message?.role === "assistant");+ expect(ended?.message?.providerReplay).toBeDefined();++ // What the host stores is JSON; restore from that, not the live object.+ const persisted = JSON.parse(JSON.stringify(ended?.message)) as UiMessage;+ const input = await firstRequestInput([+ { id: "u1", role: "user", content: "question", createdAt: "2026-01-01T00:00:00.000Z" },+ persisted,+ ]);+ expect(input).toContainEqual(expect.objectContaining({ type: "reasoning", encrypted_content: "enc-1" }));+ expect(input).toContainEqual(expect.objectContaining({ type: "message", role: "assistant", id: "msg_real_1" }));+ });+});diff --git a/packages/agent-runtime/src/assistant-provider-replay.ts b/packages/agent-runtime/src/assistant-provider-replay.tsnew file mode 100644index 000000000..a02cc33f1--- /dev/null+++ b/packages/agent-runtime/src/assistant-provider-replay.ts@@ -0,0 +1,150 @@+/**+ * Provider replay metadata for persisted assistant rows (#1972).+ *+ * pi-ai keeps provider signatures on assistant content blocks: Anthropic+ * thinking signatures and redacted payloads, Responses encrypted reasoning+ * items and message ids, Gemini thought signatures, and the reasoning field+ * name for Completions models. A transcript row only stores the concatenated+ * thinking and answer text, so a rebuilt runtime used to replay history+ * without them. pi-ai then sends the thinking as plain text or drops it, which+ * changes the request prefix and invalidates the provider's prompt cache from+ * the first reasoning turn onward.+ *+ * The row keeps block boundaries and signatures only; the texts stay in+ * `thinking` and `content`. Restoring is all-or-nothing: if the stored lengths+ * no longer add up to the row's text, the caller keeps its plain rebuild.+ */+import type { AssistantMessage } from "@earendil-works/pi-ai";+import type {+ AssistantProviderReplay,+ AssistantProviderReplayBlock,+} from "@pi-desktop/shared";++type ReplayContent = Extract<+ AssistantMessage["content"][number],+ { type: "thinking" } | { type: "text" }+>;++function nonEmpty(value: unknown): string | undefined {+ return typeof value === "string" && value.length > 0 ? value : undefined;+}++/**+ * Record the thinking/text block boundaries and signatures of a finished+ * assistant message. Returns undefined when no block carries anything to+ * replay, so ordinary rows stay unchanged on disk.+ */+export function captureAssistantProviderReplay(+ content: unknown,+): AssistantProviderReplay | undefined {+ if (!Array.isArray(content)) return undefined;+ const blocks: AssistantProviderReplayBlock[] = [];+ let carriesReplay = false;+ for (const part of content) {+ if (!part || typeof part !== "object") continue;+ const block = part as {+ type?: unknown;+ text?: unknown;+ thinking?: unknown;+ thinkingSignature?: unknown;+ textSignature?: unknown;+ redacted?: unknown;+ };+ if (block.type === "thinking") {+ // Mirrors assistantContent(): adapters may expose thinking as `text`.+ const text = typeof block.thinking === "string"+ ? block.thinking+ : typeof block.text === "string"+ ? block.text+ : "";+ const signature = nonEmpty(block.thinkingSignature);+ const redacted = block.redacted === true;+ if (signature || redacted) carriesReplay = true;+ blocks.push({+ type: "thinking",+ length: text.length,+ ...(signature ? { signature } : {}),+ ...(redacted ? { redacted: true as const } : {}),+ });+ } else if (block.type === "text" && typeof block.text === "string") {+ const signature = nonEmpty(block.textSignature);+ if (signature) carriesReplay = true;+ blocks.push({+ type: "text",+ length: block.text.length,+ ...(signature ? { signature } : {}),+ });+ }+ }+ return carriesReplay ? { version: 1, blocks } : undefined;+}++function validBlocks(replay: unknown): AssistantProviderReplayBlock[] | undefined {+ if (!replay || typeof replay !== "object") return undefined;+ const { version, blocks } = replay as { version?: unknown; blocks?: unknown };+ if (version !== 1 || !Array.isArray(blocks)) return undefined;+ for (const block of blocks) {+ if (!block || typeof block !== "object") return undefined;+ const { type, length, signature } = block as {+ type?: unknown;+ length?: unknown;+ signature?: unknown;+ };+ if (type !== "thinking" && type !== "text") return undefined;+ if (typeof length !== "number" || !Number.isInteger(length) || length < 0) {+ return undefined;+ }+ if (signature !== undefined && typeof signature !== "string") return undefined;+ }+ return blocks as AssistantProviderReplayBlock[];+}++/**+ * Rebuild the thinking/text blocks of a persisted assistant row with their+ * original boundaries and signatures. Returns undefined when the stored+ * replay is missing, malformed, or no longer matches the row's text.+ */+export function restoreAssistantProviderReplay(+ replay: unknown,+ thinking: string,+ text: string,+): ReplayContent[] | undefined {+ const blocks = validBlocks(replay);+ if (!blocks) return undefined;+ let thinkingLength = 0;+ let textLength = 0;+ for (const block of blocks) {+ if (block.type === "thinking") thinkingLength += block.length;+ else textLength += block.length;+ }+ if (thinkingLength !== thinking.length || textLength !== text.length) {+ return undefined;+ }+ const restored: ReplayContent[] = [];+ let thinkingOffset = 0;+ let textOffset = 0;+ for (const block of blocks) {+ if (block.type === "thinking") {+ const slice = thinking.slice(thinkingOffset, thinkingOffset + block.length);+ thinkingOffset += block.length;+ // An empty unsigned block carries nothing a provider could use.+ if (!slice && !block.signature && !block.redacted) continue;+ restored.push({+ type: "thinking",+ thinking: slice,+ ...(block.signature ? { thinkingSignature: block.signature } : {}),+ ...(block.redacted ? { redacted: true } : {}),+ });+ } else {+ const slice = text.slice(textOffset, textOffset + block.length);+ textOffset += block.length;+ if (!slice && !block.signature) continue;+ restored.push({+ type: "text",+ text: slice,+ ...(block.signature ? { textSignature: block.signature } : {}),+ });+ }+ }+ return restored;+}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex dcf8e6b2b..384ebdd4a 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -134,6 +134,10 @@ import { createStreamCoalescer, type StreamCoalescer } from "./stream-coalescer.import { checkGenUiFragment, genUiFragmentCheckNote, isGenUiFragmentPath } from "./gen-ui-fragment-check.js";import type { RuntimeHost } from "./host-client.js";import { classifyAgentError } from "./agent-errors.js";+import {+ captureAssistantProviderReplay,+ restoreAssistantProviderReplay,+} from "./assistant-provider-replay.js";import {assistantContent,isRecord,@@ -3177,21 +3181,35 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst content: AssistantMessage["content"] = [];// A replay placeholder the model echoed is not its reasoning; sending// it back is what kept the model continuing it (#1945).- const thinking = withoutReasoningReplayPlaceholder(m.thinking ?? "");- if (thinking.trim()) {- // Completions DeepSeek replay needs thinkingSignature so convertMessages- // maps the block to reasoning_content instead of dropping it (#296).- content.push({- type: "thinking" as const,- thinking,- ...(deepSeekCompletionsReplay- ? { thinkingSignature: "reasoning_content" as const }- : {}),- });- }- content.push(...restoreHostedSearchReplay(m.hostedSearch));- if (m.content?.trim()) {- content.push({ type: "text" as const, text: m.content });+ const rawThinking = m.thinking ?? "";+ const thinking = withoutReasoningReplayPlaceholder(rawThinking);+ // Signed blocks restore the request the live runtime sent, so a+ // rebuild keeps the provider's prompt cache (#1972). Rows that were+ // cleaned above, or whose text no longer matches, keep the plain path.+ const replayed = thinking === rawThinking+ ? restoreAssistantProviderReplay(m.providerReplay, rawThinking, m.content ?? "")+ : undefined;+ if (replayed) {+ const firstText = replayed.findIndex((block) => block.type === "text");+ const hosted = restoreHostedSearchReplay(m.hostedSearch);+ if (firstText < 0) content.push(...replayed, ...hosted);+ else content.push(...replayed.slice(0, firstText), ...hosted, ...replayed.slice(firstText));+ } else {+ if (thinking.trim()) {+ // Completions DeepSeek replay needs thinkingSignature so convertMessages+ // maps the block to reasoning_content instead of dropping it (#296).+ content.push({+ type: "thinking" as const,+ thinking,+ ...(deepSeekCompletionsReplay+ ? { thinkingSignature: "reasoning_content" as const }+ : {}),+ });+ }+ content.push(...restoreHostedSearchReplay(m.hostedSearch));+ if (m.content?.trim()) {+ content.push({ type: "text" as const, text: m.content });+ }}// Kept even when empty: a call-only turn has no text of its own and// becomes the carrier for the tool rows that follow. Assistants that@@ -8688,7 +8706,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the? { error: classifiedError, isError: true }: {}),...(hostedSearch ? { hostedSearch } : {}),+ // Signatures only describe this response's own blocks. A bubble+ // that kept text from an earlier recovery attempt no longer lines+ // up with them, so it is persisted without replay data.+ providerReplay:+ !failed && nextText === content.text && nextThinking === content.thinking+ ? captureAssistantProviderReplay((event.message as any).content)+ : undefined,};+ if (!this.currentAssistant.providerReplay) delete this.currentAssistant.providerReplay;this.emit({ type: "message_end", message: this.currentAssistant });this.activeProviderRetryAttempt = 0;this.streamStartedAt = undefined;diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex c12fe1a0c..f9cd95d90 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -170,8 +170,30 @@ export type UiMessage = {* searched.*/hostedSearch?: HostedSearch;+ /**+ * Opaque provider replay data for an assistant row: the signatures pi-ai+ * keeps on thinking/text blocks. Never shown; the runtime uses it to send a+ * restored history byte-for-byte as the live one, so a rebuilt runtime keeps+ * the prompt cache and the model's own reasoning.+ */+ providerReplay?: AssistantProviderReplay;};+/**+ * Per-block replay metadata for one assistant message, in content order.+ * `length` is the UTF-16 length of the block's text; the texts themselves are+ * already stored as `thinking` and `content` (concatenated), so only the+ * boundaries and signatures are kept here.+ */+export type AssistantProviderReplay = {+ version: 1;+ blocks: AssistantProviderReplayBlock[];+};++export type AssistantProviderReplayBlock =+ | { type: "thinking"; length: number; signature?: string; redacted?: true }+ | { type: "text"; length: number; signature?: string };+/*** Normalized provider-hosted web search activity for one assistant message.* One message can run several search rounds server-side; each round is one