Skip to content

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

fix(agent-runtime): contain subagent scratch spillover

vastsa766756983f2f
diff --git a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
index a1dbf74fb..32b8b9de0 100644
--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
@@ -125,7 +125,9 @@ details.
When a delegate's completed report exceeds `MAX_SUBAGENT_REPORT_CHARS`, the
runtime preserves the full, unclipped report in the session scratch directory
-(`<data_dir>/scratch/<sessionId>/delegations/<parentToolCallId>/report.md`)
+(`<data_dir>/scratch/<sessionId>/delegations/<parentToolCallId>/report.md`; an
+opaque ID containing path separators is encoded before it is used as a path
+component)
and returns a compact pointer notice (`Complete subagent report (N characters) was saved to: <path>`)
alongside `scratchReportPath` in the structured result. If scratch persistence fails,
it degrades gracefully to bounded head/tail clipping with a truncation marker.
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 0d98aa07d..59664469e 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -933,7 +933,8 @@ tests or other tooling. Its statuses are `completed`, `failed`,
the terminal ones surface through `TaskWait`, whose text is
the report (bounded to `MAX_SUBAGENT_REPORT_CHARS`, 12k; when exceeded, persisted to session scratch with a pointer notice per ADR 0062) and whose details
carry `delegationId`, `agent`, `modelId`, `thinkingLevel`, `status`, `startedAt`,
-`completedAt` when settled, `turns`, `toolCalls` and, on failure or timeout,
+`completedAt` when settled, `turns`, `toolCalls`, and `scratchReportPath` when
+the full report was spilled to scratch; on failure or timeout they carry
`error` (including resume ID hints on `SUBAGENT_OUTPUT_TRUNCATED`). The same effective model and thinking fields are included in the
immediate `Task` result and in lifecycle snapshots so live and restored
delegation views do not re-derive them from definitions or parent settings.
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 356c71850..8cb6d815f 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -7262,6 +7262,7 @@ describe("DesktopAgentRuntime subagents", () => {
report: "The explorer subagent failed after 1 turn(s): no route.",
turns: 1,
toolCalls: 0,
+ scratchReportPath: "/tmp/session-scratch/delegations/task-1/report.md",
error: { code: "NETWORK_ERROR", message: "no route" },
};
const task = taskTool(runtime);
@@ -7299,6 +7300,7 @@ describe("DesktopAgentRuntime subagents", () => {
status: "failed",
startedAt: expect.any(Number),
completedAt: expect.any(Number),
+ scratchReportPath: "/tmp/session-scratch/delegations/task-1/report.md",
},
],
});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 4e75171a7..27bc3a9e2 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -4989,6 +4989,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
startedAt: record.startedAt,
...(record.completedAt ? { completedAt: record.completedAt } : {}),
...(record.result?.error ? { error: record.result.error } : {}),
+ ...(record.result?.scratchReportPath
+ ? { scratchReportPath: record.result.scratchReportPath }
+ : {}),
report:
record.status === "running"
? formatDelegationHeartbeat(record)
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index 6f3315efd..16f9ef9a0 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -466,6 +466,37 @@ describe("SubagentRun reporting", () => {
}
});
+ it("keeps an opaque tool-call id inside the scratch directory", async () => {
+ const tmp = mkdtempSync(join(tmpdir(), "pi-subagent-scratch-"));
+ try {
+ const { run } = createRun({
+ scratchDir: tmp,
+ parentToolCallId: "../../outside",
+ });
+ run.handleEvent({
+ type: "message_end",
+ message: assistantMessage({
+ content: [{ type: "text", text: "A".repeat(MAX_SUBAGENT_REPORT_CHARS + 1) }],
+ stopReason: "stop",
+ }),
+ });
+ run.agent = {
+ prompt: vi.fn().mockResolvedValue(undefined),
+ waitForIdle: vi.fn().mockResolvedValue(undefined),
+ abort: vi.fn(),
+ };
+
+ const result = await (run as unknown as SubagentRun).run();
+
+ expect(result.scratchReportPath?.startsWith(join(tmp, "delegations"))).toBe(true);
+ expect(readFileSync(result.scratchReportPath!, "utf8")).toHaveLength(
+ MAX_SUBAGENT_REPORT_CHARS + 1,
+ );
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ });
+
it("falls back to bounded clipping when scratch write is unavailable or fails", async () => {
const { run } = createRun({
scratchDir: undefined,
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 3a958aee8..8ec003b79 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -223,6 +223,14 @@ function boundedReport(value: string): string {
return `${text.slice(0, head)}${marker}${text.slice(-tail)}`;
}
+/** Keep opaque provider/tool-call ids inside the session scratch directory. */
+function scratchPathSegment(value: string): string {
+ if (/^[A-Za-z0-9._-]+$/.test(value) && value !== "." && value !== "..") {
+ return value;
+ }
+ return `id-${encodeURIComponent(value)}`;
+}
+
export { addUsage };
/** One delegate execution. A resumed run is still a new instance; it is
@@ -649,7 +657,7 @@ export class SubagentRun {
const dir = join(
this.opts.scratchDir,
"delegations",
- this.opts.parentToolCallId,
+ scratchPathSegment(this.opts.parentToolCallId),
);
mkdirSync(dir, { recursive: true });
const target = join(dir, "report.md");