Skip to content

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

fix(agent-runtime): preserve executions when providers reuse tool IDs

Seraph-xc1f81eec73d0
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 34f3a0a7e..047bb8b8e 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -811,24 +811,24 @@ order the user wrote. Reads are bounded by the admitted file size. Base64 is
transient and never restored into durable UI messages or transcript records.
- Failed assistant messages remain durable diagnostic transcript entries but
are never restored into pi model context on a later turn.
-- A tool-call id is unique in every request. The transcript is an append-only
- snapshot stream that tolerates a retried append, so the same call can reach
- the assembled context twice — under one row id, which the host's keep-last
- read already collapses, or under two, which it cannot. The last view before
- the wire therefore keeps the first occurrence of each `toolCall` id and drops
- a later call or a later result for it, so the pair the provider validates
- stays well-formed; a request with no duplicates is returned unchanged. A drop
- is reported once on the `agent` log channel with the session and the ids
- (D608). Anthropic-family endpoints, including DeepSeek's, reject the whole
- turn with `tool_use ids must be unique` (issue #718), which leaves the session
- unable to continue.
-- The guard compares the wire-visible call id — the part before the `|` that
- separates the Responses item id — and drops an assistant message whole once
- every tool call in it was already claimed, because keeping its residual text
- would leave a message sitting between a call and the result answering it. A
- message that replays a claimed call while carrying a new one keeps its new
- call in place; no writer produces that partial replay, and the guard does not
- reorder messages to close the gap it leaves (D620).
+- Tool-call ids remain unique in each provider request. Before Pi executes a
+ streamed response, the parent runtime and each delegate assign fresh local
+ ids to calls that reuse an earlier wire-visible id (the part before `|`).
+ Each runtime retains its identity set across context compaction; the parent
+ seeds it from the full restored transcript, and delegates keep it across
+ model fallback. This prevents reused provider ids from losing real results
+ when the runtime journals entries by id (issue #1815).
+- The final request guard drops a repeated call only while the earlier call is
+ still waiting for its result, and drops a repeated result only without a
+ pending call. An independently completed same-id pair is retained under a
+ fresh request-local id with its result remapped to match. A renamed Responses
+ call does not reuse its old item id. No source messages are mutated; unchanged
+ requests retain their identity. Drops are logged with the session and ids
+ (D608). Composite result ids are aligned even without a duplicate drop.
+- A replayed assistant snapshot whose calls are all pending elsewhere is
+ removed whole: retaining its text would separate the call from its result
+ and make pi-ai synthesize a second output (D620). A partial snapshot retains
+ its new calls in place; the guard does not reorder messages.
- The agent loop owns its context array. `prepareNextTurn` hands pi a copy of
the live state — for a delegate turn boundary too — exactly as pi's own
`createContextSnapshot()` does for `prompt()` and `continue()`: pi's loop
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 67ad9cf89..610665e4c 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -599,14 +599,14 @@ Goal 批准所承诺的内容与 Plan 批准所承诺的内容完全相同:`mo
获得合成的仅呼叫辅助运营商,以便 call/result 对保留
格式良好,适用于每个提供商 API。工具执行期间保存的模型系统记录恢复在该调用与其结果之间,
不会结束助手的调用,因此调用仍挂在发出它的助手消息上,与实时请求一致。
-- 每个请求里的工具调用 id 必须唯一。转录是仅追加的快照流,容忍重试造成的重复追加,因此同一次调用可能两次进入组装后的
- 上下文——同一个行 id(宿主按 keep-last 读取时已折叠),或者两个不同的行 id(宿主无法折叠)。因此上线前的最后一个视图
- 对每个 `toolCall` id 只保留第一次出现,丢弃其后重复的调用或结果,使提供商校验的「一调用一结果」配对保持完整;没有重复的
- 请求原样返回。一旦发生丢弃,会在 `agent` 日志通道上报告一次,带上会话与 id(D608)。Anthropic 系端点(含 DeepSeek)
- 会以 `tool_use ids must be unique` 拒绝整个回合(issue #718),使该会话无法继续。
-- 守卫按“上线的 id”比较调用与结果,即 Responses item id 之前、以 `|` 分隔的那一段;当一条辅助消息里的工具调用全部已被更早的消息占有时,
- 整条消息被丢弃,因为保留它剩下的文本会把一条消息塞进调用与回答它的结果之间。若一条消息在复写已占用调用的同时还带一个新调用,则保留该
- 消息及其新调用;目前没有写入方会产生这种部分复写,守卫也不会重排消息来填补它留下的空隙(D620)。
+- 每个提供商请求里的工具调用 id 保持唯一。流式响应进入 Pi 工具执行前,父运行时与每个委托会为复用旧 wire id
+ (`|` 之前的部分)的调用分配新本地 id。身份集合跨上下文压缩保留;父运行时从完整恢复转录初始化,委托切换备选
+ 模型时继续使用同一集合,避免按 id 记账时丢失真实执行结果(issue #1815)。
+- 请求出口只在旧调用仍等待结果时丢弃重复调用,只在没有待配对调用时丢弃重复结果。已经完成配对的同 id 再次调用
+ 保留,并仅在请求视图中为调用和结果同步重编号。重编号的 Responses 调用不复用旧 item id,不修改源消息;未变化
+ 的请求保持对象身份。丢弃时记录会话与 id(D608);即使没有丢弃,复合结果 id 也会与调用对齐。
+- 若一个重复助手快照的全部调用都在等待其他结果,则整条移除,避免残留文本分隔调用与结果,导致 Pi 合成第二个输出
+ (D620)。部分重复快照里的新调用保留原位,不重排消息。
- 智能体循环拥有自己的上下文数组。`prepareNextTurn` 交给 pi 的是实时状态的副本(委托侧的回合边界同样如此),与 pi 自己的
`createContextSnapshot()` 在 `prompt()`/`continue()` 里的做法一致:pi 的循环会把每个流式辅助消息与每个工具结果 push 进它拿到的
数组,而它的 `message_end` 监听器又把同一消息 push 回 `state.messages`,因此交出活数组会把一个回合中较晚迭代的每条消息都存两份。
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index fc0cc4b8e..65e9b6ae9 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -11132,7 +11132,7 @@ describe("DesktopAgentRuntime loop context ownership (D620)", () => {
function scriptCallRounds(
runtime: DesktopAgentRuntime,
requests: AgentMessage[][],
- options: { stopAfterRound?: number } = {},
+ options: { stopAfterRound?: number; reuseCallId?: boolean } = {},
): void {
let round = 0;
(runtime as any).models = {
@@ -11150,9 +11150,9 @@ describe("DesktopAgentRuntime loop context ownership (D620)", () => {
{ type: "text", text: `round ${current}` },
{
type: "toolCall",
- id: `call-${current}`,
- name: "plugin_demo_probe",
- arguments: {},
+ id: options.reuseCallId ? "call-reused" : `call-${current}`,
+ name: options.reuseCallId ? "Bash" : "plugin_demo_probe",
+ arguments: options.reuseCallId ? { command: "printf probe" } : {},
},
]
: [{ type: "text", text: `round ${current}` }],
@@ -11175,7 +11175,7 @@ describe("DesktopAgentRuntime loop context ownership (D620)", () => {
function probeRuntime(
requests: AgentMessage[][],
- options: { stopAfterRound?: number } = {},
+ options: { stopAfterRound?: number; reuseCallId?: boolean } = {},
): DesktopAgentRuntime {
const runtime = createRuntime({
host: {
@@ -11261,6 +11261,27 @@ describe("DesktopAgentRuntime loop context ownership (D620)", () => {
}
}
+ it("keeps both executed results in the next request when the provider reuses a call id", async () => {
+ const requests: AgentMessage[][] = [];
+ const runtime = probeRuntime(requests, { reuseCallId: true });
+ try {
+ await runtime.prompt("run the probe twice", "user-1", "turn-1");
+
+ expect(requests).toHaveLength(3);
+ expect(resultIds(requests[1]!)).toHaveLength(1);
+ const finalRequest = requests[2]!;
+ const ids = toolCallIds(finalRequest);
+ expect(ids).toHaveLength(2);
+ expect(new Set(ids).size).toBe(2);
+ expect(resultIds(finalRequest)).toEqual(ids);
+ expect(finalRequest.filter((m) => m.role === "toolResult").map((m) => m.content))
+ .toEqual([[{ type: "text", text: "probe ok" }], [{ type: "text", text: "probe ok" }]]);
+ expectResultsFollowTheirCalls(finalRequest);
+ } finally {
+ await runtime.dispose();
+ }
+ });
+
it("stores one copy of every message the loop appends", async () => {
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 7249de152..da1dc83f4 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -167,6 +167,7 @@ import {
} from "./system-transcript.js";
import {
dedupeToolCallMessages,
+ createToolCallIdentity,
reportDuplicateToolCallDrop,
} from "./tool-call-dedupe.js";
import {
@@ -1974,6 +1975,7 @@ export class DesktopAgentRuntime {
private terminatingToolCalls = new Set<string>();
private delegateMutationTerminations = new Map<string, { code: string; message: string }>();
private fullEntries: MessageEntry[];
+ private readonly uniqueToolCalls: ReturnType<typeof createToolCallIdentity>;
private readonly systemJournal = new SystemTranscriptJournal();
private composedSections: Record<string, string> = {};
private activeCompaction?: ContextCompactionRecord;
@@ -2065,6 +2067,7 @@ export class DesktopAgentRuntime {
this.transcriptHistory = [...(opts.history ?? [])];
this.fullEntries = this.historyToEntries(this.transcriptHistory);
+ this.uniqueToolCalls = createToolCallIdentity(this.fullEntries.map((entry) => entry.message));
this.activeCompaction = opts.compaction;
this.delegationChains.hydrate(
rebuildChainsFromTranscript(this.transcriptHistory),
@@ -2247,8 +2250,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// configured budget ends as a STREAM_FAILED error and re-enters the
// shared transient retry path instead of hanging the turn on a
// connection the provider never closes.
- return withStreamIdleTimeout(retryStream, m, streamIdleTimeoutMs(), () =>
- stallAbort.abort(),
+ return this.uniqueToolCalls(
+ withStreamIdleTimeout(retryStream, m, streamIdleTimeoutMs(), () => stallAbort.abort()),
+ context.messages,
);
},
// A vendor account has no long-lived key. Leaving it unset keeps pi-ai
@@ -3161,11 +3165,11 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
* The transcript is append-only and tolerates a retried append, so the same
* call can reach the request twice: under the same row id (which the host's
* keep-last dedupe already collapses) or a new one (which it cannot). The
- * first occurrence wins, and a later call *or* a later result for that id is
- * dropped, so the pair the provider validates stays well-formed — one call,
- * one result. What was dropped is logged with its ids, because the next
- * report of this should name the writer instead of only the provider's
- * sentence.
+ * first pending occurrence wins; a later completed pair is retained under
+ * a fresh request id. New streamed executions are normalized before they
+ * reach this guard or the journal. What was dropped is logged with its ids,
+ * because the next report should name the writer instead of only the
+ * provider's sentence.
*/
private dropDuplicateToolCalls(messages: AgentMessage[]): AgentMessage[] {
const drop = dedupeToolCallMessages(messages);
diff --git a/packages/agent-runtime/src/subagent-fallback.test.ts b/packages/agent-runtime/src/subagent-fallback.test.ts
index 3009fb256..40b7c24dc 100644
--- a/packages/agent-runtime/src/subagent-fallback.test.ts
+++ b/packages/agent-runtime/src/subagent-fallback.test.ts
@@ -8,7 +8,7 @@ import { genericModelConfig } from "./model-capabilities.js";
import type { RuntimeProviderConfig } from "./provider-binding.js";
import { PROVIDER_RATE_LIMIT_MAX_RETRIES, PROVIDER_TRANSIENT_MAX_RETRIES } from "./provider-retry.js";
-type Request = { model: string; messages: Array<{ role: string; content: unknown }>; reasoning_effort?: string };
+type Request = { model: string; messages: Array<{ role: string; content: unknown; tool_call_id?: string; tool_calls?: Array<{ id: string }> }>; reasoning_effort?: string };
const cleanups: Array<() => Promise<void>> = [];
afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup(); });
@@ -27,6 +27,7 @@ async function fixture(options: {
fail?: string[];
failureStatus?: Record<string, number>;
editFirst?: boolean;
+ repeatToolRounds?: number;
onRequest?: (request: Request) => void;
} = {}) {
const requests: Request[] = [];
@@ -41,7 +42,7 @@ async function fixture(options: {
options.onRequest?.(request);
const status = options.failureStatus?.[request.model]
?? ((options.fail ?? ["primary"]).includes(request.model) ? 404 : undefined);
- if (options.editFirst && requests.length === 1) {
+ if (requests.length <= (options.repeatToolRounds ?? 0) || (options.editFirst && requests.length === 1)) {
answer(res, request.model, true);
} else if (status) {
res.writeHead(status, { "content-type": "application/json", "retry-after": "0" });
@@ -81,6 +82,23 @@ async function fixture(options: {
describe("subagent model fallback over real transport", () => {
const chain = ["primary", "secondary", "third", "fourth", "unused"];
+ it("retains both real executions when a provider repeats the same tool id", async () => {
+ const f = await fixture({ fail: [], repeatToolRounds: 2 });
+ const result = await f.run();
+
+ expect(result.status).toBe("completed");
+ expect(f.edits()).toBe(2);
+ expect(f.requests).toHaveLength(3);
+ const final = f.requests[2]!.messages;
+ const calls = final.flatMap((message) => message.tool_calls ?? []);
+ const results = final.filter((message) => message.role === "tool");
+ expect(calls).toHaveLength(2);
+ expect(new Set(calls.map((call) => call.id)).size).toBe(2);
+ expect(results.map((message) => message.tool_call_id)).toEqual(calls.map((call) => call.id));
+ expect(results.every((message) => String(message.content).includes("Saved exactly once"))).toBe(true);
+ expect(result.toolCalls).toBe(2);
+ });
+
it.each([0, 1, 2, 3])("succeeds after %i unavailable models and stops at the first working model", async (failedCount) => {
const failedModels = chain.slice(0, failedCount);
const attempts = chain.slice(0, failedCount + 1);
diff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.ts
index 183b30ada..1c5702cf0 100644
--- a/packages/agent-runtime/src/subagent-model-binding.ts
+++ b/packages/agent-runtime/src/subagent-model-binding.ts
@@ -1,3 +1,4 @@
+import { createToolCallIdentity } from "./tool-call-dedupe.js";
import { accountModelStream, type UsageObserver } from "./request-usage.js";
import {
buildProviderModel,
@@ -38,6 +39,7 @@ export function subagentModelBinding(opts: {
sessionId: string;
maxTokens?: number;
onUsage?: UsageObserver;
+ uniqueToolCalls?: ReturnType<typeof createToolCallIdentity>;
}, retry: SubagentProviderRetryState) {
// A definition may cap the delegate's own output (issue #171). The
// catalog's published limit keeps applying otherwise, so this is an
@@ -58,6 +60,7 @@ export function subagentModelBinding(opts: {
// provider receives no synthesized reasoning setting at all.
const omitThinkingModel = omitThinking ? withOmittedThinking(model) : model;
const requestKey = providerRequestKey(opts.provider);
+ const uniqueToolCalls = opts.uniqueToolCalls ?? createToolCallIdentity();
return {
model,
agentThinkingLevel,
@@ -109,7 +112,7 @@ export function subagentModelBinding(opts: {
baseUrl: m.baseUrl,
sessionId: opts.sessionId,
});
- return createProviderRetryStream(
+ return uniqueToolCalls(createProviderRetryStream(
m,
context,
sessionOptions,
@@ -127,7 +130,7 @@ export function subagentModelBinding(opts: {
status: () => retry.status,
failure: () => retry.failure,
},
- );
+ ), context.messages);
},
getApiKey: async () => requestKey || undefined,
} satisfies Pick<AgentOptions, "streamFn" | "getApiKey"> & {
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index fa4b4f884..40e1672e4 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -150,7 +150,7 @@ describe("SubagentRun event forwarding", () => {
"models.stream(omitThinkingModel, context, retryOptions)",
);
});
- it("deduplicates repeated tool calls before a subagent request", () => {
+ it("retains completed same-id rounds in a resumed subagent request", () => {
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
const { run } = createRun({
@@ -190,15 +190,15 @@ describe("SubagentRun event forwarding", () => {
: [],
);
- expect(toolCalls.map((call) => call.id)).toEqual(["child-read"]);
- expect(outgoing.filter((message) => message.role === "toolResult")).toHaveLength(1);
+ expect(toolCalls.map((call) => call.id)).toEqual(["child-read", "call_pi_repeat_1"]);
+ expect(outgoing.filter((message) => message.role === "toolResult")).toHaveLength(2);
expect(
outgoing.filter(
(message) => message.role === "assistant" && message.content.length === 0,
),
).toHaveLength(0);
expect(stderr.mock.calls.map(([chunk]) => String(chunk)).join(""))
- .toContain("session=session-1");
+ .toBe("");
} finally {
stderr.mockRestore();
}
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 8a5f60131..dc8c4dc88 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -68,6 +68,7 @@ import {
} from "./subagent-context.js";
import {
dedupeToolCallMessages,
+ createToolCallIdentity,
reportDuplicateToolCallDrop,
} from "./tool-call-dedupe.js";
import { removeTrailingAssistantMessages } from "./system-transcript.js";
@@ -238,6 +239,7 @@ export { addUsage };
/** One delegate execution. A resumed run is still a new instance; it is
* seeded with the prior chain's messages rather than kept warm in memory. */
export class SubagentRun {
+ private readonly uniqueToolCalls: ReturnType<typeof createToolCallIdentity>;
private readonly agent: Agent;
private readonly opts: SubagentRunOptions;
private currentAssistant?: UiMessage;
@@ -274,6 +276,7 @@ export class SubagentRun {
constructor(opts: SubagentRunOptions) {
this.opts = opts;
+ this.uniqueToolCalls = createToolCallIdentity(opts.initialMessages ?? []);
this.provider = opts.provider;
this.thinkingLevel = opts.thinkingLevel;
this.attemptedModels.add(`${opts.provider.id}/${opts.provider.modelId}`);
@@ -447,6 +450,7 @@ export class SubagentRun {
sessionId: this.opts.sessionId,
maxTokens: this.opts.definition.maxTokens,
onUsage: usage => this.recordUsage(usage),
+ uniqueToolCalls: this.uniqueToolCalls,
}, this.retryState);
}
diff --git a/packages/agent-runtime/src/tool-call-dedupe.test.ts b/packages/agent-runtime/src/tool-call-dedupe.test.ts
index 92f55473c..87efd32ef 100644
--- a/packages/agent-runtime/src/tool-call-dedupe.test.ts
+++ b/packages/agent-runtime/src/tool-call-dedupe.test.ts
@@ -150,6 +150,58 @@ describe("dedupeToolCallMessages", () => {
expect(dedupeToolCallMessages(messages).messages).toBe(messages);
});
+ it("keeps independently completed calls when a provider reuses an id", () => {
+ const messages = [
+ assistantMessage([toolCall("call-1")]),
+ toolResult("call-1", "first execution"),
+ assistantMessage([toolCall("call-1")]),
+ toolResult("call-1", "second execution"),
+ assistantMessage([toolCall("call-1")]),
+ toolResult("call-1", "third execution"),
+ ];
+ const original = structuredClone(messages);
+
+ const drop = dedupeToolCallMessages(messages);
+
+ expect(drop.droppedCount).toBe(0);
+ expect(drop.messages).toHaveLength(6);
+ const ids = callIds(drop.messages);
+ expect(new Set(ids).size).toBe(3);
+ expect(ids[0]).toBe("call-1");
+ expect(resultIds(drop.messages)).toEqual(ids);
+ expect(drop.messages.filter((message) => message.role === "toolResult")
+ .map((message) => message.content)).toEqual([
+ [text("first execution")], [text("second execution")], [text("third execution")],
+ ]);
+ expect(messages).toEqual(original);
+ expect(dedupeToolCallMessages(messages)).toEqual(drop);
+ });
+
+ it("still drops replayed snapshots and results within each reused-id round", () => {
+ const first = assistantMessage([toolCall("call-1|item-1")]);
+ const second = assistantMessage([toolCall("call-1|item-2")]);
+ const drop = dedupeToolCallMessages([
+ first, first, toolResult("call-1|item-1"), toolResult("call-1|item-1"),
+ second, second, toolResult("call-1|item-2"), toolResult("call-1|item-2"),
+ ]);
+
+ expect(drop.droppedCount).toBe(4);
+ expect(drop.droppedMessages).toBe(2);
+ expect(drop.messages).toHaveLength(4);
+ const ids = callIds(drop.messages);
+ expect(new Set(ids.map((id) => id.split("|")[0])).size).toBe(2);
+ expect(resultIds(drop.messages)).toEqual(ids);
+ });
+
+ it("aligns a composite result even when no duplicate was dropped", () => {
+ const messages = [assistantMessage([toolCall("call-1|item-1")]), toolResult("call-1|other")];
+ const drop = dedupeToolCallMessages(messages);
+
+ expect(drop.droppedCount).toBe(0);
+ expect(resultIds(drop.messages)).toEqual(["call-1|item-1"]);
+ expect(resultIds(messages)).toEqual(["call-1|other"]);
+ });
+
it("reports the wire ids and how many messages it removed", () => {
const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
try {
diff --git a/packages/agent-runtime/src/tool-call-dedupe.ts b/packages/agent-runtime/src/tool-call-dedupe.ts
index 9f42f0d57..8cb18140d 100644
--- a/packages/agent-runtime/src/tool-call-dedupe.ts
+++ b/packages/agent-runtime/src/tool-call-dedupe.ts
@@ -1,4 +1,5 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import type { AssistantMessage, AssistantMessageEventStream } from "@earendil-works/pi-ai";
type RecordLike = Record<string, unknown>;
@@ -30,8 +31,68 @@ function wireCallId(id: string): string {
return separator < 0 ? id : id.slice(0, separator);
}
+function callIdsIn(messages: readonly unknown[]): Set<string> {
+ const ids = new Set<string>();
+ for (const message of messages) {
+ if (!isRecord(message) || message.role !== "assistant" || !Array.isArray(message.content)) continue;
+ for (const block of message.content) {
+ if (isRecord(block) && block.type === "toolCall" && typeof block.id === "string") ids.add(wireCallId(block.id));
+ }
+ }
+ return ids;
+}
+
+function idAllocator(ids: Iterable<string>): () => string {
+ const reserved = new Set(ids);
+ let nextId = 0;
+ return () => {
+ let id: string;
+ do { id = `call_pi_repeat_${++nextId}`; } while (reserved.has(id));
+ reserved.add(id);
+ return id;
+ };
+}
+
+/** Give new executions unique identities before Pi executes or journals them. */
+export function createToolCallIdentity(initialHistory: readonly unknown[] = []): (
+ stream: AssistantMessageEventStream, history: readonly unknown[],
+) => AssistantMessageEventStream {
+ const seenIds = callIdsIn(initialHistory);
+ return (stream, history) => {
+ for (const id of callIdsIn(history)) seenIds.add(id);
+ const previousIds = new Set(seenIds);
+ const normalize = (message: AssistantMessage): AssistantMessage => {
+ if (message.stopReason === "error" || message.stopReason === "aborted") return message;
+ const used = new Set(previousIds);
+ const freshId = idAllocator([...previousIds, ...callIdsIn([message])]);
+ let changed = false;
+ const content = message.content.map((block) => {
+ if (block.type !== "toolCall") return block;
+ const wire = wireCallId(block.id);
+ if (!used.has(wire)) { used.add(wire); return block; }
+ changed = true;
+ return { ...block, id: freshId() };
+ });
+ const normalized = changed ? { ...message, content } : message;
+ for (const id of callIdsIn([normalized])) seenIds.add(id);
+ return normalized;
+ };
+ return new Proxy(stream, {
+ get(target, property, receiver) {
+ 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;
+ }
+ };
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ };
+}
+
/**
- * Keep the first call and result for every tool-call id in a provider request.
+ * Keep one result per execution, with unique ids in the provider request.
*
* The transcript can contain repeated snapshots of one call. Returning the
* original array when nothing changes preserves the common path's identity and
@@ -49,10 +110,11 @@ function wireCallId(id: string): string {
* result one message later; no writer reaches that partial replay, and the
* guard leaves it alone rather than reordering what the model sees.
*
- * Ids are compared by the part the provider validates, so two entries whose
- * item half differs count as one call. That shared id is the only id sharing
- * this guard accepts: a provider that reused one `call_id` for two distinct
- * calls would lose the second call and its result, reported under that id.
+ * A repeated id is a snapshot only while its call is waiting for a result.
+ * Once answered, the provider may reuse it for a new execution (#1815). Keep
+ * that execution and its result under a fresh request-local id, so endpoints
+ * requiring globally unique ids still accept the request. Never mutate the
+ * live transcript or carry a reused Responses item id onto the renamed call.
*/
export function dedupeToolCallMessages(
messages: AgentMessage[],
@@ -64,6 +126,8 @@ export function dedupeToolCallMessages(
const droppedIds = new Set<string>();
let droppedCount = 0;
let droppedMessages = 0;
+ let changed = false;
+ const freshId = idAllocator(callIdsIn(messages));
const note = (id: string) => {
droppedCount += 1;
if (droppedIds.size < MAX_LOGGED_DUPLICATE_TOOL_CALLS) {
@@ -80,19 +144,23 @@ export function dedupeToolCallMessages(
continue;
}
let calls = 0;
- const kept = content.filter((block) => {
- if (!isRecord(block) || block.type !== "toolCall") return true;
+ let contentChanged = false;
+ const kept = content.flatMap((block) => {
+ if (!isRecord(block) || block.type !== "toolCall") return [block];
const id = typeof block.id === "string" ? block.id : undefined;
- if (id === undefined) return true;
+ if (id === undefined) return [block];
calls += 1;
const wire = wireCallId(id);
- if (keptCalls.has(wire)) {
+ if ((openCalls.get(wire) ?? 0) > 0) {
note(wire);
- return false;
+ contentChanged = true;
+ return [];
}
- keptCalls.set(wire, id);
+ const requestId = keptCalls.has(wire) ? freshId() : id;
+ keptCalls.set(wire, requestId);
openCalls.set(wire, (openCalls.get(wire) ?? 0) + 1);
- return true;
+ if (requestId !== id) contentChanged = true;
+ return [requestId === id ? block : { ...block, id: requestId }];
});
// Every call this message carried was already claimed by an earlier one,
// so the message is that earlier message's snapshot rather than new
@@ -105,8 +173,9 @@ export function dedupeToolCallMessages(
droppedMessages += 1;
continue;
}
+ if (contentChanged) changed = true;
next.push(
- kept.length === content.length ? message : ({ ...message, content: kept } as AgentMessage),
+ contentChanged ? ({ ...message, content: kept } as AgentMessage) : message,
);
continue;
}
@@ -115,12 +184,12 @@ export function dedupeToolCallMessages(
const id = (message as { toolCallId?: unknown }).toolCallId;
if (typeof id === "string") {
const wire = wireCallId(id);
- if (keptResults.has(wire)) {
+ const waiting = openCalls.get(wire) ?? 0;
+ if (keptResults.has(wire) && waiting === 0) {
note(wire);
continue;
}
keptResults.add(wire);
- const waiting = openCalls.get(wire) ?? 0;
if (waiting > 0) {
openCalls.set(wire, waiting - 1);
const owner = keptCalls.get(wire);
@@ -128,6 +197,7 @@ export function dedupeToolCallMessages(
// composite id, so a result whose item half disagrees would leave the
// call pending and earn a second, synthesized output for this id.
if (owner !== undefined && owner !== id) {
+ changed = true;
next.push({ ...message, toolCallId: owner } as AgentMessage);
continue;
}
@@ -138,7 +208,7 @@ export function dedupeToolCallMessages(
}
return {
- messages: droppedCount === 0 ? messages : next,
+ messages: droppedCount === 0 && !changed ? messages : next,
droppedCount,
droppedMessages,
droppedIds: [...droppedIds],
diff --git a/packages/agent-runtime/src/tool-call-identity.test.ts b/packages/agent-runtime/src/tool-call-identity.test.ts
new file mode 100644
index 000000000..f8890159e
--- /dev/null
+++ b/packages/agent-runtime/src/tool-call-identity.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+import { createAssistantMessageEventStream, normalizeContext, type AssistantMessage, type Message, type Model } from "@earendil-works/pi-ai";
+import { convertResponsesMessages } from "@earendil-works/pi-ai/api/openai-responses-shared";
+import { stream as streamCompletions } from "@earendil-works/pi-ai/api/openai-completions";
+import { dedupeToolCallMessages } from "./tool-call-dedupe.js";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { createToolCallIdentity } from "./tool-call-dedupe.js";
+
+function message(ids: string[]): AssistantMessage {
+ return {
+ role: "assistant", api: "openai-completions", provider: "fixture", model: "fixture",
+ content: ids.map((id) => ({ type: "toolCall", id, name: "Read", arguments: { path: "file.txt" } })),
+ timestamp: 1, stopReason: "toolUse",
+ usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ };
+}
+
+describe("tool execution identity", () => {
+ it("preserves paired results through the real Responses and Chat Completions converters", async () => {
+ const history = [
+ message(["reused|fc_old"]),
+ { role: "toolResult", toolCallId: "reused|fc_old", toolName: "Read", content: [{ type: "text", text: "first result" }], isError: false, timestamp: 2 },
+ message(["reused|fc_new"]),
+ { role: "toolResult", toolCallId: "reused|fc_new", toolName: "Read", content: [{ type: "text", text: "second result" }], isError: false, timestamp: 3 },
+ ] as AgentMessage[];
+ const request = dedupeToolCallMessages(history).messages;
+ const context = normalizeContext({ messages: request as Message[] });
+ const model: Model<"openai-responses"> = {
+ id: "fixture", name: "Fixture", api: "openai-responses", provider: "fixture", baseUrl: "https://fixture.invalid",
+ reasoning: false, input: ["text"], contextWindow: 100_000, maxTokens: 1000,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ };
+ const responses = convertResponsesMessages(model, context, new Set(["fixture"]));
+ const calls = responses.filter((item) => item.type === "function_call");
+ const outputs = responses.filter((item) => item.type === "function_call_output");
+ expect(calls).toHaveLength(2);
+ expect(new Set(calls.map((item) => item.call_id)).size).toBe(2);
+ expect(outputs.map((item) => item.call_id)).toEqual(calls.map((item) => item.call_id));
+ expect(outputs.map((item) => item.output)).toEqual(["first result", "second result"]);
+ expect(calls[1]!.id).toBeUndefined();
+
+ type ChatMessage = { role: string; tool_calls?: Array<{ id: string }>; tool_call_id?: string; content?: unknown };
+ let chatMessages: ChatMessage[] = [];
+ const chatResult = await streamCompletions({ ...model, api: "openai-completions" }, context, {
+ apiKey: "fixture", maxRetries: 0,
+ onPayload: (payload) => { chatMessages = (payload as { messages: ChatMessage[] }).messages; },
+ fetch: async () => new Response(`data: ${JSON.stringify({
+ id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture",
+ choices: [{ index: 0, delta: { role: "assistant", content: "done" }, finish_reason: "stop" }],
+ })}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } }),
+ }).result();
+ expect(chatResult.stopReason).toBe("stop");
+ const chatCalls = chatMessages.flatMap((item) => item.role === "assistant" ? item.tool_calls ?? [] : []);
+ const chatOutputs = chatMessages.filter((item) => item.role === "tool");
+ expect(chatCalls).toHaveLength(2);
+ expect(new Set(chatCalls.map((item) => item.id)).size).toBe(2);
+ expect(chatOutputs.map((item) => item.tool_call_id)).toEqual(chatCalls.map((item) => item.id));
+ expect(chatOutputs.map((item) => item.content)).toEqual(["first result", "second result"]);
+ });
+
+ it("reserves restored and newly executed ids after their messages leave the request", async () => {
+ const wrap = createToolCallIdentity([message(["restored|fc_old", "call_pi_repeat_1"])]);
+ async function complete(id: string) {
+ const response = message([id]);
+ const stream = createAssistantMessageEventStream();
+ const wrapped = wrap(stream, []);
+ stream.push({ type: "done", reason: "toolUse", message: response });
+ stream.end(response);
+ for await (const _event of wrapped) { /* consume like Pi */ }
+ return (await wrapped.result()).content.flatMap((block) => block.type === "toolCall" ? [block.id] : [])[0]!;
+ }
+
+ const first = await complete("restored|fc_old");
+ const second = await complete("restored|fc_old");
+ const third = await complete(first);
+ expect(new Set(["restored|fc_old", "call_pi_repeat_1", first, second, third]).size).toBe(5);
+ });
+
+ it("keeps done and result consistent, without mutating the provider's message or metadata", async () => {
+ const withUniqueToolCallIds = createToolCallIdentity();
+ const original = message(["reused|fc_old", "reused|fc_new", "call_pi_repeat_1"]);
+ const snapshot = structuredClone(original);
+ const stream = createAssistantMessageEventStream();
+ const wrapped = withUniqueToolCallIds(stream, [message(["reused|fc_history"])]);
+ stream.push({ type: "start", partial: original });
+ 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[0]).toEqual({ type: "start", partial: original });
+ expect(events[1]).toEqual({ type: "done", reason: "toolUse", message: result });
+ const ids = result.content.flatMap((block) => block.type === "toolCall" ? [block.id] : []);
+ expect(new Set(ids).size).toBe(3);
+ expect(ids.at(-1)).toBe("call_pi_repeat_1");
+ expect(ids.slice(0, 2).every((id) => !id.includes("|"))).toBe(true);
+ expect(result).toMatchObject({ usage: original.usage, stopReason: original.stopReason, timestamp: original.timestamp });
+ expect(original).toEqual(snapshot);
+ expect(await wrapped.result()).toEqual(result);
+ });
+
+ it("preserves unique responses and error events by identity", async () => {
+ const withUniqueToolCallIds = createToolCallIdentity();
+ const original = message(["unique|fc_1"]);
+ const stream = createAssistantMessageEventStream();
+ const wrapped = withUniqueToolCallIds(stream, []);
+ stream.push({ type: "done", reason: "toolUse", message: original });
+ stream.end(original);
+ for await (const event of wrapped) {
+ if (event.type === "done") expect(event.message).toBe(original);
+ }
+ expect(await wrapped.result()).toBe(original);
+
+ const failed = { ...original, stopReason: "aborted" as const, errorMessage: "cancelled" };
+ const errors = createAssistantMessageEventStream();
+ const wrappedErrors = withUniqueToolCallIds(errors, [original]);
+ const errorEvent = { type: "error" as const, reason: "aborted" as const, error: failed };
+ errors.push(errorEvent);
+ errors.end(failed);
+ for await (const event of wrappedErrors) expect(event).toBe(errorEvent);
+ expect(await wrappedErrors.result()).toBe(failed);
+ });
+});