Skip to content

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

fix(agent-runtime): recover sessions after malformed tool calls

Linuxdazhao051aceff7e25
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 1aa790497..31c8eb26f 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -236,6 +236,24 @@ removes any trailing assistant rows if present, but does not require an
assistant message at the transcript tail before calling `continue()` (issue
#1768).
+Complete assistant responses are checked for malformed tool calls before any
+call in that response can execute. Missing or blank names/IDs, an empty
+Responses wire ID, and non-JSON-object arguments produce the existing terminal
+local `context-validation` error. The unexecuted batch is excluded from model
+context; visible text/thinking and the error remain available in the transcript.
+This does not guess a tool identity, repair arguments into an executable call,
+or spend the transport retry budget. Ordinary tool-schema failures still return
+tool feedback through Pi's existing validation path.
+
+Continue must also recover a runtime retained from an earlier failure. Model
+context projection removes malformed tool calls and their associated results,
+including retained compaction tails and resumed delegates, while preserving
+valid sibling calls/results, system updates, user messages and useful assistant
+content. The durable transcript is unchanged and completed tools are not
+re-executed. Other malformed context remains subject to strict validation.
+Tool token estimates are optional telemetry: an invalid call identity must not
+prevent the corresponding terminal tool event from being delivered.
+
Before surfacing a pre-stream `PROVIDER_ERROR` for HTTP 400/422 whose message
ends in `(no body)`, the runtime makes at most one silent repair attempt with
the generated output-limit fields removed: `max_tokens`,
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d2bf1b3cd..3f6f13ae5 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -10536,6 +10536,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| Acceptance | Scenarios |
|---|---|
| C / E / Security / Quality — Gemini work setup | E2E-LIVE-VOICE-gemini-work-schema |
+| C / Quality — Continue after malformed tool output | E2E-RUNTIME-malformed-tool-call-continue-recovery |
| B / Security / Quality — Optional provider client certificate requests | E2E-PROVIDER-optional-client-certificate |
| C / E / F / Quality / Security — Session Todo checklist | E2E-CHAT-session-todo-checklist |
| C / E / Security / Quality — Live Voice four-stage interaction | E2E-LIVE-VOICE-four-stage-ui |
@@ -18993,3 +18994,32 @@ their separate platform acceptance.
stubbed). Rust provider tests independently verify real SQLite persistence;
`provider-reasoning-effort.test.ts` captures requests from the real pi-ai
adapter with fixture SSE responses. No live gateway credentials are required.
+
+
+#### E2E-RUNTIME-malformed-tool-call-continue-recovery: Continue after malformed tool output
+
+- **Preconditions**: An isolated sidecar and loopback Responses fixture can
+ emit an empty tool name, then a corrected Read call. Unit fixtures also
+ cover missing names/IDs, empty Responses wire IDs, non-object arguments,
+ retained malformed context, compaction tails and resumed delegates.
+- **Steps**: Return one malformed response, then invoke the same `agent.prompt`
+ entry used by Continue three times. Repeat with three consecutive malformed
+ responses followed by a corrected response. Keep the runtime alive throughout.
+- **Expected**: Each malformed batch settles with one local
+ `context-validation` error before tool execution, with no transport retry.
+ All three later prompts complete; the corrected Read executes once, and the
+ runtime is reused rather than restarted. Model context retains valid history
+ and system updates while excluding malformed calls and associated results.
+ Optional usage estimation does not lose terminal tool events. The durable
+ transcript and Host permissions are unchanged; unrelated malformed hosted
+ search still fails strict validation.
+- **Specs linked**: `03-runtime/02-agent-runtime.md` §5d.
+- **Acceptance**: Conversation, runtime recovery and quality.
+- **Milestone**: M5 hardening.
+- **Automation**: `pnpm test:e2e:hosted-search` runs the production sidecar and
+ real Responses adapter against synthetic SSE, including one-error and
+ three-error recovery cases. `malformed-tool-recovery.test.ts`,
+ `tool-call-identity.test.ts` and `subagent.test.ts` cover retained state,
+ event/result agreement, batch rejection and delegate restoration.
+- **Status**: Automated offline; native UI clicking and live providers are
+ outside this fixture's coverage.
diff --git a/packages/agent-runtime/src/malformed-tool-recovery.test.ts b/packages/agent-runtime/src/malformed-tool-recovery.test.ts
new file mode 100644
index 000000000..0e42e6cf8
--- /dev/null
+++ b/packages/agent-runtime/src/malformed-tool-recovery.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it, vi } from "vitest";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { createAssistantMessageEventStream, type AssistantMessage } from "@earendil-works/pi-ai";
+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";
+import type { AgentEventEnvelope } from "@pi-desktop/shared";
+import { buildSessionContext } from "./session-context.js";
+import { recoverMalformedToolCalls } from "./tool-call-recovery.js";
+import type { CompactionEntry } from "./pi-runtime-types.js";
+import { convertToLlm } from "./pi-runtime-messages.js";
+import { DesktopAgentRuntime } from "./runtime.js";
+
+function assistant(content: unknown[], stopReason = "toolUse"): AssistantMessage {
+ return {
+ role: "assistant", content, api: "openai-completions", provider: "fixture", model: "fixture",
+ stopReason, timestamp: Date.now(),
+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ } as AssistantMessage;
+}
+
+const call = (id = "valid-call") => ({ type: "toolCall", id, name: "Bash", arguments: { command: "printf checked" } });
+const answer = () => assistant([{ type: "text", text: "The requested check is complete." }], "stop");
+
+function fixture(reply: (round: number) => AssistantMessage) {
+ const requests: AgentMessage[][] = [];
+ const events: AgentEventEnvelope["event"][] = [];
+ const host = { call: vi.fn(async (method: string) => method === "tools.execute"
+ ? { ok: true, content: { content: [{ type: "text", text: "checked" }], details: {} } }
+ : undefined) };
+ const runtime = new DesktopAgentRuntime({
+ sessionId: "malformed-call-fixture", mode: "agent", thinkingLevel: "off", host: host as never,
+ provider: { id: "fixture", name: "Fixture", modelId: "fixture", apiKey: "fixture", baseUrl: "http://localhost/v1",
+ supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ history: [{ id: "earlier-user", role: "user", content: "Keep the completed work.", createdAt: new Date(1).toISOString() }],
+ onEvent: (envelope) => events.push(envelope.event),
+ });
+ vi.spyOn(runtime["models"], "streamSimple").mockImplementation((_model, context) => {
+ requests.push(structuredClone(context.messages));
+ if (requests.length > 6) throw new Error("Unexpected extra provider request");
+ validateHostedSearchMessages(context.messages);
+ const message = reply(requests.length);
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: message });
+ stream.push({ type: "done", reason: message.stopReason as "stop" | "toolUse", message });
+ stream.end(message);
+ });
+ return stream;
+ });
+ return { runtime, host, requests, events };
+}
+
+describe("malformed tool-call recovery", () => {
+ it.each([
+ ["empty name", { name: "" }],
+ ["missing name", { name: undefined }],
+ ["empty id", { id: "" }],
+ ["missing id", { id: undefined }],
+ ["empty wire id", { id: "|item-1" }],
+ ["non-object arguments", { arguments: [] }],
+ ])("rejects a response with %s before execution and accepts three subsequent prompts", async (_label, invalid) => {
+ const { runtime, host, requests, events } = fixture((round) => round === 1
+ ? assistant([call("withheld-call"), { ...call("bad-call"), ...invalid }])
+ : round === 2 ? assistant([call("corrected-call")]) : answer());
+ try {
+ await runtime.prompt("Run the check.");
+ expect(requests).toHaveLength(1);
+ expect(host.call.mock.calls.filter(([method]) => method === "tools.execute")).toHaveLength(0);
+ expect(events).toContainEqual(expect.objectContaining({ type: "error", error: expect.objectContaining({
+ details: { origin: "local", phase: "context-validation" },
+ }) }));
+ expect(events.filter((event) => event.type === "tool_start")).toHaveLength(0);
+ for (let attempt = 0; attempt < 3; attempt++) await runtime.prompt("Continue the current task.");
+ expect(requests).toHaveLength(5);
+ expect(host.call.mock.calls.filter(([method]) => method === "tools.execute")).toHaveLength(1);
+ expect(runtime["agent"].state.messages.at(-1)).toMatchObject({ stopReason: "stop" });
+ expect(JSON.stringify(requests.slice(1))).toContain("Keep the completed work.");
+ expect(JSON.stringify(requests.slice(1))).not.toContain("withheld-call");
+ } finally { await runtime.dispose(); }
+ });
+
+ it("bounds persistent malformed responses and recovers when a later manual prompt gets a valid response", async () => {
+ const { runtime, requests, events } = fixture((round) => round <= 3
+ ? assistant([{ ...call(), name: "" }]) : answer());
+ try {
+ for (let attempt = 1; attempt <= 3; attempt++) {
+ await runtime.prompt("Continue the current task.");
+ expect(requests).toHaveLength(attempt);
+ expect(runtime.getStatus().isRunning).toBe(false);
+ }
+ await runtime.prompt("Continue the current task.");
+ expect(requests).toHaveLength(4);
+ expect(events.filter((event) => event.type === "error")).toHaveLength(3);
+ expect(runtime["agent"].state.messages.at(-1)).toMatchObject({ stopReason: "stop" });
+ } finally { await runtime.dispose(); }
+ });
+
+ it("continues a previously poisoned runtime without replaying completed sibling tools", async () => {
+ const { runtime, host, requests } = fixture(answer);
+ const completed = assistant([
+ { type: "text", text: "Keep this useful response." },
+ call("completed-call"), { ...call("bad-call"), name: "" },
+ ]);
+ const goodResult: AgentMessage = { role: "toolResult", toolCallId: "completed-call", toolName: "Bash",
+ content: [{ type: "text", text: "Completed exactly once." }], timestamp: Date.now(), isError: false };
+ const badResult: AgentMessage = { ...goodResult, toolCallId: "bad-call", toolName: "", isError: true };
+ for (const [id, message] of [["poisoned-assistant", completed], ["completed-call", goodResult], ["bad-call", badResult]] as const) {
+ runtime["appendLiveEntry"](id, message);
+ runtime["agent"].state.messages.push(message);
+ }
+ const original = structuredClone(completed);
+ try {
+ const failures: string[] = [];
+ for (let attempt = 0; attempt < 3; attempt++) {
+ try { await runtime.prompt("Continue the current task."); }
+ catch (error) { failures.push(error instanceof Error ? error.message : String(error)); }
+ }
+ expect(failures).toEqual([]);
+ expect(requests).toHaveLength(3);
+ expect(host.call.mock.calls.filter(([method]) => method === "tools.execute")).toHaveLength(0);
+ expect(requests[0]).toContainEqual(goodResult);
+ expect(JSON.stringify(requests)).toContain("Keep this useful response.");
+ expect(JSON.stringify(requests)).not.toContain("bad-call");
+ expect(completed).toEqual(original);
+ } finally { await runtime.dispose(); }
+ });
+
+ it("settles an invalid tool event even when token usage cannot be estimated", async () => {
+ const { runtime, events } = fixture(answer);
+ try {
+ await runtime["handleAgentEvent"]({ type: "tool_execution_start", toolCallId: "bad-call", toolName: "", args: {} });
+ await runtime["handleAgentEvent"]({ type: "tool_execution_end", toolCallId: "bad-call", toolName: "",
+ result: { content: [{ type: "text", text: "Unknown tool" }], details: {} }, isError: true });
+ expect(events).toContainEqual(expect.objectContaining({ type: "tool_end", toolCallId: "bad-call", isError: true }));
+ } finally { await runtime.dispose(); }
+ });
+
+ it("recovers a compaction tail while preserving system updates and a valid same-id sibling", () => {
+ const system: AgentMessage = { role: "system", content: "Keep the host's instructions.", timestamp: 1 };
+ const retained = assistant([
+ { type: "text", text: "Keep the earlier findings." },
+ { ...call("shared|fc_read"), name: "Read", arguments: { path: "notes.txt" } },
+ { ...call("shared|fc_bash"), arguments: [] },
+ ]);
+ const goodResult: AgentMessage = { role: "toolResult", toolCallId: "shared|fc_read", toolName: "Read",
+ content: [{ type: "text", text: "Useful evidence." }], timestamp: 2, isError: false };
+ const badResult: AgentMessage = { ...goodResult, toolCallId: "shared", toolName: "Bash", isError: true };
+ const entry: CompactionEntry = { type: "compaction", id: "compacted", parentId: null, seq: 3, timestamp: 3,
+ summary: "Earlier work", tokensBefore: 100, retainedTail: [system, retained, goodResult, badResult], fromHook: false };
+ const original = structuredClone(entry);
+ const messages = buildSessionContext([entry]).messages;
+ expect(messages.map((message) => message.role)).toEqual(["compactionSummary", "system", "assistant", "toolResult"]);
+ expect(messages).toContain(system);
+ expect(messages).toContain(goodResult);
+ expect(messages).not.toContain(badResult);
+ expect(messages[2]).toMatchObject({ content: [
+ { type: "text", text: "Keep the earlier findings." },
+ { type: "toolCall", id: "shared|fc_read", name: "Read" },
+ ] });
+ expect(() => validateHostedSearchMessages(convertToLlm(messages))).not.toThrow();
+ expect(entry).toEqual(original);
+ });
+
+ it("keeps a later completed execution that reuses a rejected call's identity", () => {
+ const invalid = assistant([{ ...call("reused|fc_bad"), arguments: [] }]);
+ const valid = assistant([call("reused|fc_good")]);
+ const result: AgentMessage = { role: "toolResult", toolCallId: "reused", toolName: "Bash",
+ content: [{ type: "text", text: "Completed." }], timestamp: 2, isError: false };
+ expect(recoverMalformedToolCalls([invalid, { ...result, isError: true }, valid, result])).toEqual([valid, result]);
+ });
+
+ it("keeps unrelated malformed context subject to strict validation", () => {
+ const messages = [assistant([{ type: "hostedSearch", phase: "web_search_call" }, call()])];
+ expect(recoverMalformedToolCalls(messages)).toBe(messages);
+ expect(() => validateHostedSearchMessages(messages)).toThrow("Local request context validation failed");
+ });
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index de76a8001..d2808875b 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -14,6 +14,7 @@ import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } fro
import { restoreHostedSearchReplay } from "./hosted-search-replay.js";
import { requestExtensionUi } from "./extensions/ui-request.js";
import { readLocalRequestErrorDetails } from "./local-request-errors.js";
+import { isValidToolCall, recoverMalformedToolCalls } from "./tool-call-recovery.js";
import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { todoWriteDescription, todoWriteParameters } from "./todo-tool.js";
import { createJevClassifierTool } from "./jev-classifier-tool.js";
@@ -1748,7 +1749,7 @@ function estimateToolTokenUsage(
result: unknown,
isError: boolean,
timestamp: number,
-): ToolTokenUsage {
+): ToolTokenUsage | undefined {
const toolCall = {
role: "assistant" as const,
content: [
@@ -1766,6 +1767,8 @@ function estimateToolTokenUsage(
stopReason: "toolUse" as const,
timestamp,
} satisfies AssistantMessage;
+ // Optional telemetry must not suppress a terminal tool event.
+ if (!isValidToolCall(toolCall.content[0])) return undefined;
const toolRow = {
id: toolCallId,
role: "tool" as const,
@@ -9076,6 +9079,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
this.pendingUserMessageId = userMessageId;
this.resetRunRecoveryState();
this.autonomousExecution = false;
+ const recovered = recoverMalformedToolCalls(this.agent.state.messages);
+ if (recovered !== this.agent.state.messages) this.setAgentMessages(recovered);
// Main resolves this provenance from the Host ledger. Never infer it from
// prompt text, model output, extension content, or restored history.
const origin = typeof input === "string" ? undefined : input.sessionMessage;
diff --git a/packages/agent-runtime/src/session-context.ts b/packages/agent-runtime/src/session-context.ts
index d930c55be..0036efa44 100644
--- a/packages/agent-runtime/src/session-context.ts
+++ b/packages/agent-runtime/src/session-context.ts
@@ -1,4 +1,5 @@
import { readSystemMessage } from "./system-transcript-journal.js";
+import { recoverMalformedToolCalls } from "./tool-call-recovery.js";
/**
* Project pi session entries into the model context.
*
@@ -98,8 +99,8 @@ export function buildSessionContext(
messages: AgentMessage[];
} {
return {
- messages: buildContextEntries(pathEntries).flatMap((entry) =>
+ messages: recoverMalformedToolCalls(buildContextEntries(pathEntries).flatMap((entry) =>
sessionEntryToContextMessages(entry, identity),
- ),
+ )),
};
}
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index 5a245b08c..1f414d152 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -4,7 +4,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { Type } from "typebox";
import type { AgentEventEnvelope, SubagentDefinition } from "@pi-desktop/shared";
-import type { Message } from "@earendil-works/pi-ai";
+import { createAssistantMessageEventStream, type Message } from "@earendil-works/pi-ai";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
import {
composeSubagentSystemPrompt,
MAX_SUBAGENT_REPORT_CHARS,
@@ -195,6 +196,30 @@ describe("composeSubagentSystemPrompt", () => {
});
describe("SubagentRun event forwarding", () => {
+ it("resumes a malformed-call history without executing its old tools", async () => {
+ const { run } = createRun({ initialMessages: [assistantMessage({ content: [
+ { type: "text", text: "Retained findings." },
+ { type: "toolCall", id: "bad-call", name: "", arguments: {} },
+ ] })] as AgentMessage[] });
+ const requests: Message[][] = [];
+ run.agent.streamFunction = (_model: unknown, context: { messages: Message[] }) => {
+ requests.push(context.messages);
+ const message = assistantMessage({ content: [{ type: "text", text: "Finished the review." }], stopReason: "stop" });
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: message } as never);
+ stream.push({ type: "done", reason: "stop", message } as never);
+ stream.end(message as never);
+ });
+ return stream;
+ };
+ const result = await run.run();
+ expect(result.status).toBe("completed");
+ expect(requests).toHaveLength(1);
+ expect(JSON.stringify(requests)).toContain("Retained findings.");
+ expect(JSON.stringify(requests)).not.toContain("bad-call");
+ });
+
it("keeps the no-pass selection out of the agent's canonical state", () => {
const { run } = createRun({ thinkingLevel: "omit" });
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index e6975acb3..32e308706 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -52,6 +52,7 @@ import {
} from "@pi-desktop/shared";
import { classifyAgentError } from "./agent-errors.js";
import { readLocalRequestErrorDetails } from "./local-request-errors.js";
+import { recoverMalformedToolCalls } from "./tool-call-recovery.js";
import { withProviderFetchFailure } from "./provider-transport-recovery.js";
import {
assistantContent,
@@ -282,7 +283,8 @@ export class SubagentRun {
constructor(opts: SubagentRunOptions) {
this.opts = opts;
- this.uniqueToolCalls = createToolCallIdentity(opts.initialMessages ?? []);
+ const initialMessages = recoverMalformedToolCalls(opts.initialMessages ?? []);
+ this.uniqueToolCalls = createToolCallIdentity(initialMessages);
this.provider = opts.provider;
this.thinkingLevel = opts.thinkingLevel;
this.attemptedModels.add(`${opts.provider.id}/${opts.provider.modelId}`);
@@ -317,7 +319,7 @@ export class SubagentRun {
),
),
thinkingLevel: binding.agentThinkingLevel,
- messages: initialSystemTranscript(opts.systemPrompt, opts.tools, opts.initialMessages ? [...opts.initialMessages] : []),
+ messages: initialSystemTranscript(opts.systemPrompt, opts.tools, [...initialMessages]),
},
toolExecution: "parallel",
});
diff --git a/packages/agent-runtime/src/tool-call-dedupe.ts b/packages/agent-runtime/src/tool-call-dedupe.ts
index 8cb18140d..d6c1e8f9e 100644
--- a/packages/agent-runtime/src/tool-call-dedupe.ts
+++ b/packages/agent-runtime/src/tool-call-dedupe.ts
@@ -1,5 +1,6 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { AssistantMessage, AssistantMessageEventStream } from "@earendil-works/pi-ai";
+import { rejectMalformedToolCalls } from "./tool-call-recovery.js";
type RecordLike = Record<string, unknown>;
@@ -62,6 +63,7 @@ export function createToolCallIdentity(initialHistory: readonly unknown[] = []):
for (const id of callIdsIn(history)) seenIds.add(id);
const previousIds = new Set(seenIds);
const normalize = (message: AssistantMessage): AssistantMessage => {
+ message = rejectMalformedToolCalls(message);
if (message.stopReason === "error" || message.stopReason === "aborted") return message;
const used = new Set(previousIds);
const freshId = idAllocator([...previousIds, ...callIdsIn([message])]);
@@ -82,7 +84,11 @@ export function createToolCallIdentity(initialHistory: readonly unknown[] = []):
if (property === "result") return async () => normalize(await target.result());
if (property === Symbol.asyncIterator) return async function* () {
for await (const event of target) {
- yield event.type === "done" ? { ...event, message: normalize(event.message) } : event;
+ if (event.type !== "done") { yield event; continue; }
+ const message = normalize(event.message);
+ yield message.stopReason === "error"
+ ? { type: "error", reason: "error", error: message }
+ : { ...event, message };
}
};
return Reflect.get(target, property, receiver);
diff --git a/packages/agent-runtime/src/tool-call-identity.test.ts b/packages/agent-runtime/src/tool-call-identity.test.ts
index f8890159e..cdb301fc6 100644
--- a/packages/agent-runtime/src/tool-call-identity.test.ts
+++ b/packages/agent-runtime/src/tool-call-identity.test.ts
@@ -123,4 +123,24 @@ describe("tool execution identity", () => {
for await (const event of wrappedErrors) expect(event).toBe(errorEvent);
expect(await wrappedErrors.result()).toBe(failed);
});
+
+ it("exposes the same rejected batch through the terminal event and result", async () => {
+ const original = message(["valid", ""]);
+ original.content.unshift({ type: "text", text: "Retain this explanation." });
+ const snapshot = structuredClone(original);
+ const stream = createAssistantMessageEventStream();
+ const wrapped = createToolCallIdentity()(stream, []);
+ stream.push({ type: "done", reason: "toolUse", message: original });
+ stream.end(original);
+ const events = [];
+ for await (const event of wrapped) events.push(event);
+ const result = await wrapped.result();
+ expect(events).toEqual([{ type: "error", reason: "error", error: result }]);
+ expect(result).toMatchObject({
+ content: [{ type: "text", text: "Retain this explanation." }], stopReason: "error",
+ errorDetails: { code: "LOCAL_REQUEST_ERROR", phase: "context-validation" },
+ });
+ expect(await wrapped.result()).toEqual(result);
+ expect(original).toEqual(snapshot);
+ });
});
diff --git a/packages/agent-runtime/src/tool-call-recovery.ts b/packages/agent-runtime/src/tool-call-recovery.ts
new file mode 100644
index 000000000..fb84ab6c1
--- /dev/null
+++ b/packages/agent-runtime/src/tool-call-recovery.ts
@@ -0,0 +1,73 @@
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { LocalRequestError, localRequestErrorDetails, type AssistantMessage, type ToolCall } from "@earendil-works/pi-ai";
+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";
+
+function wireId(id: unknown): string | undefined {
+ return typeof id === "string" ? id.split("|", 1)[0] : undefined;
+}
+
+function validIdentity(id: unknown, name: unknown): boolean {
+ return Boolean(wireId(id)?.trim()) &&
+ typeof name === "string" && name.trim().length > 0;
+}
+
+export function isValidToolCall(call: ToolCall): boolean {
+ if (!validIdentity(call.id, call.name)) return false;
+ try {
+ validateHostedSearchMessages([{ role: "assistant", content: [call] } as AssistantMessage]);
+ return true;
+ } catch (error) {
+ if (!localRequestErrorDetails(error)) throw error;
+ return false;
+ }
+}
+
+/** Reject the whole unexecuted batch, without inventing a tool name, id or arguments. */
+export function rejectMalformedToolCalls(message: AssistantMessage): AssistantMessage {
+ if (message.stopReason === "error" || message.stopReason === "aborted" ||
+ !message.content.some((block) => block.type === "toolCall" && !isValidToolCall(block))) return message;
+ const error = new LocalRequestError("context-validation");
+ return {
+ ...message,
+ content: message.content.filter((block) => block.type !== "toolCall"),
+ stopReason: "error",
+ errorMessage: error.message,
+ errorDetails: localRequestErrorDetails(error),
+ };
+}
+
+/** Repair only the model projection; preserve the transcript and completed sibling calls. */
+export function recoverMalformedToolCalls(messages: AgentMessage[]): AgentMessage[] {
+ const rejected = new Map<string | undefined, Set<unknown>>();
+ let changed = false;
+ const recovered: AgentMessage[] = [];
+ for (const message of messages) {
+ if (message.role === "assistant" && Array.isArray(message.content)) {
+ const content = message.content.filter((block) => {
+ if (block.type !== "toolCall") return true;
+ const id = wireId(block.id);
+ if (isValidToolCall(block)) {
+ rejected.get(id)?.delete(block.name);
+ return true;
+ }
+ const names = rejected.get(id) ?? new Set<unknown>();
+ names.add(block.name);
+ rejected.set(id, names);
+ return false;
+ });
+ if (content.length !== message.content.length) {
+ changed = true;
+ if (content.length) recovered.push({ ...message, content });
+ continue;
+ }
+ } else if (message.role === "toolResult" && (
+ !validIdentity(message.toolCallId, message.toolName) ||
+ rejected.get(wireId(message.toolCallId))?.has(message.toolName)
+ )) {
+ changed = true;
+ continue;
+ }
+ recovered.push(message);
+ }
+ return changed ? recovered : messages;
+}
diff --git a/scripts/e2e-hosted-search.mjs b/scripts/e2e-hosted-search.mjs
index d2fc25539..c947f6398 100644
--- a/scripts/e2e-hosted-search.mjs
+++ b/scripts/e2e-hosted-search.mjs
@@ -93,7 +93,7 @@ if (values.help) {
Default: build shared, agent-runtime, and the production sidecar bundle.
--bundle: build the resolver module and run that explicit sidecar artifact.
Evidence and isolated homes stay under PI_SCRATCH_DIR or mkdtemp(os.tmpdir()).
-Eight cases: next prompt, Read, instruction change, out-of-project instruction fallback, real Task/TaskWait, persisted restore, two invalid-history cases.
+Ten cases: malformed tool-call continuation (one or three failures), next prompt, Read, instruction change, out-of-project instruction fallback, real Task/TaskWait, persisted restore, two invalid-history cases.
Files are retained for inspection; no automatic deletion and no dependency installation.
Reviewed source, patches, and lock metadata are fingerprinted before the build and again
when the run ends; any change between the two fails the run.`);
diff --git a/scripts/e2e/hosted-search-scenarios.mjs b/scripts/e2e/hosted-search-scenarios.mjs
index 5c79ea1a9..07bd7acef 100644
--- a/scripts/e2e/hosted-search-scenarios.mjs
+++ b/scripts/e2e/hosted-search-scenarios.mjs
@@ -70,6 +70,44 @@ export async function runScenarios(bundle, root, timeoutMs, report, loadInstruct
report(result);
};
+ for (const failures of [1, 3]) {
+ await run(`malformed-tool-continue-${failures}`, (body, requests) => {
+ assert.equal(body.input.some((item) => item.type === "function_call" && !item.name), false,
+ "a malformed call must not poison the next real provider request");
+ assert.ok(requests.length <= failures + 4, "unexpected automatic retry");
+ if (requests.length <= failures) return { tool: { name: "", args: {} } };
+ if (requests.length === failures + 1) {
+ return { tool: { name: "Read", args: { path: "nested/fixture.txt" } } };
+ }
+ assert.match(functionResult(body, "Read"), /OFFLINE_READ_RESULT/);
+ return { text: "CONTINUE_RECOVERED" };
+ }, async ({ provider, start, dir }) => {
+ const sidecar = await start();
+ const params = parameters(provider.baseUrl, dir, "malformed-tool");
+ sidecar.expectContextValidationError = true;
+ for (let attempt = 0; attempt < failures; attempt++) {
+ const events = await sidecar.prompt(params, "Continue the current task.");
+ const errors = events.filter(({ event }) => event.type === "error");
+ assert.equal(errors.length, 1, "each malformed response must settle with one local error");
+ assert.equal(errors[0].event.error.details.origin, "local");
+ assert.equal(errors[0].event.error.details.phase, "context-validation");
+ assert.equal(provider.requests.length, attempt + 1, "malformed output must not enter transport retry");
+ }
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "tools.execute").length, 0);
+ sidecar.expectContextValidationError = false;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const events = await sidecar.prompt(params, "Continue the current task.");
+ assert.equal(events.some(({ event }) => event.type === "error"), false);
+ assertText(sidecar, "CONTINUE_RECOVERED");
+ }
+ assert.equal(provider.requests.length, failures + 4);
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "tools.execute").length, 1,
+ "the corrected tool must execute once across three Continue prompts");
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "session.get").length, 1,
+ "Continue must recover the reused runtime without a restart");
+ });
+ }
+
await run("search-next-prompt", (body, requests) => {
if (requests.length === 1) return { search: true, text: "SEARCH_FINISHED" };
assert.equal(requests.length, 2, "unexpected retry/extra parent request");
diff --git a/scripts/e2e/hosted-search-sidecar.mjs b/scripts/e2e/hosted-search-sidecar.mjs
index 4f57b934a..943e1efb0 100644
--- a/scripts/e2e/hosted-search-sidecar.mjs
+++ b/scripts/e2e/hosted-search-sidecar.mjs
@@ -39,6 +39,7 @@ export class OfflineSidecar {
this.sequence = 0;
this.closed = false;
this.stopping = false;
+ this.expectContextValidationError = false;
child.on("error", (error) => this.fail(error));
this.exit = new Promise((resolve) => child.once("close", (code, signal) => {
this.closed = true;
@@ -113,12 +114,15 @@ export class OfflineSidecar {
const envelope = frame.params;
this.events.push(envelope);
const event = envelope.event;
+ const expectedError = (error) => this.expectContextValidationError &&
+ error?.code === "INTERNAL" && error.retriable === false &&
+ error.details?.origin === "local" && error.details?.phase === "context-validation";
if (event.type === "message_end") {
const message = event.message;
this.messages.set(message.id, message);
- if (message.error) this.fail(new Error(`message error: ${JSON.stringify(message.error)}`));
+ if (message.error && !expectedError(message.error)) this.fail(new Error(`message error: ${JSON.stringify(message.error)}`));
}
- if (event.type === "error") this.fail(new Error(`agent error: ${JSON.stringify(event.error)}`));
+ if (event.type === "error" && !expectedError(event.error)) this.fail(new Error(`agent error: ${JSON.stringify(event.error)}`));
if (event.type === "status" && event.status.activity?.phase === "retrying") {
this.fail(new Error(`unexpected retry: ${JSON.stringify(event.status.activity.error)}`));
}