Skip to content

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

fix(agent-runtime): keep length-stopped and mid-batch-interrupted calls out of compaction file ops

liuzixiang4d8d4a89e0d9
diff --git a/packages/agent-runtime/src/pi-file-ops.test.ts b/packages/agent-runtime/src/pi-file-ops.test.ts
index f3e3d9c04..00fb6ff0d 100644
--- a/packages/agent-runtime/src/pi-file-ops.test.ts
+++ b/packages/agent-runtime/src/pi-file-ops.test.ts
@@ -12,7 +12,7 @@ function toolCallWithArguments(
name: string,
args: Record<string, unknown>,
id = "call-1",
- stopReason: "toolUse" | "error" | "aborted" | "deferred" = "toolUse",
+ stopReason: "toolUse" | "error" | "aborted" | "deferred" | "length" = "toolUse",
): AgentMessage {
return {
role: "assistant",
@@ -37,6 +37,20 @@ function toolCallMessage(name: string, path: string, id = "call-1"): AgentMessag
return toolCallWithArguments(name, { path }, id);
}
+function toolResultMessage(id: string, isError = false): AgentMessage {
+ // Mirrors agent-loop's createToolResultMessage: every executed call gains a
+ // result row stamped with isError.
+ return {
+ role: "toolResult",
+ toolCallId: id,
+ toolName: "read",
+ isError,
+ content: [],
+ details: {},
+ timestamp: 3,
+ } as unknown as AgentMessage;
+}
+
function userMessage(text: string, timestamp: number): AgentMessage {
return { role: "user", content: [{ type: "text", text }], timestamp } as AgentMessage;
}
@@ -46,7 +60,7 @@ function messageEntry(id: string, message: AgentMessage, second: number): Entry
type: "message",
id,
parentId: null,
- timestamp: `2026-09-22T00:00:0${second}.000Z`,
+ timestamp: `2026-09-22T00:00:${String(second).padStart(2, "0")}.000Z`,
message,
} as unknown as Entry;
}
@@ -129,8 +143,10 @@ describe("pi's file-op collection through the adapter", () => {
const entries = [
messageEntry("u1", userMessage("read src/a.txt and then edit src/a.ts", 1), 1),
messageEntry("a1", toolCallMessage("Read", "src/a.txt"), 2),
- messageEntry("a2", toolCallMessage("Edit", "src/a.ts", "call-2"), 3),
- messageEntry("u2", userMessage("latest question", 4), 4),
+ messageEntry("r1", toolResultMessage("call-1"), 3),
+ messageEntry("a2", toolCallMessage("Edit", "src/a.ts", "call-2"), 4),
+ messageEntry("r2", toolResultMessage("call-2"), 5),
+ messageEntry("u2", userMessage("latest question", 6), 6),
];
it("collects the files a checkpoint used to report as empty", () => {
@@ -165,9 +181,12 @@ describe("pi's file-op collection through the adapter", () => {
const entries = [
messageEntry("u1", userMessage("touch the files", 1), 1),
messageEntry("a1", toolCallWithArguments("Read", { file_path: "src/a.txt" }), 2),
- messageEntry("a2", toolCallWithArguments("Edit", { filepath: "src/b.ts" }, "call-2"), 3),
- messageEntry("a3", toolCallWithArguments("Write", { file: "src/c.ts" }, "call-3"), 4),
- messageEntry("u2", userMessage("latest question", 5), 5),
+ messageEntry("r1", toolResultMessage("call-1"), 3),
+ messageEntry("a2", toolCallWithArguments("Edit", { filepath: "src/b.ts" }, "call-2"), 4),
+ messageEntry("r2", toolResultMessage("call-2"), 5),
+ messageEntry("a3", toolCallWithArguments("Write", { file: "src/c.ts" }, "call-3"), 6),
+ messageEntry("r3", toolResultMessage("call-3"), 7),
+ messageEntry("u2", userMessage("latest question", 8), 8),
];
const preparation = preparationOf(entries, true);
@@ -236,6 +255,20 @@ describe("pi's file-op collection through the adapter", () => {
),
messageEntry("u2", userMessage("latest question", 9), 9),
];
+ // Result rows for the calls whose paths the assertions expect: a real
+ // transcript pairs every executed call with a non-error toolResult row.
+ const resultRows = [
+ messageEntry("r1", toolResultMessage("call-1"), 10),
+ messageEntry("r3", toolResultMessage("call-3"), 11),
+ messageEntry("r4", toolResultMessage("call-4"), 12),
+ messageEntry("r5", toolResultMessage("call-5"), 13),
+ messageEntry("r6", toolResultMessage("call-6"), 14),
+ ];
+ entries.splice(2, 0, resultRows[0]!);
+ entries.splice(5, 0, resultRows[1]!);
+ entries.splice(7, 0, resultRows[2]!);
+ entries.splice(9, 0, resultRows[3]!);
+ entries.splice(11, 0, resultRows[4]!);
const preparation = preparationOf(entries, true);
@@ -257,13 +290,14 @@ describe("pi's file-op collection through the adapter", () => {
const entries = [
messageEntry("u1", userMessage("edit src/real.ts", 1), 1),
messageEntry("a1", toolCallWithArguments("Edit", { path: "src/real.ts" }, "call-1"), 2),
- messageEntry("u2", userMessage("write src/never.ts", 3), 3),
+ messageEntry("r1", toolResultMessage("call-1"), 3),
+ messageEntry("u2", userMessage("write src/never.ts", 4), 4),
messageEntry(
"a2",
toolCallWithArguments("Write", { path: "src/never.ts", content: "x" }, "call-2", "aborted"),
- 4,
+ 5,
),
- messageEntry("u3", userMessage("latest question", 5), 5),
+ messageEntry("u3", userMessage("latest question", 6), 6),
];
const preparation = preparationOf(entries, true);
@@ -272,6 +306,70 @@ describe("pi's file-op collection through the adapter", () => {
expect([...preparation!.fileOps.written]).toEqual([]);
expect([...preparation!.fileOps.edited]).toEqual(["src/real.ts"]);
});
+
+ it("leaves a length-stopped turn's calls out: pi fails them all unexecuted", () => {
+ // agent-loop fails every call on a `length` message ("was not executed:
+ // the response hit the output token limit") without running any of them —
+ // the arguments themselves may be truncated mid-JSON, so even a
+ // half-written path value must not reach the checkpoint.
+ const entries = [
+ messageEntry("u1", userMessage("write the config", 1), 1),
+ messageEntry(
+ "a1",
+ toolCallWithArguments("Write", { path: "src/trunc" }, "call-1", "length"),
+ 2,
+ ),
+ messageEntry("r1", toolResultMessage("call-1", true), 3),
+ messageEntry("u2", userMessage("latest question", 4), 4),
+ ];
+
+ const preparation = preparationOf(entries, true);
+
+ expect(preparation).toBeDefined();
+ expect([...preparation!.fileOps.written]).toEqual([]);
+ expect([...preparation!.fileOps.edited]).toEqual([]);
+ expect([...preparation!.fileOps.read]).toEqual([]);
+ });
+
+ it("counts only the calls a mid-batch Stop let finish", () => {
+ // A Stop pressed during tool execution breaks a sequential batch before
+ // preparing the remaining calls: the trailing toolCall blocks stay on the
+ // assistant message (stopReason is still "toolUse") but never gain
+ // result rows, and only the finished call touched its file.
+ const batch = {
+ role: "assistant",
+ content: [
+ { type: "toolCall", id: "call-1", name: "Edit", arguments: { path: "src/done.ts" } },
+ { type: "toolCall", id: "call-2", name: "Edit", arguments: { path: "src/skipped-a.ts" } },
+ { type: "toolCall", id: "call-3", name: "Edit", arguments: { path: "src/skipped-b.ts" } },
+ ],
+ api: "openai-completions",
+ provider: "local",
+ model: "local-model",
+ usage: {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "toolUse",
+ timestamp: 2,
+ } as AgentMessage;
+ const entries = [
+ messageEntry("u1", userMessage("edit the three files", 1), 1),
+ messageEntry("a1", batch, 2),
+ messageEntry("r1", toolResultMessage("call-1"), 3),
+ messageEntry("u2", userMessage("latest question", 4), 4),
+ ];
+
+ const preparation = preparationOf(entries, true);
+
+ expect(preparation).toBeDefined();
+ expect([...preparation!.fileOps.edited]).toEqual(["src/done.ts"]);
+ expect([...preparation!.fileOps.written]).toEqual([]);
+ });
});
describe("collectMessageFileOperations", () => {
@@ -303,4 +401,41 @@ describe("collectMessageFileOperations", () => {
expect([...ops.read]).toEqual([]);
expect([...ops.edited]).toEqual(["src/done.ts"]);
});
+
+ it("with executed call ids, counts a toolUse call only on a completed run", () => {
+ const ops = {
+ read: new Set<string>(),
+ written: new Set<string>(),
+ edited: new Set<string>(),
+ };
+ const executed = new Set(["ok-1"]);
+
+ collectMessageFileOperations(
+ toolCallWithArguments("edit", { path: "src/ran.ts" }, "ok-1", "toolUse"),
+ ops,
+ executed,
+ );
+ // A call whose result row only reports an error, or that has no row at
+ // all (mid-batch Stop), never took effect.
+ collectMessageFileOperations(
+ toolCallWithArguments("edit", { path: "src/failed.ts" }, "bad", "toolUse"),
+ ops,
+ executed,
+ );
+ collectMessageFileOperations(
+ toolCallWithArguments("edit", { path: "src/no-row.ts" }, "missing", "toolUse"),
+ ops,
+ executed,
+ );
+ // The stop-reason guard covers a whole `length` batch by itself.
+ collectMessageFileOperations(
+ toolCallWithArguments("write", { path: "src/length.ts" }, "c9", "length"),
+ ops,
+ executed,
+ );
+
+ expect([...ops.edited]).toEqual(["src/ran.ts"]);
+ expect([...ops.written]).toEqual([]);
+ expect([...ops.read]).toEqual([]);
+ });
});
diff --git a/packages/agent-runtime/src/pi-runtime-compaction-plan.ts b/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
index 832fdd90a..179ffeb88 100644
--- a/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
+++ b/packages/agent-runtime/src/pi-runtime-compaction-plan.ts
@@ -149,7 +149,11 @@ function fileOperationPath(args: unknown): string | undefined {
* Assistant stop reasons whose tool calls never ran.
*
* pi-agent-core returns before `executeToolCalls` when a turn stops with
- * `error` or `aborted`, so those tool results stay empty. `deferred` is the
+ * `error` or `aborted`, so those tool results stay empty. A `length` stop is
+ * the opposite guarantee: agent-loop fails every tool call on the message
+ * with an error result ("was not executed: the response hit the output
+ * token limit") without running any of them, because the arguments
+ * themselves may be truncated mid-JSON. `deferred` is the
* third reason compaction-tail drops from the rebuilt context
* (`DROPPED_STOP_REASONS`); session-context and subagent-context treat the
* same three rows as transcript-only. The toolCall blocks stay on the
@@ -163,17 +167,39 @@ const UNEXECUTED_ASSISTANT_STOP_REASONS: ReadonlySet<string> = new Set([
"error",
"aborted",
"deferred",
+ "length",
]);
+/**
+ * Ids of tool calls whose transcript shows a completed, non-error run.
+ * pi-agent-core stamps every toolResult row with `isError`; calls whose only
+ * row is an error row (a failed call touched nothing) or that has no row at
+ * all (a Stop pressed mid-batch breaks a sequential batch before preparing
+ * the remaining calls, and a parallel batch marks the skipped calls aborted)
+ * never took effect on disk.
+ */
+function executedToolCallIds(messages: AgentMessage[]): Set<string> {
+ const ids = new Set<string>();
+ for (const message of messages) {
+ if (message.role !== "toolResult") continue;
+ const row = message as AgentMessage & { toolCallId?: unknown; isError?: unknown };
+ if (row.isError === true) continue;
+ if (typeof row.toolCallId === "string") ids.add(row.toolCallId);
+ }
+ return ids;
+}
+
/** Record one assistant message's Read/Write/Edit paths. Mutates `fileOps`. */
export function collectMessageFileOperations(
message: AgentMessage,
fileOps: FileOperations,
+ executedCallIds?: ReadonlySet<string>,
): void {
if (message.role !== "assistant" || !Array.isArray(message.content)) return;
if (UNEXECUTED_ASSISTANT_STOP_REASONS.has(message.stopReason)) return;
for (const block of message.content) {
if (!block || block.type !== "toolCall") continue;
+ if (executedCallIds && !executedCallIds.has(block.id)) continue;
const path = fileOperationPath(block.arguments);
if (!path) continue;
switch (block.name) {
@@ -203,7 +229,8 @@ function collectFileOperations(
}
}
}
- for (const message of messages) collectMessageFileOperations(message, fileOps);
+ const executedCallIds = executedToolCallIds(messages);
+ for (const message of messages) collectMessageFileOperations(message, fileOps, executedCallIds);
return fileOps;
}
diff --git a/packages/agent-runtime/src/reasoning-replay.test.ts b/packages/agent-runtime/src/reasoning-replay.test.ts
index f8eb25425..b76653b45 100644
--- a/packages/agent-runtime/src/reasoning-replay.test.ts
+++ b/packages/agent-runtime/src/reasoning-replay.test.ts
@@ -26,7 +26,7 @@ function assistant(
thinking: string,
text = "ok",
thinkingSignature = "reasoning_content",
- stopReason: "stop" | "error" | "aborted" | "deferred" = "stop",
+ stopReason: "stop" | "error" | "aborted" | "deferred" | "length" = "stop",
): AgentMessage {
const content: unknown[] = [
{ type: "thinking", thinking, thinkingSignature },
@@ -140,6 +140,14 @@ describe("harvestRetainedReasoning", () => {
]);
expect(turns.map((turn) => turn.thinking)).toEqual(["kept"]);
});
+
+ it("skips a length-stopped turn: the token limit cut its think mid-sentence", () => {
+ const turns = harvestRetainedReasoning([
+ assistant("settled plan"),
+ assistant("truncated pla", "partial", "reasoning_content", "length"),
+ ]);
+ expect(turns.map((turn) => turn.thinking)).toEqual(["settled plan"]);
+ });
});
describe("retainedReasoning replay messages", () => {
diff --git a/packages/agent-runtime/src/reasoning-replay.ts b/packages/agent-runtime/src/reasoning-replay.ts
index 5efed66ba..cd83a82b5 100644
--- a/packages/agent-runtime/src/reasoning-replay.ts
+++ b/packages/agent-runtime/src/reasoning-replay.ts
@@ -109,15 +109,17 @@ function assistantThinkingText(message: AssistantMessage): {
* `isContextMessage` and compaction-tail `DROPPED_STOP_REASONS` treat error,
* aborted, and deferred assistants as transcript rows, not model context.
* A partial think from one of those turns is not completed reasoning, and it
- * must not take a retained slot away from a finished turn.
+ * must not take a retained slot away from a finished turn. A `length` stop
+ * cuts the response off at the output token limit, so its think is partial
+ * by construction.
*/
-const DROPPED_STOP_REASONS = new Set<string>(["error", "aborted", "deferred"]);
+const DROPPED_STOP_REASONS = new Set<string>(["error", "aborted", "deferred", "length"]);
/**
* Collect the newest assistant turns that still carry thinking, newest-last,
* for storage in checkpoint details. Tool-call blocks are dropped on purpose.
- * Error, aborted, and deferred turns are skipped for the same reason the live
- * context drops them.
+ * Error, aborted, deferred, and length-stopped turns are skipped for the same
+ * reason the live context drops them.
*/
export function harvestRetainedReasoning(
messages: readonly AgentMessage[],