Skip to content

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

fix(agent-runtime): keep the loop context array out of the session state

deqiying353c67270411
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 95dda728a..b1570b8b0 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -698,6 +698,27 @@ criterion-by-criterion report of what was met and the evidence observed.
(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 (D613).
+- 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
+ appends each streamed assistant message and each tool result to the array it
+ was given, while its `message_end` listener appends the same message to
+ `state.messages`, so handing over the live array stored every message of a
+ run's later iterations twice. The next turn's first request was built from
+ that array, and the duplicate of an assistant message carrying text plus a
+ tool call survived as a text-only clone between the call and its result —
+ pi-ai then closed the still-pending call with a synthesized output next to the
+ real one, and the endpoint rejected the turn with
+ `Duplicate tool output for call_id`. In a delegate the same doubling doubled
+ the estimate at the following boundary and left the trailing row a fallback
+ carries onto a model it cannot resume from (D613).
- Restored checkpoints clear provider usage from retained assistant messages
for budgeting. That usage measured the pre-compacted request and must not
make the summary + tail appear as large as the discarded context.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 6c6930488..523b0f9e8 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8166,6 +8166,8 @@ identify the platform validation still needed.
| F — Persistence (stored model binding array) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry |
| Quality (stored model binding array) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry |
| Quality (unique tool-call ids) | E2E-RUNTIME-unique-tool-call-ids-per-request |
+| C — Conversation & stream (loop context ownership) | E2E-RUNTIME-loop-context-ownership |
+| Quality (loop context ownership) | E2E-RUNTIME-loop-context-ownership |
| G — Plugin host lifecycle (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |
| Quality (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |
@@ -14403,9 +14405,36 @@ the latest destination. These assertions measure work counts, not device FPS.
- **Automation:** `packages/agent-runtime/src/runtime.test.ts` covers both halves
against a real runtime built from a duplicated history (drop + one log line)
and a unique one (identity, no log line).
+
- **Status:** Unit-covered; no end-to-end driver issues a real provider request
against a duplicated transcript.
+### E2E-RUNTIME-loop-context-ownership
+
+- **Preconditions:** A deterministic provider fixture that answers the first two
+ rounds with one tool call each and stops the turn after the second round the
+ way a user Stop does. No real provider credentials.
+- **Steps:** Send one prompt so the runtime runs both tool rounds and ends the
+ turn on a tool round. Send a second prompt. Read the state the runtime kept and
+ the outgoing request the fixture received.
+- **Expected:** The kept state holds each streamed assistant message and each tool
+ result exactly once; no result is separated from the call it answers; the
+ fixture's request carries exactly one result per call. No duplicate-drop line is
+ logged, because the request guard had nothing to drop.
+- **Specs:** `03-runtime/02-agent-runtime.md` §5c,
+ `08-meta/decisions-log.md` D613.
+- **Acceptance:** C (conversation and stream), Quality.
+- **Milestone:** Post-MVP regression coverage.
+- **Automation:** `packages/agent-runtime/src/runtime.test.ts` (loop context
+ ownership) drives the real pi loop through `runtime.prompt()` and reads the
+ view `convertToLlm` handed the provider; `subagent-loop-context.test.ts` covers
+ the delegate's turn boundary. The adapter's own output is out of reach of both,
+ so `tool-call-dedupe.test.ts` (request wire contract) drives pi-ai's message
+ transform directly to pin the two outputs one call id receives when a request
+ separates a call from its result.
+- **Status:** Unit-covered; no end-to-end driver issues a real provider request
+ from a context the loop appended to.
+
### E2E-MCP-HTTP-ACK — HTTP acknowledgement and authorization status
- **Preconditions**: A local mock Streamable HTTP server returns JSON for
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 4cc7e2031..458adc5e3 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -6595,3 +6595,38 @@ that was sitting at the bottom — including after the turn had finished.
by `apps/desktop/test/default-model-display.test.mjs` and
`apps/desktop/test/image-generation-default.test.mjs`, with
`provider-model-config.test.mjs` asserting the add branch consults them.
+
+## 2026-09-22 — The loop owns its context array (D613)
+
+- A turn whose later iterations ran tools left `state.messages` holding two copies
+ of every message those iterations appended, and the next turn's first request
+ was assembled from that array. The duplicate of an assistant message that
+ carried text plus a tool call survived the request guard (D608) as a text-only
+ clone sitting between the call and the result answering it; pi-ai then closed
+ the still-pending call with a synthesized "No result provided" output next to
+ the real one, so one call id carried two outputs and the endpoint rejected the
+ whole turn with `Duplicate tool output for call_id` (HTTP 400, not retriable).
+ The array is reused, so every following turn failed the same way and `继续`
+ could not recover the session.
+- pi-ai's loop appends each streamed assistant message and each tool result to
+ the context it was handed, while its own `message_end` listener appends the
+ same message object to `state.messages`. `rebuiltAgentContext()` returned that
+ live array, so both appends landed in one array; it now returns a copy, exactly
+ like pi's own `createContextSnapshot()` does for `prompt()` and `continue()`.
+ The delegate's turn boundary handed over the same live array
+ (`subagent.ts` `prepareNextTurn`) and now copies too. The loop's view and
+ `state.messages` carry the same messages in the same order at each message
+ boundary, they are simply no longer the same array — which is what keeps the
+ duplicates out of the next request.
+- The request guard at `convertToLlm` (D608) now matches what the provider
+ validates: call and result ids are compared by their wire-visible part, a
+ result whose item half disagrees with its call is paired to the call's id, and
+ an assistant message whose tool calls were all already claimed is dropped whole
+ instead of being kept as the clone that separates a call from its result. The
+ drop log line also states how many messages were removed. A message that
+ replays one claimed call while carrying a new one is left in place with its new
+ call, the only id sharing the guard accepts; no writer reaches that shape.
+- No provider transport, host protocol, version, storage migration, transcript
+ rewrite, or compaction/retention/budget rule changes.
+ `03-runtime/02-agent-runtime.md` §5c and
+ E2E-RUNTIME-loop-context-ownership record the contract and its coverage.
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 026d712c1..f35d4178f 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -540,6 +540,15 @@ Goal 批准所承诺的内容与 Plan 批准所承诺的内容完全相同:`mo
对每个 `toolCall` id 只保留第一次出现,丢弃其后重复的调用或结果,使提供商校验的「一调用一结果」配对保持完整;没有重复的
请求原样返回。一旦发生丢弃,会在 `agent` 日志通道上报告一次,带上会话与 id(D608)。Anthropic 系端点(含 DeepSeek)
会以 `tool_use ids must be unique` 拒绝整个回合(issue #718),使该会话无法继续。
+- 守卫按“上线的 id”比较调用与结果,即 Responses item id 之前、以 `|` 分隔的那一段;当一条辅助消息里的工具调用全部已被更早的消息占有时,
+ 整条消息被丢弃,因为保留它剩下的文本会把一条消息塞进调用与回答它的结果之间。若一条消息在复写已占用调用的同时还带一个新调用,则保留该
+ 消息及其新调用;目前没有写入方会产生这种部分复写,守卫也不会重排消息来填补它留下的空隙(D613)。
+- 智能体循环拥有自己的上下文数组。`prepareNextTurn` 交给 pi 的是实时状态的副本(委托侧的回合边界同样如此),与 pi 自己的
+ `createContextSnapshot()` 在 `prompt()`/`continue()` 里的做法一致:pi 的循环会把每个流式辅助消息与每个工具结果 push 进它拿到的
+ 数组,而它的 `message_end` 监听器又把同一消息 push 回 `state.messages`,因此交出活数组会把一个回合中较晚迭代的每条消息都存两份。
+ 下一回合的首个请求正是用该数组组装的,其中“带文本与工具调用的辅助消息”的重复项会残留为只剩文本的克隆,卡在调用与结果之间——pi-ai
+ 随后会为这个仍处于待配对的调用合成一条输出,与真实结果并列,端点以 `Duplicate tool output for call_id` 拒绝整个回合。在委托运行时,
+ 同样的重复还会让下一个边界的估算翻倍,并让备用模型拿到的末行无法被 `continue()` 续跑(D613)。
- 视觉运行时只从会话绑定的附件、scratch 与项目根目录中水合持久化的图片引用。
处于 10 MB 内联安全上限之内的图片会成为临时的 pi-ai 图片块;超限或不可用的
图片则退化为安全的 `@path` 回退。超限历史的水合会直接复制文件,不会先把内容
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index e25fb7794..4158ee14b 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -5345,6 +5345,8 @@ eleven-tool-round desktop paths are verified by
| C / F / 品质 —— 上下文估算保持安全(校准) | E2E-CONTEXT-estimate-calibration-stays-safe |
| C — 对话与流式(工具调用 id 唯一) | E2E-RUNTIME-unique-tool-call-ids-per-request |
| 品质(工具调用 id 唯一) | E2E-RUNTIME-unique-tool-call-ids-per-request |
+| C — 对话与流式(循环上下文归属) | E2E-RUNTIME-loop-context-ownership |
+| 品质(循环上下文归属) | E2E-RUNTIME-loop-context-ownership |
| G — 插件宿主生命周期(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |
| 品质(崩溃上报) | E2E-PLUGIN-crash-report-names-the-exit-code |
| F — 持久化(存储的模型绑定数组) | E2E-PROVIDER-stored-binding-array-reads-entry-by-entry |
@@ -8464,8 +8466,23 @@ the latest destination. These assertions measure work counts, not device FPS.
**里程碑:** Post-MVP 回归覆盖。
- **自动化:** `packages/agent-runtime/src/runtime.test.ts` 用真实的运行时覆盖两半:重复历史(丢弃 + 一行日志)与唯一历史
(同一对象、无日志)。
+
- **状态:** 单元测试覆盖;没有端到端驱动对重复转录发出真实提供商请求。
+### E2E-RUNTIME-loop-context-ownership
+
+- **先决条件:** 一个确定性提供商夹具:前两轮各回一次工具调用,并在第二轮之后像用户 Stop 那样结束回合;不使用真实凭据。
+- **步骤:** 发一条提示,让运行时跑完两轮工具调用并在工具轮上结束回合;再发第二条提示。读取运行时保留的状态与夹具收到的出站请求。
+- **预期:** 保留的状态里每个流式辅助消息与每个工具结果都只有一份;没有结果与它回答的调用被隔开;夹具收到的请求对每次调用只带一个结果。
+ 不产生去重日志行,因为请求守卫没有任何东西需要丢弃。
+- **规格:** 03-runtime/02-agent-runtime §5c、08-meta/decisions-log D613。**验收:** C(对话与流)、品质。
+ **里程碑:** Post-MVP 回归覆盖。
+- **自动化:** `packages/agent-runtime/src/runtime.test.ts`(loop context ownership)通过 `runtime.prompt()` 驱动真实 pi 循环,
+ 并读取 `convertToLlm` 交给提供商的视图;`subagent-loop-context.test.ts` 覆盖委托侧的回合边界。两者都到不了适配器自身的输出,
+ 因此由 `tool-call-dedupe.test.ts`(request wire contract)直接驱动 pi-ai 的消息变换,固定「请求把调用与结果隔开时同一个 call id
+ 会拿到两条输出」这一机制。
+- **状态:** 单元测试覆盖;没有端到端驱动从「循环追加过的上下文」构建新回合的请求。
+
### E2E-MCP-HTTP-ACK — HTTP acknowledgement and authorization status
- **Preconditions**: A local mock Streamable HTTP server returns JSON for
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index cb3a1f969..d6f0c59c5 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -4677,3 +4677,22 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.
`apps/desktop/test/default-model-display.test.mjs` 与
`apps/desktop/test/image-generation-default.test.mjs` 固定,
`provider-model-config.test.mjs` 断言新增分支会走这两个判断。
+
+## 2026-09-22 — 循环拥有自己的上下文数组(D613)
+
+- 当某个回合的较晚迭代跑了工具后,`state.messages` 会把那些迭代追加的每条消息存两份,而下一回合的首个请求正是用该数组组装的。
+ 其中“带文本与工具调用的辅助消息”的重复项在请求守卫(D608)之后残留为只剩文本的克隆,卡在调用与回答它的结果之间;pi-ai 随后会为
+ 这个仍处于待配对的调用合成一条 “No result provided” 输出,与真实结果并列,于是同一个 call id 带上了两条输出,端点以
+ `Duplicate tool output for call_id`(HTTP 400,不可重试)拒绝整个回合。该数组会被复用,因此其后每个回合都以同样方式失败,
+ `继续` 也无法让会话恢复。
+- pi-ai 的循环会把每个流式辅助消息与每个工具结果 push 进它拿到的上下文,而它自己的 `message_end` 监听器又把同一个消息对象 push 回
+ `state.messages`。`rebuiltAgentContext()` 返回的正是这个活数组,两次 push 因此落在同一个数组里;现在它返回副本,与 pi 自己的
+ `createContextSnapshot()` 在 `prompt()` 与 `continue()` 里的做法一致。委托侧的回合边界此前交出的也是同一个活数组
+ (`subagent.ts` 的 `prepareNextTurn`),现已同样改为副本。每个消息边界处循环视图与 `state.messages` 携带同样的消息、同样的顺序,
+ 只是不再是同一个数组——这正是把重复项挡在下一回合请求之外的原因。
+- `convertToLlm` 处的请求守卫(D608)改为与提供商实际校验的对象一致:调用与结果的 id 按“上线可见”的那一段比较;当结果与调用在 item
+ 段上不一致时,结果改挂到调用的 id 上;当一条辅助消息里的工具调用全部已被占用时,整条消息被丢弃,而不再保留那个把调用与结果隔开的克隆。
+ 丢弃日志同时给出被移除的消息条数。若一条消息在复写某个已占用调用的同时还带一个新调用,则保留该消息及其新调用——这是守卫接受的唯一一种
+ id 复用;目前没有写入方会产生这种部分复写。
+- 不涉及提供商传输、宿主协议、版本、存储迁移、转录重写,也不改变压缩/保留/预算规则。
+ `03-runtime/02-agent-runtime.md` §5c 与 E2E-RUNTIME-loop-context-ownership 记录了该契约与覆盖情况。
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index c7ff7917a..ddd57a78b 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -1,9 +1,11 @@
import { describe, expect, it, vi } from "vitest";
-import { estimateContextTokens as estimateAgentContextTokens, estimateTokens, type Agent } from "@earendil-works/pi-agent-core";
+import { estimateContextTokens as estimateAgentContextTokens, estimateTokens, type Agent, type AgentMessage } from "@earendil-works/pi-agent-core";
import {
+ createAssistantMessageEventStream,
getCurrentTools,
getCurrentSystemMessage,
toToolDeclaration,
+ type AssistantMessage,
} from "@earendil-works/pi-ai";
import { formatSessionMessage, type SessionMessageOrigin } from "@pi-desktop/shared";
import { estimateContextTokens as estimateTranscriptTokens } from "@earendil-works/pi-ai/utils/estimate";
@@ -8881,3 +8883,199 @@ describe("context estimate calibration", () => {
});
});
});
+
+describe("DesktopAgentRuntime loop context ownership (D613)", () => {
+ /**
+ * Rounds 1 and 2 answer with a tool call and round 3 closes the turn; with
+ * `stopAfterFirstRound` the run ends on the tool round instead, the way a
+ * user Stop does. Every round records the request view the provider saw.
+ */
+ function scriptCallRounds(
+ runtime: DesktopAgentRuntime,
+ requests: AgentMessage[][],
+ options: { stopAfterRound?: number } = {},
+ ): void {
+ let round = 0;
+ (runtime as any).models = {
+ streamSimple: (_model: unknown, context: { messages: AgentMessage[] }) => {
+ round += 1;
+ const current = round;
+ requests.push([...context.messages]);
+ if (current === options.stopAfterRound) {
+ runtime.requestGracefulStop();
+ }
+ const withCall = current <= 2;
+ const message = assistantMessage({
+ content: withCall
+ ? [
+ { type: "text", text: `round ${current}` },
+ {
+ type: "toolCall",
+ id: `call-${current}`,
+ name: "plugin_demo_probe",
+ arguments: {},
+ },
+ ]
+ : [{ type: "text", text: `round ${current}` }],
+ stopReason: withCall ? "toolUse" : "stop",
+ }) as unknown as AssistantMessage;
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: message });
+ stream.push({
+ type: "done",
+ reason: withCall ? "toolUse" : "stop",
+ message,
+ });
+ stream.end(message);
+ });
+ return stream;
+ },
+ };
+ }
+
+ function probeRuntime(
+ requests: AgentMessage[][],
+ options: { stopAfterRound?: number } = {},
+ ): DesktopAgentRuntime {
+ const runtime = createRuntime({
+ host: {
+ call: vi.fn(async (method: string) =>
+ method === "tools.execute"
+ ? {
+ ok: true,
+ content: {
+ content: [{ type: "text", text: "probe ok" }],
+ details: {},
+ },
+ }
+ : undefined,
+ ),
+ } as never,
+ pluginTools: [
+ { name: "plugin_demo_probe", description: "probe", parameters: {} },
+ ],
+ });
+ scriptCallRounds(runtime, requests, options);
+ return runtime;
+ }
+
+ function textBlocks(messages: AgentMessage[]): string[] {
+ return messages.flatMap((message) =>
+ message.role === "assistant"
+ ? ((message as { content: unknown[] }).content ?? [])
+ .filter(
+ (block): block is { type: string; text: string } =>
+ typeof block === "object" &&
+ block !== null &&
+ (block as { type?: string }).type === "text",
+ )
+ .map((block) => block.text)
+ : [],
+ );
+ }
+
+ function toolCallIds(messages: AgentMessage[]): string[] {
+ return messages.flatMap((message) =>
+ message.role === "assistant"
+ ? ((message as { content: unknown[] }).content ?? [])
+ .filter(
+ (block): block is { type: string; id: string } =>
+ typeof block === "object" &&
+ block !== null &&
+ (block as { type?: string }).type === "toolCall",
+ )
+ .map((block) => block.id)
+ : [],
+ );
+ }
+
+ function resultIds(messages: AgentMessage[]): string[] {
+ return messages
+ .filter((message) => message.role === "toolResult")
+ .map((message) => (message as { toolCallId?: string }).toolCallId ?? "");
+ }
+
+ /** Every result has to sit directly behind the assistant that carries its call. */
+ function expectResultsFollowTheirCalls(messages: AgentMessage[]): void {
+ for (let index = 0; index < messages.length; index += 1) {
+ const message = messages[index] as { role?: string; toolCallId?: string };
+ if (message.role !== "toolResult") continue;
+ let previous = index - 1;
+ while (
+ previous >= 0 &&
+ (messages[previous] as { role?: string }).role === "system"
+ ) {
+ previous -= 1;
+ }
+ const carrier = messages[previous] as { role?: string; content?: unknown[] };
+ expect(carrier?.role).toBe("assistant");
+ expect(
+ (carrier?.content ?? []).some(
+ (block) =>
+ typeof block === "object" &&
+ block !== null &&
+ (block as { type?: string }).type === "toolCall" &&
+ (block as { id?: string }).id === message.toolCallId,
+ ),
+ ).toBe(true);
+ }
+ }
+
+ it("stores one copy of every message the loop appends", async () => {
+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ const requests: AgentMessage[][] = [];
+ const runtime = probeRuntime(requests);
+
+ await runtime.prompt("first task", "user-1", "turn-1");
+
+ // The loop appends the streamed assistant message and the tool results to
+ // the context it was handed; pi's `message_end` listener appends the same
+ // object to the state. Sharing one array stored every message of the
+ // later rounds twice (D613).
+ const state = (runtime as any).agent.state.messages as AgentMessage[];
+ expect(textBlocks(state)).toEqual(["round 1", "round 2", "round 3"]);
+ expect(toolCallIds(state)).toEqual(["call-1", "call-2"]);
+ expect(resultIds(state)).toEqual(["call-1", "call-2"]);
+ // Nothing was duplicated, so the request guard had nothing to report.
+ const log = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");
+ expect(log).not.toContain("duplicate tool call");
+
+ await runtime.dispose();
+ } finally {
+ stderr.mockRestore();
+ }
+ });
+
+ it("opens the next turn from a stopped tool round without guard repairs", async () => {
+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ const requests: AgentMessage[][] = [];
+ const runtime = probeRuntime(requests, { stopAfterRound: 2 });
+
+ // A Stop ends the run on the second tool round, so those messages are the
+ // ones the next turn's first request is built from — the request that
+ // production rejected with `Duplicate tool output for call_id` (D613).
+ await runtime.prompt("first task", "user-1", "turn-1");
+
+ requests.length = 0;
+ await runtime.prompt("second task", "user-2", "turn-2");
+
+ // `streamSimple` sees the view `convertToLlm` produced, so this is the
+ // request the guard let through unrepaired, not the adapter's output: the
+ // second output pi-ai synthesizes for an unanswered call is pinned
+ // directly in `tool-call-dedupe.test.ts` (request wire contract).
+ const wire = requests[0]!;
+ expect(toolCallIds(wire)).toEqual(["call-1", "call-2"]);
+ expect(resultIds(wire)).toEqual(["call-1", "call-2"]);
+ expectResultsFollowTheirCalls(wire);
+ const log = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");
+ expect(log).not.toContain("duplicate tool call");
+
+ await runtime.dispose();
+ } finally {
+ stderr.mockRestore();
+ }
+ });
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index d9a19eb80..8fa521e69 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -5957,7 +5957,19 @@ Delegation rules:
this.setAgentMessages(messages);
this.setAgentTools(tools);
return {
- messages: this.agent.state.messages,
+ // The loop owns its context array. pi appends every streamed assistant
+ // message and every tool result to the context it was handed, and its own
+ // `message_end` listener appends the same message object to
+ // `state.messages`; handing over the live array makes both land in one
+ // array, so every message of a run's later iterations is stored twice.
+ // The next turn is then built from that array, and the duplicate of an
+ // assistant message that carries text plus a tool call survives the
+ // request guard as a text-only clone sitting between the call and the
+ // result answering it. pi-ai then closes the still-pending call with a
+ // synthesized "No result provided" output next to the real one — two
+ // outputs for one call id, which the provider rejects (D613).
+ // `createContextSnapshot()` copies for the same reason.
+ messages: [...this.agent.state.messages],
tools,
systemPrompt: this.agent.state.systemPrompt,
} as AgentContext;
diff --git a/packages/agent-runtime/src/subagent-loop-context.test.ts b/packages/agent-runtime/src/subagent-loop-context.test.ts
new file mode 100644
index 000000000..e1e670519
--- /dev/null
+++ b/packages/agent-runtime/src/subagent-loop-context.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from "vitest";
+import type { SubagentDefinition } from "@pi-desktop/shared";
+import { SubagentRun } from "./subagent.js";
+import type { RuntimeProviderConfig } from "./provider-binding.js";
+
+/**
+ * What a turn boundary decides — compact, degrade, or report an overflow — is
+ * covered by `subagent-context.test.ts`. This file pins the update the delegate
+ * hands the agent loop instead, because that array is the context every later
+ * iteration of a run appends to (D613).
+ */
+vi.mock("./subagent-context.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./subagent-context.js")>();
+ return {
+ ...actual,
+ prepareDelegateTurnContext: vi.fn(async () => ({
+ kind: "degraded" as const,
+ messages: [],
+ tokensBefore: 1,
+ })),
+ };
+});
+
+const provider: RuntimeProviderConfig = {
+ id: "local",
+ name: "Local",
+ baseUrl: "http://127.0.0.1:11434/v1",
+ modelId: "local-model",
+ apiKey: "",
+ authKind: "none",
+ supportsReasoning: false,
+ supportedThinkingLevels: ["off"],
+};
+
+function definition(): SubagentDefinition {
+ return {
+ name: "explorer",
+ description: "Search the workspace and report findings.",
+ tools: ["Read"],
+ prompt: "Find the answer and report it.",
+ source: "builtin",
+ };
+}
+
+/** The agent-loop surface the delegate wires a run through. */
+type DelegateAgent = {
+ state: { messages: unknown[] };
+ prepareNextTurnWithContext?: (
+ turn: unknown,
+ signal: AbortSignal,
+ ) => Promise<{ context?: { messages: unknown[] } } | undefined>;
+};
+
+function createDelegate(): DelegateAgent {
+ const run = new SubagentRun({
+ definition: definition(),
+ sessionId: "session-1",
+ turnId: "turn-1",
+ parentToolCallId: "task-1",
+ task: "Find where the permission dialog is rendered.",
+ provider,
+ thinkingLevel: "off",
+ systemPrompt: "system",
+ tools: [],
+ onEvent: () => undefined,
+ });
+ return (run as unknown as { agent: DelegateAgent }).agent;
+}
+
+/** Minimal pi-ai assistant message, shaped like the ones the loop appends. */
+function assistantMessage(text: string) {
+ return {
+ role: "assistant",
+ api: "openai-completions",
+ provider: "local",
+ model: "local-model",
+ stopReason: "stop",
+ timestamp: 2,
+ usage: {
+ input: 10,
+ output: 5,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 15,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ content: [{ type: "text", text }],
+ };
+}
+
+describe("SubagentRun loop context ownership (D613)", () => {
+ it("hands the loop its own context array at a protected turn boundary", async () => {
+ const agent = createDelegate();
+ agent.state.messages = [
+ { role: "system", content: "system", timestamp: 0 },
+ { role: "user", content: "Find the permission dialog.", timestamp: 1 },
+ ];
+
+ const update = await agent.prepareNextTurnWithContext!(
+ { toolResults: [] },
+ new AbortController().signal,
+ );
+
+ // The boundary protected the request, so it did hand the loop a context.
+ expect(update?.context?.messages).toBeDefined();
+ const carried = update!.context!.messages;
+ // pi's loop appends every streamed assistant message and tool result to the
+ // array it was handed, while its `message_end` listener appends the same
+ // message to the agent state. Handing over the state's live array would
+ // store every message of the run's later iterations twice, and the trailing
+ // row `useNextModel` slices off before a fallback would then leave an
+ // assistant row at the head of what `continue()` refuses to resume from
+ // (D613).
+ expect(carried).not.toBe(agent.state.messages);
+ const streamed = assistantMessage("round 2");
+ carried.push(streamed);
+ expect(agent.state.messages).not.toContain(streamed);
+ });
+});
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index ed46b8441..ff780d6c5 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -403,7 +403,14 @@ export class SubagentRun {
}
return {
context: {
- messages: this.agent.state.messages,
+ // The loop owns its context array: pi appends every streamed assistant
+ // message and every tool result to the array it was handed, while its
+ // own `message_end` listener appends the same message to
+ // `state.messages`. Handing over the live array stores each message of
+ // the run's later iterations twice, which doubles the estimate at the
+ // next boundary and leaves `useNextModel` a trailing assistant row it
+ // cannot resume from (D613).
+ messages: [...this.agent.state.messages],
tools: this.agent.state.tools,
},
};
diff --git a/packages/agent-runtime/src/tool-call-dedupe.test.ts b/packages/agent-runtime/src/tool-call-dedupe.test.ts
new file mode 100644
index 000000000..285ce7773
--- /dev/null
+++ b/packages/agent-runtime/src/tool-call-dedupe.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it, vi } from "vitest";
+import type { AgentMessage } from "@earendil-works/pi-agent-core";
+import { transformMessages } from "@earendil-works/pi-ai/api/transform-messages";
+import {
+ dedupeToolCallMessages,
+ reportDuplicateToolCallDrop,
+} from "./tool-call-dedupe.js";
+
+/** Only the fields the guard reads: the role, the blocks, and the call id. */
+function assistantMessage(content: unknown[]): AgentMessage {
+ return { role: "assistant", content, timestamp: 1 } as unknown as AgentMessage;
+}
+
+function text(value: string) {
+ return { type: "text", text: value };
+}
+
+function toolCall(id: string, name = "Read") {
+ return { type: "toolCall", id, name, arguments: {} };
+}
+
+function toolResult(toolCallId: string, value = "ok"): AgentMessage {
+ return {
+ role: "toolResult",
+ toolCallId,
+ toolName: "Read",
+ content: [text(value)],
+ isError: false,
+ timestamp: 2,
+ } as unknown as AgentMessage;
+}
+
+function callIds(messages: AgentMessage[]): string[] {
+ return messages.flatMap((message) =>
+ message.role === "assistant"
+ ? ((message as { content: unknown[] }).content ?? [])
+ .filter(
+ (block): block is { type: string; id: string } =>
+ typeof block === "object" &&
+ block !== null &&
+ (block as { type?: string }).type === "toolCall",
+ )
+ .map((block) => block.id)
+ : [],
+ );
+}
+
+function resultIds(messages: AgentMessage[]): string[] {
+ return messages
+ .filter((message) => message.role === "toolResult")
+ .map((message) => (message as { toolCallId?: string }).toolCallId ?? "");
+}
+
+describe("dedupeToolCallMessages", () => {
+ it("returns the request view unchanged when every call id is unique", () => {
+ const messages = [
+ assistantMessage([text("reading"), toolCall("call-1")]),
+ toolResult("call-1"),
+ assistantMessage([text("done")]),
+ ];
+
+ const drop = dedupeToolCallMessages(messages);
+
+ expect(drop.messages).toBe(messages);
+ expect(drop.droppedCount).toBe(0);
+ expect(drop.droppedMessages).toBe(0);
+ expect(drop.droppedIds).toEqual([]);
+ });
+
+ it("drops a replayed round as one snapshot and one duplicate result", () => {
+ // The shape production hit: pi's loop appends the streamed assistant
+ // message and its tool result to the context it was handed, while its own
+ // `message_end` listener appends the same objects to the session state, so
+ // one round reached the next turn as two copies of each (D613). The
+ // assistant message carries text *and* a call, so dropping only the call
+ // block would leave a text-only clone between the call and its result.
+ const assistant = assistantMessage([
+ text("reading the file"),
+ toolCall("call-1|item-1"),
+ ]);
+ const result = toolResult("call-1|item-1");
+
+ const drop = dedupeToolCallMessages([assistant, assistant, result, result]);
+
+ expect(drop.droppedCount).toBe(2);
+ expect(drop.droppedMessages).toBe(1);
+ expect(drop.droppedIds).toEqual(["call-1"]);
+ // One call, then the result that answers it: nothing sits between them.
+ expect(drop.messages).toHaveLength(2);
+ expect(drop.messages[0]).toBe(assistant);
+ expect(drop.messages[1]).toBe(result);
+ expect(callIds(drop.messages)).toEqual(["call-1|item-1"]);
+ expect(resultIds(drop.messages)).toEqual(["call-1|item-1"]);
+ });
+
+ it("treats ids that differ only after the separator as one call", () => {
+ // Only the part before the separator reaches the provider as `call_id`, so
+ // two entries whose item half differs still collide on the wire.
+ const assistant = assistantMessage([toolCall("call-1|item-1")]);
+
+ const drop = dedupeToolCallMessages([
+ assistant,
+ toolResult("call-1|item-2"),
+ toolResult("call-1|item-3"),
+ ]);
+
+ expect(drop.droppedCount).toBe(1);
+ expect(drop.droppedMessages).toBe(0);
+ expect(drop.messages).toHaveLength(2);
+ // The surviving result answers the call under the call's own composite id,
+ // so pi-ai pairs them instead of synthesizing a second output for the id.
+ expect(resultIds(drop.messages)).toEqual(["call-1|item-1"]);
+ });
+
+ it("keeps a new call in a message that also replays an older one", () => {
+ const first = assistantMessage([text("first"), toolCall("call-1")]);
+ const second = assistantMessage([
+ text("second"),
+ toolCall("call-1"),
+ toolCall("call-2"),
+ ]);
+
+ const drop = dedupeToolCallMessages([
+ first,
+ second,
+ toolResult("call-1"),
+ toolResult("call-2"),
+ ]);
+
+ expect(drop.droppedCount).toBe(1);
+ expect(drop.droppedMessages).toBe(0);
+ // Only the replayed block goes: the message also carries a new call, so it
+ // stays, and the guard does not reorder messages to close the gap the
+ // dropped call leaves behind. No writer reaches this partial replay today —
+ // the runtime's own duplication repeats a message whole, which is the case
+ // dropped whole above.
+ expect(drop.messages.map((message) => message.role)).toEqual([
+ "assistant",
+ "assistant",
+ "toolResult",
+ "toolResult",
+ ]);
+ expect(callIds(drop.messages)).toEqual(["call-1", "call-2"]);
+ expect(resultIds(drop.messages)).toEqual(["call-1", "call-2"]);
+ });
+
+ it("leaves a call whose result never arrived to pi-ai's placeholder", () => {
+ const messages = [assistantMessage([toolCall("call-1")])];
+
+ expect(dedupeToolCallMessages(messages).messages).toBe(messages);
+ });
+
+ it("reports the wire ids and how many messages it removed", () => {
+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
+ try {
+ reportDuplicateToolCallDrop("session-1", {
+ messages: [],
+ droppedCount: 2,
+ droppedMessages: 1,
+ droppedIds: ["call-1"],
+ });
+ const line = stderr.mock.calls.map(([chunk]) => String(chunk)).join("");
+ expect(line).toContain(
+ "dropped 2 duplicate tool call entries (1 replayed message)",
+ );
+ expect(line).toContain("session=session-1");
+ expect(line).toContain("ids=call-1");
+ } finally {
+ stderr.mockRestore();
+ }
+ });
+});
+
+/**
+ * The failure this guard exists for is invisible in the runtime's own view of a
+ * request: pi-ai synthesizes the second output inside its provider transform,
+ * after the point a scripted provider can capture. Driving that transform is
+ * what pins the mechanism the endpoint rejects (D613).
+ */
+describe("request wire contract (D613)", () => {
+ /** Only the fields the transform reads for a non-normalizing API. */
+ const model = {
+ api: "openai-completions",
+ id: "test-model",
+ provider: "test",
+ input: ["text"],
+ } as never;
+
+ /** Every output the provider would validate for this request. */
+ function wireOutputIds(messages: AgentMessage[]): string[] {
+ return transformMessages(messages as never, model)
+ .filter((message) => message.role === "toolResult")
+ .map((message) => String((message as { toolCallId?: string }).toolCallId));
+ }
+
+ it("answers a call the request separates from its result twice", () => {
+ // The shape production sent: the replayed clone of the assistant message
+ // sits between the call and the result answering it, so the transform
+ // closes the call it can no longer see answered — `Duplicate tool output
+ // for call_id`.
+ const call = assistantMessage([text("reading"), toolCall("call-1")]);
+ const clone = assistantMessage([text("reading")]);
+
+ expect(wireOutputIds([call, clone, toolResult("call-1")])).toEqual([
+ "call-1",
+ "call-1",
+ ]);
+ });
+
+ it("answers a replayed round once after the guard drops it whole", () => {
+ const call = assistantMessage([text("reading"), toolCall("call-1")]);
+ const replay = assistantMessage([text("reading"), toolCall("call-1")]);
+
+ const drop = dedupeToolCallMessages([
+ call,
+ replay,
+ toolResult("call-1"),
+ toolResult("call-1"),
+ ]);
+
+ expect(drop.droppedMessages).toBe(1);
+ expect(wireOutputIds(drop.messages)).toEqual(["call-1"]);
+ });
+});
diff --git a/packages/agent-runtime/src/tool-call-dedupe.ts b/packages/agent-runtime/src/tool-call-dedupe.ts
index 7dc35e825..ca44f65ef 100644
--- a/packages/agent-runtime/src/tool-call-dedupe.ts
+++ b/packages/agent-runtime/src/tool-call-dedupe.ts
@@ -7,6 +7,8 @@ const MAX_LOGGED_DUPLICATE_TOOL_CALLS = 8;
export type DuplicateToolCallDrop = {
messages: AgentMessage[];
droppedCount: number;
+ /** Messages removed whole because every tool call in them was a replay. */
+ droppedMessages: number;
droppedIds: string[];
};
@@ -14,20 +16,54 @@ function isRecord(value: unknown): value is RecordLike {
return typeof value === "object" && value !== null;
}
+/**
+ * The id a provider validates, which is not always the id we store.
+ *
+ * PI-Desktop keeps pi-ai's composite Responses call id (`<call_id>|<item_id>`)
+ * so a replay can address the server-side item, and the adapter sends only the
+ * part before the separator as `call_id`. Two entries whose composite ids
+ * differ in the item half therefore still collide on the wire, so every
+ * comparison below uses this wire-visible id (D613).
+ */
+function wireCallId(id: string): string {
+ const separator = id.indexOf("|");
+ return separator < 0 ? id : id.slice(0, separator);
+}
+
/**
* Keep the first call and result for every tool-call id in a 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
* avoids copying messages that are already valid.
+ *
+ * A request that separates a call from its result is not merely untidy: pi-ai
+ * closes a call whose result does not follow it with a synthesized
+ * "No result provided" output *and* sends the real result, so one call id
+ * carries two outputs and the endpoint rejects the whole turn (D608, D613).
+ * Dropping a replayed assistant message whole — rather than keeping the text it
+ * is left with — is what keeps that separation out of the request, and the
+ * duplication the runtime itself produces repeats a message whole, so that is
+ * the shape the drop covers. A message that replays one call while carrying a
+ * new one keeps its new call where it is, which leaves the replayed call's own
+ * 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.
*/
export function dedupeToolCallMessages(
messages: AgentMessage[],
): DuplicateToolCallDrop {
- const claimedCalls = new Set<string>();
- const claimedResults = new Set<string>();
+ const keptCalls = new Map<string, string>();
+ const keptResults = new Set<string>();
+ /** Wire ids whose call is still waiting for a result in this request. */
+ const openCalls = new Map<string, number>();
const droppedIds = new Set<string>();
let droppedCount = 0;
+ let droppedMessages = 0;
const note = (id: string) => {
droppedCount += 1;
if (droppedIds.size < MAX_LOGGED_DUPLICATE_TOOL_CALLS) {
@@ -43,30 +79,59 @@ export function dedupeToolCallMessages(
next.push(message);
continue;
}
+ let calls = 0;
const kept = content.filter((block) => {
if (!isRecord(block) || block.type !== "toolCall") return true;
const id = typeof block.id === "string" ? block.id : undefined;
if (id === undefined) return true;
- if (claimedCalls.has(id)) {
- note(id);
+ calls += 1;
+ const wire = wireCallId(id);
+ if (keptCalls.has(wire)) {
+ note(wire);
return false;
}
- claimedCalls.add(id);
+ keptCalls.set(wire, id);
+ openCalls.set(wire, (openCalls.get(wire) ?? 0) + 1);
return true;
});
- if (kept.length === 0 && content.length > 0) continue;
- next.push(kept.length === content.length ? message : ({ ...message, content: kept } as AgentMessage));
+ // Every call this message carried was already claimed by an earlier one,
+ // so the message is that earlier message's snapshot rather than new
+ // context. Its text is a copy too, and keeping the copy would place a
+ // message between a call and the result answering it.
+ if (
+ calls > 0 &&
+ kept.every((block) => !isRecord(block) || block.type !== "toolCall")
+ ) {
+ droppedMessages += 1;
+ continue;
+ }
+ next.push(
+ kept.length === content.length ? message : ({ ...message, content: kept } as AgentMessage),
+ );
continue;
}
if (message.role === "toolResult") {
const id = (message as { toolCallId?: unknown }).toolCallId;
if (typeof id === "string") {
- if (claimedResults.has(id)) {
- note(id);
+ const wire = wireCallId(id);
+ if (keptResults.has(wire)) {
+ note(wire);
continue;
}
- claimedResults.add(id);
+ keptResults.add(wire);
+ const waiting = openCalls.get(wire) ?? 0;
+ if (waiting > 0) {
+ openCalls.set(wire, waiting - 1);
+ const owner = keptCalls.get(wire);
+ // One call id, one result: pi-ai pairs a result to its call by the
+ // 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) {
+ next.push({ ...message, toolCallId: owner } as AgentMessage);
+ continue;
+ }
+ }
}
}
next.push(message);
@@ -75,6 +140,7 @@ export function dedupeToolCallMessages(
return {
messages: droppedCount === 0 ? messages : next,
droppedCount,
+ droppedMessages,
droppedIds: [...droppedIds],
};
}
@@ -84,9 +150,15 @@ export function reportDuplicateToolCallDrop(
drop: DuplicateToolCallDrop,
): void {
if (drop.droppedCount === 0) return;
+ const replayed =
+ drop.droppedMessages > 0
+ ? ` (${drop.droppedMessages} replayed message${
+ drop.droppedMessages === 1 ? "" : "s"
+ })`
+ : "";
process.stderr.write(
`[agent-runtime] dropped ${drop.droppedCount} duplicate tool call ${
drop.droppedCount === 1 ? "entry" : "entries"
- } before the request (session=${sessionId} ids=${drop.droppedIds.join(",")})\n`,
+ }${replayed} before the request (session=${sessionId} ids=${drop.droppedIds.join(",")})\n`,
);
}