Skip to content

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

fix(agent-runtime): bound thinking text in a retained compaction tail

xpeng5278-web969c3c04b97e
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 76cabcdba..d30c8fab4 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -553,7 +553,11 @@ and every record written before the marker existed — is normalized to its late
user message only, so a restart cannot restore a sequence of
executable-looking old requests. Dropping an assistant message also drops its
tool calls, and the fallback drops the results of calls it did not keep, so no
-orphaned tool call or unmatched result can reach the provider. The retained tail
+orphaned tool call or unmatched result can reach the provider. Assistant
+thinking shares the same character budget as text. Answer text is reserved
+first; a thinking block that has to be shortened drops its provider signature,
+so the replay is not a mutated signed trace. A block that still fits keeps its
+signature, and redacted thinking is left unchanged. The retained tail
is re-estimated with the summary before persistence and before continuation, so
an oversized request still cannot pass the guard. A fallback also records
`details.failureReason` — `no_new_history`, `summary_budget`,
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 e34ce2ab7..e010adcdb 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -386,7 +386,9 @@ pi 0.84.4+ 只在循环将要在同一次运行中开启另一个助手回合时
以及标记出现之前写入的记录——仍会归一化为只保留最新的用户消息,因此重启无法
恢复一串看起来可执行的旧请求。放弃助理消息也会丢弃其工具调用,回退还会丢弃
它没有保留的调用所对应的结果,因此没有孤立的工具调用或不匹配的结果可以到达
-提供商。保留的尾部用持久化之前的摘要重新估计,并且在继续之前再次估计,
+提供商。助手思考与正文共用同一字符预算。正文先保留;必须缩短的思考块会丢掉
+提供商签名,以免回放一段被改过的已签名推理。仍然放得下的块保留签名,脱敏思考
+块保持不变。保留的尾部用持久化之前的摘要重新估计,并且在继续之前再次估计,
所以超大的请求仍然无法通过警卫。回退还会记录 `details.failureReason`——
`no_new_history`、`summary_budget`、`summary_provider` 或 `checkpoint_oversized`——
一个封闭词表,而不是可能带有端点细节的提供商错误文本。
diff --git a/packages/agent-runtime/src/agent-messages.ts b/packages/agent-runtime/src/agent-messages.ts
index 5e3bcff78..5e4594dfd 100644
--- a/packages/agent-runtime/src/agent-messages.ts
+++ b/packages/agent-runtime/src/agent-messages.ts
@@ -182,10 +182,28 @@ export function truncateTextWithMarker(
}`;
}
+/**
+ * Which string a block contributes to the truncation budget.
+ *
+ * Readable assistant thinking lives in `thinking`, not `text`, and pi counts
+ * it toward the context estimate. Redacted thinking is an opaque signature
+ * replay and is not rewritten. A thinking block that only carries `text`
+ * (some OpenAI-compatible adapters) still uses that field.
+ */
+function truncationField(block: Record<string, unknown>): "text" | "thinking" | undefined {
+ if (block.type === "thinking" && block.redacted === true) return undefined;
+ if (block.type === "thinking" && typeof block.thinking === "string") return "thinking";
+ if (typeof block.text === "string") return "text";
+ return undefined;
+}
+
/**
* Bound every text block of one message so the message's total text is at most
- * `maxChars`. Blocks without text (tool calls, images) are kept, so a truncated
- * message is still a provider-valid message with its tool calls intact.
+ * `maxChars`. Answer text is reserved first; assistant thinking is then cut to
+ * whatever remains, and a shortened thinking block drops its provider signature
+ * so the replay is not a mutated signed trace. Blocks without text (tool calls,
+ * images, redacted thinking) are kept, so a truncated message is still a
+ * provider-valid message with its tool calls intact.
*/
export function truncateMessageText(
message: AgentMessage,
@@ -198,18 +216,39 @@ export function truncateMessageText(
return text === content ? message : ({ ...message, content: text } as AgentMessage);
}
if (!Array.isArray(content)) return message;
- let remaining = maxChars;
+ const fields = content.map((block) =>
+ isRecord(block) ? truncationField(block) : undefined,
+ );
+ // Reserve answer text first so a long thinking trace cannot evict it.
+ let textBudget = maxChars;
+ const textAllowance: number[] = [];
+ content.forEach((block, index) => {
+ if (fields[index] !== "text" || !isRecord(block)) return;
+ const value = block.text as string;
+ const allowance = Math.min(value.length, Math.max(0, textBudget));
+ textAllowance[index] = allowance;
+ textBudget -= allowance;
+ });
+ let thinkingBudget = Math.max(0, textBudget);
let changed = false;
- const blocks = content.map((block) => {
- if (!isRecord(block) || typeof block.text !== "string") return block;
- if (block.text.length <= remaining) {
- remaining -= block.text.length;
+ const blocks = content.map((block, index) => {
+ const field = fields[index];
+ if (!field || !isRecord(block)) return block;
+ const value = block[field];
+ if (typeof value !== "string") return block;
+ const allowance = field === "text" ? (textAllowance[index] ?? 0) : thinkingBudget;
+ if (value.length <= allowance) {
+ if (field === "thinking") thinkingBudget -= value.length;
return block;
}
changed = true;
- const text = truncateTextWithMarker(block.text, Math.max(1, remaining), marker);
- remaining = 0;
- return { ...block, text };
+ const nextValue = truncateTextWithMarker(value, Math.max(1, allowance), marker);
+ if (field === "thinking") thinkingBudget = 0;
+ if (field === "text") return { ...block, text: nextValue };
+ const next: Record<string, unknown> = { ...block, thinking: nextValue };
+ delete next.thinkingSignature;
+ delete next.redacted;
+ return next;
});
return changed ? ({ ...message, content: blocks } as AgentMessage) : message;
}
diff --git a/packages/agent-runtime/src/compaction-tail.test.ts b/packages/agent-runtime/src/compaction-tail.test.ts
index 0767395bb..208ab1d6b 100644
--- a/packages/agent-runtime/src/compaction-tail.test.ts
+++ b/packages/agent-runtime/src/compaction-tail.test.ts
@@ -174,6 +174,55 @@ describe("selectRecentTail", () => {
]);
});
+ it("bounds assistant thinking so a retained tail can fit the budget", () => {
+ const thinking = "t".repeat(20_000);
+ const message = {
+ role: "assistant",
+ content: [
+ { type: "thinking", thinking, thinkingSignature: "sig-original" },
+ { type: "text", text: "ship the fix" },
+ ],
+ api: "anthropic-messages",
+ provider: "anthropic",
+ model: "claude-opus-4-5",
+ usage,
+ stopReason: "stop",
+ timestamp: 2,
+ } as AgentMessage;
+
+ const tail = selectRecentTail([message], 80);
+
+ expect(tail).toHaveLength(1);
+ const content = (tail[0] as { content: Array<Record<string, unknown>> }).content;
+ const thinkingBlock = content.find((block) => block.type === "thinking");
+ const textBlock = content.find((block) => block.type === "text");
+ expect(thinkingBlock?.thinking).toEqual(
+ expect.stringContaining(CHECKPOINT_TRUNCATION_MARKER.trim()),
+ );
+ expect((thinkingBlock?.thinking as string).length).toBeLessThan(thinking.length);
+ expect(thinkingBlock).not.toHaveProperty("thinkingSignature");
+ expect(textBlock).toMatchObject({ type: "text", text: "ship the fix" });
+ expect(estimateTokens(tail[0]!)).toBeLessThanOrEqual(80);
+ });
+
+ it("keeps a signed thinking block that already fits the tail", () => {
+ const message = {
+ role: "assistant",
+ content: [
+ { type: "thinking", thinking: "short plan", thinkingSignature: "sig-kept" },
+ { type: "text", text: "done" },
+ ],
+ api: "anthropic-messages",
+ provider: "anthropic",
+ model: "claude-opus-4-5",
+ usage,
+ stopReason: "stop",
+ timestamp: 2,
+ } as AgentMessage;
+
+ expect(selectRecentTail([message], 10_000)[0]).toBe(message);
+ });
+
it("returns an empty tail when only tool results remain", () => {
// Neither a bare result nor a bare tool call is a message a provider
// accepts, so there is nothing this path can keep.