Skip to content

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

fix(agent-runtime): reject empty delegate compaction summaries

xpeng5278-web907871c4e8be
diff --git a/docs/adr/0299-subagent-context-budget.md b/docs/adr/0299-subagent-context-budget.md
index 821d0423f..800d9616a 100644
--- a/docs/adr/0299-subagent-context-budget.md
+++ b/docs/adr/0299-subagent-context-budget.md
@@ -92,7 +92,11 @@ protection at all.
brief plus the most recent message(s) and discards the rest of its history.
The run continues and records that it was degraded, so the parent's report
and the lifecycle details say the delegate lost history rather than
- presenting a complete answer.
+ presenting a complete answer. An extracted summary that is empty or
+ whitespace-only — including a thinking-only or output-limited reply whose
+ text blocks are absent — is a summarization failure, not a successful
+ empty checkpoint. Accepting it would report compaction success while
+ silently discarding the working context.
5. **A terminal code the parent can act on.** When even the degraded context
does not fit, the run fails with `SUBAGENT_CONTEXT_OVERFLOW`
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 506edb8a8..3e33e59ce 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1138,7 +1138,9 @@ When a summary cannot be generated or installed below the hard limit, the run
degrades: it keeps the original task brief plus the most recent message(s),
discards the rest of its history, continues, and records that it was degraded,
so the report and lifecycle details say the delegate lost history rather than
-presenting a complete answer. When even that does not fit, the run fails with
+presenting a complete answer. Empty or whitespace-only extracted summary text
+(including a thinking-only or output-limited reply with no text blocks) counts
+as "cannot be generated" — it must not install an empty successful checkpoint. When even that does not fit, the run fails with
`SUBAGENT_CONTEXT_OVERFLOW` (not retriable) naming what the parent can change —
narrow the task, delegate to a model with a larger window, read less at once —
instead of forwarding the provider's overflow text.
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 be236cdf2..1f7aa60ea 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -804,7 +804,9 @@ Electron main 里解析一次——凭据与 Pi catalog 快照都在那里——
当摘要无法生成,或压缩后的上下文仍然超出预算时,该次运行降级:只保留原始任务简报
加最近的若干条消息,丢弃其余历史,继续运行,并记录它已被降级,因此报告与生命周期
-details 会说明该委托丢失了历史,而不是把一个不完整的答案当作完整答案呈现。若连这样
+details 会说明该委托丢失了历史,而不是把一个不完整的答案当作完整答案呈现。提取后
+为空或仅空白的摘要文本(包括只有 thinking、没有任何 text 块,或因输出长度截断而
+没有正文的回复)一律视为「无法生成」—— 不得安装一个空的、却被当成成功的检查点。若连这样
也放不下,该次运行以 `SUBAGENT_CONTEXT_OVERFLOW`(不可重试)失败,点名父级可以改变
什么 —— 缩小任务范围、改用窗口更大的模型、一次读取更少内容 —— 而不是把提供商的
溢出文本转发出去。
diff --git a/packages/agent-runtime/src/empty-delegate-summary.test.ts b/packages/agent-runtime/src/empty-delegate-summary.test.ts
new file mode 100644
index 000000000..2c1119720
--- /dev/null
+++ b/packages/agent-runtime/src/empty-delegate-summary.test.ts
@@ -0,0 +1,167 @@
+import { expect, it } from "vitest";
+import type {
+ Api,
+ AssistantMessage,
+ Model,
+ Models,
+} from "@earendil-works/pi-ai";
+import { prepareDelegateTurnContext } from "./subagent-context.js";
+import { buildProviderModel } from "./provider-binding.js";
+
+/**
+ * A thinking-only, output-limited summary reply must not install an empty
+ * compacted checkpoint. textFromContent ignores thinking blocks, so the
+ * extracted summary is ""; accepting it as success would drop recent tool
+ * evidence while reporting kind "compacted".
+ */
+async function reproduce(
+ responseKind: "thinking-only" | "provider-error" | "valid-text",
+) {
+ const model: Model<Api> = {
+ ...buildProviderModel({
+ id: "fixture",
+ name: "Fixture",
+ modelId: "fixture",
+ apiKey: "",
+ authKind: "none",
+ supportsReasoning: true,
+ supportedThinkingLevels: ["off", "low"],
+ baseUrl: "http://127.0.0.1:1/v1",
+ }),
+ contextWindow: 8192,
+ maxTokens: 1024,
+ };
+ const usage = {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ };
+ const assistant = (
+ content: AssistantMessage["content"],
+ ): AssistantMessage => ({
+ role: "assistant",
+ content,
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage,
+ stopReason: "stop",
+ timestamp: 2,
+ });
+ const taskBrief =
+ "Inspect permissions and keep the result of the latest Read.";
+ let summaryRequests = 0;
+ const outcome = await prepareDelegateTurnContext({
+ model,
+ taskBrief,
+ retentionMode: "active_turn",
+ signal: new AbortController().signal,
+ messages: [
+ { role: "user", content: taskBrief, timestamp: 1 },
+ {
+ ...assistant([
+ {
+ type: "toolCall",
+ id: "old-read",
+ name: "Read",
+ arguments: { path: "old-file.ts" },
+ },
+ ]),
+ stopReason: "toolUse",
+ },
+ {
+ role: "toolResult",
+ toolCallId: "old-read",
+ toolName: "Read",
+ isError: false,
+ content: [{ type: "text", text: "old history ".repeat(1500) }],
+ timestamp: 2,
+ },
+ {
+ ...assistant([
+ {
+ type: "toolCall",
+ id: "read-1",
+ name: "Read",
+ arguments: { path: "permissions.ts" },
+ },
+ ]),
+ stopReason: "toolUse",
+ },
+ {
+ role: "toolResult",
+ toolCallId: "read-1",
+ toolName: "Read",
+ isError: false,
+ content: [
+ {
+ type: "text",
+ text: "RECENT_FINDING: permission check is missing.",
+ },
+ ],
+ timestamp: 3,
+ },
+ ],
+ // Mock only the external summary completion. No network or paid API is used.
+ summaryModels: () =>
+ ({
+ completeSimple: async () => {
+ summaryRequests++;
+ if (responseKind === "provider-error") {
+ return {
+ ...assistant([]),
+ stopReason: "error",
+ errorMessage: "401 invalid API key",
+ };
+ }
+ if (responseKind === "valid-text") {
+ return assistant([
+ {
+ type: "text",
+ text: "The permission check is missing; inspect permissions.ts next.",
+ },
+ ]);
+ }
+ return {
+ ...assistant([
+ { type: "thinking", thinking: "I need to summarize this." },
+ ]),
+ stopReason: "length",
+ };
+ },
+ }) as unknown as Models,
+ });
+ expect(summaryRequests).toBeGreaterThan(0);
+ return outcome;
+}
+
+it("does not replace real delegate history with an empty successful checkpoint", async () => {
+ const outcome = await reproduce("thinking-only");
+ // A thinking-only completion has no summary text; it must enter the existing
+ // failed-summary degradation path, which preserves the brief and recent evidence.
+ expect(outcome.kind).toBe("degraded");
+ if (outcome.kind === "degraded") {
+ expect(JSON.stringify(outcome.messages)).toContain("RECENT_FINDING");
+ }
+});
+
+it("control: a reported provider error preserves recent evidence through degradation", async () => {
+ const outcome = await reproduce("provider-error");
+ expect(outcome.kind).toBe("degraded");
+ if (outcome.kind === "degraded") {
+ expect(JSON.stringify(outcome.messages)).toContain("RECENT_FINDING");
+ }
+});
+
+it("control: a real text summary produces a compacted context", async () => {
+ const outcome = await reproduce("valid-text");
+ expect(outcome.kind).toBe("compacted");
+ if (outcome.kind === "compacted") {
+ expect(JSON.stringify(outcome.messages)).toContain(
+ "permission check is missing",
+ );
+ }
+});
diff --git a/packages/agent-runtime/src/pi-runtime-compaction-summary.ts b/packages/agent-runtime/src/pi-runtime-compaction-summary.ts
index 8d11f0e94..3b0ce291a 100644
--- a/packages/agent-runtime/src/pi-runtime-compaction-summary.ts
+++ b/packages/agent-runtime/src/pi-runtime-compaction-summary.ts
@@ -207,7 +207,24 @@ async function requestSummary(
),
};
}
- return { ok: true, value: { text: textFromContent(response.content), usage: response.usage } };
+ // Thinking-only / output-limited replies extract to "" via textFromContent
+ // (thinking blocks are excluded). An empty checkpoint would look like a
+ // successful compaction while silently discarding working context.
+ const text = textFromContent(response.content);
+ if (!text.trim()) {
+ const limited =
+ response.stopReason === "length"
+ ? " (output limited before any summary text)"
+ : "";
+ return {
+ ok: false,
+ error: new CompactionError(
+ "summarization_failed",
+ `${errorLabel} failed: empty summary text${limited}`,
+ ),
+ };
+ }
+ return { ok: true, value: { text, usage: response.usage } };
}
export async function generateSummaryWithUsage(