From 42ce039ff67c4aef9f99754f36d0b268cb2bd699 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:52:29 +0800 Subject: [PATCH] fix(pi): keep historical tool results with their call batch --- runtime/pi/src/worker.ts | 29 +++++++++++++++++++++++++- runtime/pi/test/worker.test.mjs | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index 960b5eaa..357d60ed 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -134,6 +134,32 @@ function repairInterruptedCalls(manager: SessionManager): void { isError: true, timestamp: Date.now() }); } +function pairToolResults(messages: readonly Message[]): Message[] { + const paired: Message[] = []; + const deferred: Message[] = []; + let pending = new Set(); + for (const message of messages) { + if (message.role === "toolResult") { + if (pending.delete(message.toolCallId)) paired.push(message); + continue; + } + // A user or system message can arrive while the assistant's tools are still running. + // Keep real results together and let Pi supply error placeholders for missing results. + if (message.role !== "assistant" && pending.size > 0) { + deferred.push(message); + continue; + } + paired.push(...deferred, message); + deferred.length = 0; + if (message.role === "assistant") { + pending = new Set(message.stopReason === "error" || message.stopReason === "aborted" ? [] : + message.content.flatMap(block => block.type === "toolCall" ? [block.id] : [])); + } + } + paired.push(...deferred); + return paired; +} + function publishSession(manager: SessionManager, dir?: string): void { const path = manager.getSessionFile(); if (!dir || !path || !existsSync(path)) return; @@ -175,7 +201,8 @@ async function run(req: RunRequest): Promise { modelConfigs.set(provider, config); } const streamSimple = runtime.streamSimple.bind(runtime); - runtime.streamSimple = (m, context, options) => streamSimple(m, context, { + runtime.streamSimple = (m, context, options) => streamSimple(m, + m.api === "openai-completions" ? { ...context, messages: pairToolResults(context.messages) } : context, { ...options, transport: "sse", onPayload: async (original, currentModel) => { diff --git a/runtime/pi/test/worker.test.mjs b/runtime/pi/test/worker.test.mjs index 648d88da..9ff4ff30 100644 --- a/runtime/pi/test/worker.test.mjs +++ b/runtime/pi/test/worker.test.mjs @@ -98,6 +98,43 @@ test("real Pi SDK streams, invokes only host tools and restores persisted sessio assert.ok(fixture.requests[2].messages.some(m => m.role === "tool" && m.content === "hello")); }); +test("OpenAI-compatible requests keep historical tool results in their own assistant batch", { timeout: 30000 }, async t => { + const fixture = await startFixture(t, (body, res) => { + let pending = new Set(); + for (const message of body.messages) { + if (message.role === "tool" ? !pending.delete(message.tool_call_id) : pending.size > 0) { + res.writeHead(400, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: { message: "Invalid tool result sequence" } })); + return; + } + if (message.role === "assistant") pending = new Set(message.tool_calls?.map(call => call.id)); + } + sse(res, { role: "assistant", content: "verified history" }, "stop"); + }); + const call = id => ({ id, function: { name: "echo", arguments: "{}" } }); + const result = (id, content) => ({ role: "tool", tool_call_id: id, tool_name: "echo", content }); + const req = request(fixture.url); + req.generateOnly = true; + req.history = [ + { role: "user", content: "Use echo" }, + { role: "assistant", tool_calls: [call("reused"), call("second")] }, + result("reused", "first result"), + { role: "user", content: "An interruption" }, + result("second", "second result"), + result("second", "duplicate result"), + { role: "assistant", content: "Continuing" }, + result("reused", "orphaned result"), + { role: "assistant", tool_calls: [call("reused")] }, + result("reused", "new batch result"), + { role: "user", content: "Summarize" }, + ]; + const run = await invoke(t, req); + assert.equal(run.result.status, "completed", run.result.error); + assert.equal(run.result.response, "verified history"); + assert.deepEqual(fixture.requests[0].messages.filter(m => m.role === "tool" || m.content === "An interruption").map(m => m.content), + ["first result", "second result", "An interruption", "new batch result"]); +}); + test("cancel rejects a pending host tool and settles without another model call", { timeout: 30000 }, async t => { const fixture = await startFixture(t, (_, res) => sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "call-wait", type: "function", function: { name: "echo", arguments: '{"text":"wait"}' } }] }, "tool_calls")); const { result } = await invoke(t, request(fixture.url), (r, send) => {