Skip to content

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

feat(agent-runtime): add subagent scratch spillover and resume hints

Totopo27b093419fde8f
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 a2ff87c2c..a1dbf74fb 100644
--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
@@ -4,7 +4,7 @@
- Status: Accepted for implementation (definition roots amended by ADR 0112;
timeout policy amended by ADR 0119; delegation presentation amended by D265;
opt-in parent-tool inherit amended by ADR 0246; resumable delegations amended
- by ADR 0279)
+ by ADR 0279; report spillover amended by RFC #1196)
- Date: 2026-08-06
- Deciders: PI-Desktop core
- Related: D201, ADR 0041 (persistence outbox), ADR 0048 (lazy per-turn tool
@@ -123,6 +123,18 @@ message, bounded to `MAX_SUBAGENT_REPORT_CHARS` (12k), becomes the `Task` tool
result, with `agent`, `status`, `turns`, `toolCalls` and `usage` as structured
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`)
+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.
+Delegates with mutation capability are guided in their prompt to write oversized
+reports (>8,000 characters) directly to a file and return a summary with the file path.
+When a delegate truncates due to model output token limits (`SUBAGENT_OUTPUT_TRUNCATED`),
+the failure result includes character count statistics and a resume hint for ADR 0279
+chains (`Task(resume: "<delegationId>")`).
+
Delegate messages and tool rows are still emitted and persisted — they are what
makes a delegation reviewable — but every row carries `parentToolCallId` and
`agentName`, and the runtime skips those rows when it rebuilds model context.
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 94eacf3de..0d98aa07d 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -931,10 +931,10 @@ keyboard-focus, and reduced-motion checks require project-provided browser
tests or other tooling. Its statuses are `completed`, `failed`,
`aborted`, `timed_out` and the registry-only `stopped`;
the terminal ones surface through `TaskWait`, whose text is
-the report (bounded to `MAX_SUBAGENT_REPORT_CHARS`, 12k) and whose details
+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,
-`error`. The same effective model and thinking fields are included in the
+`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.
`startedAt` and `completedAt` are runtime timestamps in milliseconds and are the source of
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index fa1cc55cd..4e75171a7 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -523,6 +523,9 @@ function delegationSummary(record: DelegationRecord): Record<string, unknown> {
...(record.result?.contextDegraded
? { contextDegraded: record.result.contextDegraded }
: {}),
+ ...(record.result?.scratchReportPath
+ ? { scratchReportPath: record.result.scratchReportPath }
+ : {}),
...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
...(record.modelChangedFrom
? { modelChangedFrom: record.modelChangedFrom }
@@ -4390,6 +4393,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
sessionId: this.sessionId,
turnId: this.turnId,
parentToolCallId: toolCallId,
+ delegationId: record.delegationId,
+ scratchDir: this.scratchDir,
task,
provider,
infiniteProviderRetry: this.infiniteProviderRetry,
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index 63f91dc36..6f3315efd 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -1,4 +1,7 @@
import { describe, expect, it, vi } from "vitest";
+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { Type } from "typebox";
import type { AgentEventEnvelope, SubagentDefinition } from "@pi-desktop/shared";
import type { Message } from "@earendil-works/pi-ai";
@@ -114,6 +117,15 @@ describe("composeSubagentSystemPrompt", () => {
expect(prompt).toContain("You may change files");
expect(prompt).not.toContain("no tools that change files");
+ expect(prompt).toContain("If the final report would exceed ~8,000 characters, write the full report to a file yourself");
+ });
+
+ it("does not instruct read-only delegates to write reports to a file", () => {
+ const prompt = composeSubagentSystemPrompt({
+ definition: definition({ tools: ["Read", "Glob"] }),
+ });
+
+ expect(prompt).not.toContain("write the full report to a file yourself");
});
it("lists resolved inherit tools and treats them as mutating when they write", () => {
@@ -389,11 +401,98 @@ describe("SubagentRun reporting", () => {
expect(result.outputTruncated).toBe(true);
expect(result.report).toContain("The explorer subagent failed");
expect(result.report).toContain(
- "The subagent response exceeded the model's output token limit and was truncated.",
+ "The subagent response exceeded the model's output token limit and was truncated",
);
expect(result.report).toContain("Analysis report cut off mid-sentence...");
});
+ it("includes resume hint and size stats in truncated output when delegationId is provided", async () => {
+ const { run } = createRun({ delegationId: "del-resume-123" });
+ run.handleEvent({
+ type: "message_end",
+ message: assistantMessage({
+ content: [{ type: "text", text: "Partial text here..." }],
+ stopReason: "length",
+ }),
+ });
+ 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.status).toBe("failed");
+ expect(result.error?.code).toBe("SUBAGENT_OUTPUT_TRUNCATED");
+ expect(result.error?.message).toContain('Resume this delegation with Task(resume: "del-resume-123").');
+ expect(result.error?.message).toContain("characters produced before truncation");
+ expect(result.error?.resumeId).toBe("del-resume-123");
+ expect(result.error?.charactersProduced).toBe("Partial text here...".length);
+ });
+
+ it("spills oversized reports to session scratch directory (ADR 0062)", async () => {
+ const tmp = mkdtempSync(join(tmpdir(), "pi-subagent-scratch-"));
+ try {
+ const { run } = createRun({
+ scratchDir: tmp,
+ parentToolCallId: "call-99",
+ });
+ const largeReport = "A".repeat(MAX_SUBAGENT_REPORT_CHARS + 500);
+ run.handleEvent({
+ type: "message_end",
+ message: assistantMessage({
+ content: [{ type: "text", text: largeReport }],
+ 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.status).toBe("completed");
+ expect(result.scratchReportPath).toBeDefined();
+ expect(result.report).toContain("Complete subagent report");
+ expect(result.report).toContain("was saved to:");
+ expect(result.report).toContain(result.scratchReportPath!);
+ expect(existsSync(result.scratchReportPath!)).toBe(true);
+ expect(readFileSync(result.scratchReportPath!, "utf8")).toBe(largeReport);
+ } 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,
+ parentToolCallId: "call-no-scratch",
+ });
+ const largeReport = "A".repeat(MAX_SUBAGENT_REPORT_CHARS + 500);
+ run.handleEvent({
+ type: "message_end",
+ message: assistantMessage({
+ content: [{ type: "text", text: largeReport }],
+ 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.status).toBe("completed");
+ expect(result.scratchReportPath).toBeUndefined();
+ expect(result.report.length).toBeLessThanOrEqual(MAX_SUBAGENT_REPORT_CHARS);
+ expect(result.report).toContain("[subagent report truncated]");
+ });
+
it("clears truncated output state if a subsequent turn finishes cleanly", async () => {
const { run } = createRun();
run.handleEvent({
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 759b3cd86..3a958aee8 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -19,6 +19,8 @@
* already stopped calling tools. Only user Stop or `TaskStop` aborts it.
*/
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
import { randomUUID } from "node:crypto";
import {
Agent,
@@ -112,7 +114,14 @@ export type SubagentRunResult = {
contextDegraded?: boolean;
/** True when the delegate response hit the model's output token limit. */
outputTruncated?: boolean;
- error?: { code: string; message: string };
+ /** File path in session scratch where the unclipped report was preserved (ADR 0062). */
+ scratchReportPath?: string;
+ error?: {
+ code: string;
+ message: string;
+ resumeId?: string;
+ charactersProduced?: number;
+ };
};
export type SubagentToolOutcome = {
@@ -127,6 +136,10 @@ export type SubagentRunOptions = {
turnId?: string;
/** `Task` call that owns this delegate. */
parentToolCallId: string;
+ /** Delegation identifier issued by the runtime for this task run (ADR 0279). */
+ delegationId?: string;
+ /** Session scratch workspace root for persistent spillover artifacts (ADR 0062). */
+ scratchDir?: string;
/** The delegated instruction, written by the parent model. */
task: string;
/** Provider resolved by Electron main (the definition's pin, or the
@@ -189,7 +202,7 @@ export function composeSubagentSystemPrompt(options: {
`You are the \"${definition.name}\" subagent inside PI-Desktop, working on one task delegated by the main agent.`,
`You cannot see the user, ask questions, or delegate further. Finish the task with the tools you have: ${toolList}.`,
subagentCanMutate(definition, resolved)
- ? "You may change files, but only the ones the task is about; leave everything else untouched."
+ ? "You may change files, but only the ones the task is about; leave everything else untouched. If the final report would exceed ~8,000 characters, write the full report to a file yourself and make the final message a compact summary plus the file path."
: "You have no tools that change files or run commands, so never report an edit you could not have made.",
"Your final message is the report the main agent receives when you finish. Make it self-contained: what you did, what you found with exact paths and line numbers, and anything you could not finish.",
"Keep the report tight. Report findings, not narration, and never pad it with a summary of your own process.",
@@ -379,10 +392,17 @@ export class SubagentRun {
});
}
if (this.lastReportTruncated) {
+ const produced = this.lastReportText.length;
+ const stats = ` (${produced} characters produced before truncation)`;
+ const hint = this.opts.delegationId
+ ? ` Resume this delegation with Task(resume: "${this.opts.delegationId}").`
+ : "";
return this.result("failed", this.lastReportText, {
code: "SUBAGENT_OUTPUT_TRUNCATED",
message:
- "The subagent response exceeded the model's output token limit and was truncated.",
+ `The subagent response exceeded the model's output token limit and was truncated${stats}.${hint}`,
+ ...(this.opts.delegationId ? { resumeId: this.opts.delegationId } : {}),
+ charactersProduced: produced,
});
}
return this.result("completed", this.lastReportText);
@@ -621,10 +641,34 @@ export class SubagentRun {
return error;
}
+ private saveScratchReport(text: string): string | undefined {
+ if (!this.opts.scratchDir || text.length <= MAX_SUBAGENT_REPORT_CHARS) {
+ return undefined;
+ }
+ try {
+ const dir = join(
+ this.opts.scratchDir,
+ "delegations",
+ this.opts.parentToolCallId,
+ );
+ mkdirSync(dir, { recursive: true });
+ const target = join(dir, "report.md");
+ writeFileSync(target, text, "utf8");
+ return target;
+ } catch {
+ return undefined;
+ }
+ }
+
private result(
status: SubagentRunStatus,
report: string,
- error?: { code: string; message: string },
+ error?: {
+ code: string;
+ message: string;
+ resumeId?: string;
+ charactersProduced?: number;
+ },
): SubagentRunResult {
const name = this.opts.definition.name;
const body = report.trim();
@@ -642,16 +686,28 @@ export class SubagentRun {
const degradationNote = this.contextDegraded
? "Note: this subagent's context exceeded its model's window and older working history was discarded without a summary, so this report may be incomplete."
: undefined;
+ const preamble = [
+ ...this.modelFailures.map(
+ (failure) =>
+ `Model ${failure.model} failed (${failure.code}): ${failure.message}`,
+ ),
+ ...(degradationNote ? [degradationNote] : []),
+ ];
+ const scratchReportPath = this.saveScratchReport(text);
+ let finalReport: string;
+ if (scratchReportPath) {
+ const notice = `Complete subagent report (${text.length} characters) was saved to: ${scratchReportPath}`;
+ finalReport =
+ preamble.length > 0 ? `${preamble.join("\n\n")}\n\n${notice}` : notice;
+ } else {
+ finalReport = boundedReport([...preamble, text].join("\n\n"));
+ }
return {
agentName: name,
modelId: this.provider.modelId,
thinkingLevel: this.thinkingLevel,
status,
- report: boundedReport([
- ...this.modelFailures.map((failure) => `Model ${failure.model} failed (${failure.code}): ${failure.message}`),
- ...(degradationNote ? [degradationNote] : []),
- text,
- ].join("\n\n")),
+ report: finalReport,
turns: this.turns,
toolCalls: this.toolCalls,
...(this.usage ? { usage: this.usage } : {}),
@@ -659,6 +715,7 @@ export class SubagentRun {
...(this.contextCompactions > 0 ? { contextCompactions: this.contextCompactions } : {}),
...(this.contextDegraded ? { contextDegraded: true } : {}),
...(this.lastReportTruncated ? { outputTruncated: true } : {}),
+ ...(scratchReportPath ? { scratchReportPath } : {}),
...(error ? { error } : {}),
};
}