Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): bound retained CJK text to the token budget
xpeng5278-webf9ff833c252f
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 70155677e..192a070c9 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -645,7 +645,10 @@ rejects. None of these values are configurable.number, corrected against observed request usage. The runtime estimator anchorson the last assistant usage and delegates provider-message estimation topi-ai, whose 1.1.0 text estimate is 3.5 characters per token; text truncation-converts token budgets with the same ratio. Desktop-only rows keep the existing+starts from that ratio, then shrinks the cut until the output-cap estimate+(chars/4 plus the CJK correction) fits the same token budget. Retained tails,+checkpoint user messages, and a delegate's retained task brief share that+bound. Desktop-only rows keep the existingcharacter heuristic. With no usageanchor, the budget also computes the output-cap estimatorover non-system conversation messages plus the current system prompt and activediff --git a/packages/agent-runtime/src/compaction-tail.test.ts b/packages/agent-runtime/src/compaction-tail.test.tsindex 208ab1d6b..0805d51eb 100644--- a/packages/agent-runtime/src/compaction-tail.test.ts+++ b/packages/agent-runtime/src/compaction-tail.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vitest";import type { AgentMessage } from "@earendil-works/pi-agent-core";-import { estimateTokens } from "./pi-runtime-estimates.js";+import { estimateOutputCapInputTokens } from "./output-cap.js";+import {+ ESTIMATED_TEXT_CHARS_PER_TOKEN,+ estimateTokens,+} from "./pi-runtime-estimates.js";import {CHECKPOINT_TRUNCATION_MARKER,COMPACTION_RETAINED_TAIL_SHAPE,@@ -98,6 +102,18 @@ describe("selectRecentTail", () => {]);});+ it("truncates CJK text the chars-per-token estimate would have kept whole", () => {+ // 600 Han characters are ~172 tokens at 3.5 chars/token, under a 200+ // budget, but ~600 under the output-cap estimate. The tail must still cut.+ const budget = 200;+ const tail = selectRecentTail([user("中".repeat(600))], budget);++ expect(tail).toHaveLength(1);+ const text = (tail[0] as { content: Array<{ text: string }> }).content[0]!.text;+ expect(text).toContain(CHECKPOINT_TRUNCATION_MARKER.trim());+ expect(outputCapTokens(text)).toBeLessThanOrEqual(budget);+ });+it("keeps the newest message even when it alone exceeds the budget", () => {const messages = [user(body(400), 1),@@ -232,6 +248,12 @@ describe("selectRecentTail", () => {});});+function outputCapTokens(text: string): number {+ return estimateOutputCapInputTokens({+ messages: [{ role: "user", content: text }],+ });+}+describe("truncateMessageToTail", () => {it("bounds every text block and keeps the tool call identity", () => {const message = toolCallAssistant("call-1", body(4_000));@@ -244,6 +266,39 @@ describe("truncateMessageToTail", () => {expect(truncated.content[0]!.text!.length).toBeLessThan(4_000);expect(truncated.content[1]).toMatchObject({ type: "toolCall", id: "call-1" });});++ it("keeps an ASCII tail at the character ceiling", () => {+ const budget = 200;+ const truncated = truncateMessageToTail(user("a".repeat(1_600)), budget) as {+ content: Array<{ text: string }>;+ };+ const text = truncated.content[0]!.text;++ // The historical ceiling is budget * 3.5 characters. ASCII already+ // estimates under that, so the CJK shrink must not pull it down toward+ // `budget` characters.+ const ceiling = Math.max(+ 64,+ Math.floor(budget * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ );+ expect(text.length).toBe(ceiling);+ expect(outputCapTokens(text)).toBeLessThanOrEqual(budget);+ });++ it("shrinks a long CJK tail until the output-cap estimate fits", () => {+ const budget = 200;+ const truncated = truncateMessageToTail(user("中".repeat(1_600)), budget) as {+ content: Array<{ text: string }>;+ };+ const text = truncated.content[0]!.text;++ expect(text).toContain("中");+ expect(text).toContain(CHECKPOINT_TRUNCATION_MARKER.trim());+ expect(outputCapTokens(text)).toBeLessThanOrEqual(budget);+ expect(text.length).toBeLessThan(+ Math.floor(budget * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ );+ });});describe("stripDanglingToolCalls", () => {diff --git a/packages/agent-runtime/src/compaction-tail.ts b/packages/agent-runtime/src/compaction-tail.tsindex 57f4504f3..9f3eefaff 100644--- a/packages/agent-runtime/src/compaction-tail.ts+++ b/packages/agent-runtime/src/compaction-tail.ts@@ -29,6 +29,10 @@ import {estimateTokens,} from "./pi-runtime-estimates.js";import { isRecord, truncateMessageText } from "./agent-messages.js";+import {+ charBudgetWithinOutputCap,+ estimateOutputCapInputTokens,+} from "./output-cap.js";/*** `details` marker for a tail holding the real recent window rather than the@@ -51,26 +55,60 @@ const RETAINED_TAIL_ROLES = new Set(["user", "assistant", "toolResult"]);const DROPPED_STOP_REASONS = new Set(["error", "aborted", "deferred"]);function messageTokens(message: AgentMessage): number {- return Math.max(1, Math.ceil(estimateTokens(message)));+ const estimated = Math.max(1, Math.ceil(estimateTokens(message)));+ // chars/3.5 under-counts Han, kana, and Hangul. The next request is gated+ // on the output-cap estimate, so a CJK message that looks cheap here is+ // still truncated.+ const capped = estimateOutputCapInputTokens({+ messages: [{+ role: message.role,+ content: (message as { content?: unknown }).content,+ }],+ });+ return Math.max(estimated, capped);+}++/**+ * Text {@link truncateMessageText} can actually shorten. Redacted thinking is+ * an opaque signature and is left unchanged, so it must not pull the budget.+ */+function plainRetainedText(message: AgentMessage): string {+ const content = (message as { content?: unknown }).content;+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ let text = "";+ for (const block of content) {+ if (!isRecord(block)) continue;+ if (block.type === "thinking" && block.redacted === true) continue;+ if (block.type === "thinking" && typeof block.thinking === "string") {+ text += block.thinking;+ continue;+ }+ if (typeof block.text === "string") text += block.text;+ }+ return text;}/*** Bound one message to a token budget by truncating its text blocks. Tool calls* and tool results keep their identity, so a truncated message is still a- * provider-valid message.+ * provider-valid message. The character ceiling stays the ASCII chars/3.5 cap;+ * CJK text is then shrunk to the output-cap estimate.*/export function truncateMessageToTail(message: AgentMessage,maxTokens: number,): AgentMessage {- return truncateMessageText(- message,- Math.max(- 64,- Math.floor(Math.max(1, maxTokens) * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ const ceiling = Math.max(+ 64,+ Math.floor(Math.max(1, maxTokens) * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ );+ const maxChars = charBudgetWithinOutputCap(maxTokens, ceiling, (chars) =>+ plainRetainedText(+ truncateMessageText(message, chars, CHECKPOINT_TRUNCATION_MARKER),),- CHECKPOINT_TRUNCATION_MARKER,);+ return truncateMessageText(message, maxChars, CHECKPOINT_TRUNCATION_MARKER);}/** Content blocks of a message, whatever shape its role uses. */diff --git a/packages/agent-runtime/src/output-cap.test.ts b/packages/agent-runtime/src/output-cap.test.tsindex c39495be7..a4a3770dc 100644--- a/packages/agent-runtime/src/output-cap.test.ts+++ b/packages/agent-runtime/src/output-cap.test.ts@@ -1,9 +1,12 @@import { describe, expect, it } from "vitest";import { getCurrentSystemPrompt, normalizeContext, type Message } from "@earendil-works/pi-ai";+import { CHECKPOINT_TRUNCATION_MARKER } from "./compaction-tail.js";+import { ESTIMATED_TEXT_CHARS_PER_TOKEN } from "./pi-runtime-estimates.js";import {clampOutputToContext,estimateOutputCapInputTokens,requestTranscript,+ truncateTextWithinOutputCap,type OutputCapContext,} from "./output-cap.js";@@ -587,3 +590,47 @@ it("counts instruction sections and tool declarations in transcript-only requestexpect(estimateOutputCapInputTokens(state)).toBeGreaterThan(estimateOutputCapInputTokens(base));expect(estimateOutputCapInputTokens(state)).toBeGreaterThan(4);});++describe("truncateTextWithinOutputCap", () => {+ const budget = 200;+ const ceiling = Math.floor(budget * ESTIMATED_TEXT_CHARS_PER_TOKEN);++ it("leaves ASCII at the character ceiling", () => {+ const text = truncateTextWithinOutputCap(+ "a".repeat(1_600),+ budget,+ CHECKPOINT_TRUNCATION_MARKER,+ ceiling,+ );+ expect(text.length).toBe(ceiling);+ expect(estimateOutputCapInputTokens({+ messages: [{ role: "user", content: text }],+ })).toBeLessThanOrEqual(budget);+ });++ it("shrinks CJK that is longer than the ceiling", () => {+ const text = truncateTextWithinOutputCap(+ "中".repeat(1_600),+ budget,+ CHECKPOINT_TRUNCATION_MARKER,+ ceiling,+ );+ expect(text).toContain(CHECKPOINT_TRUNCATION_MARKER.trim());+ expect(estimateOutputCapInputTokens({+ messages: [{ role: "user", content: text }],+ })).toBeLessThanOrEqual(budget);+ });++ it("shrinks CJK that fits the character ceiling but not the token budget", () => {+ const text = truncateTextWithinOutputCap(+ "中".repeat(600),+ budget,+ CHECKPOINT_TRUNCATION_MARKER,+ ceiling,+ );+ expect(text.length).toBeLessThan(600);+ expect(estimateOutputCapInputTokens({+ messages: [{ role: "user", content: text }],+ })).toBeLessThanOrEqual(budget);+ });+});diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.tsindex 991a627bb..0e7cf3670 100644--- a/packages/agent-runtime/src/output-cap.ts+++ b/packages/agent-runtime/src/output-cap.ts@@ -37,6 +37,7 @@ import {hostedSearchReplayProjection,type HostedSearchReplayOptions,} from "@earendil-works/pi-ai/utils/hosted-search";+import { truncateTextWithMarker } from "./agent-messages.js";/** Structural view of the request context; assignable from pi-ai's `Context`. */export type OutputCapContext = {@@ -281,6 +282,70 @@ export function estimateOutputCapInputTokens(return baseline + Math.ceil(cjkChars * 0.75);}+/**+ * Largest character budget in `1..charCeiling` for which `textAt` stays within+ * `tokenBudget` under {@link estimateOutputCapInputTokens}.+ *+ * `charCeiling` is the historical ASCII cap (token budget times the 3.5+ * chars-per-token ratio). Latin text already estimates under that cap, so it+ * is returned unchanged. CJK text estimates near one token per character, and+ * the cap is walked down until the same estimator that gates the output+ * ceiling fits. A budget too small to hold the truncation marker may still+ * exceed it by that marker alone.+ */+export function charBudgetWithinOutputCap(+ tokenBudget: number,+ charCeiling: number,+ textAt: (maxChars: number) => string,+): number {+ const budget = Math.max(+ 1,+ Math.floor(Number.isFinite(tokenBudget) ? tokenBudget : 1),+ );+ const ceiling = Math.max(+ 1,+ Math.floor(Number.isFinite(charCeiling) ? charCeiling : 1),+ );+ const tokensAt = (maxChars: number) =>+ estimateOutputCapInputTokens({+ messages: [{ role: "user", content: textAt(maxChars) }],+ });+ if (tokensAt(ceiling) <= budget) return ceiling;++ let low = 1;+ let high = ceiling - 1;+ let best = 1;+ while (low <= high) {+ const mid = Math.floor((low + high) / 2);+ if (tokensAt(mid) <= budget) {+ best = mid;+ low = mid + 1;+ } else {+ high = mid - 1;+ }+ }+ return best;+}++/**+ * Cut `text` with `marker` so {@link estimateOutputCapInputTokens} fits+ * `tokenBudget`. See {@link charBudgetWithinOutputCap} for why ASCII keeps+ * the character ceiling.+ */+export function truncateTextWithinOutputCap(+ text: string,+ tokenBudget: number,+ marker: string,+ charCeiling: number,+): string {+ const maxChars = charBudgetWithinOutputCap(+ tokenBudget,+ charCeiling,+ (chars) => truncateTextWithMarker(text, chars, marker),+ );+ return truncateTextWithMarker(text, maxChars, marker);+}+/*** The transcript the adapter puts on the wire. Unless the model declares* mid-conversation system support, every adapter folds the later systemdiff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex de67f3f21..4f1412f26 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -8583,6 +8583,47 @@ describe("DesktopAgentRuntime per-turn context protection", () => {).toBeLessThanOrEqual(20_000);expect(retained[0].content.slice(0, 7)).toBe("newest:");expect(retained[0].content).toContain("[checkpoint truncated:");+ // ASCII stays at the 3.5 chars/token ceiling (~70k), not one char per token.+ expect(retained[0].content.length).toBeGreaterThan(20_000 * 3);+ await runtime.dispose();+ });++ it("truncates a CJK user message the character estimate would have kept whole", async () => {+ const runtime = createRuntime();+ // 50k Han characters are ~14k tokens at 3.5 chars/token, under the 20k+ // retention cap, but ~50k under the output-cap estimate. Keeping the+ // message whole overflows the next request.+ const asks = ["oldest", "newest"].map((label, index) => ({+ type: "message",+ id: `ask-${index}`,+ parentId: index === 0 ? null : `ask-${index - 1}`,+ timestamp: `2026-07-30T00:00:0${index}Z`,+ message: {+ role: "user",+ content: `${label}:${"中".repeat(index === 1 ? 50_000 : 100)}`,+ timestamp: index + 1,+ },+ }));+ (runtime as any).fullEntries = asks;++ const entries = (runtime as any).entriesWithCompaction();+ const budget = (runtime as any).contextBudget(+ entries.map((entry: any) => entry.message),+ );+ const preparation = (runtime as any).prepareCompactionInput(+ entries,+ budget,+ 20_000,+ "active_turn",+ );+ const retained = preparation.value.retainedTail;++ expect(retained).toHaveLength(1);+ expect(retained[0].content.slice(0, 7)).toBe("newest:");+ expect(retained[0].content).toContain("[checkpoint truncated:");+ expect(estimateOutputCapInputTokens({+ messages: [{ role: "user", content: retained[0].content }],+ })).toBeLessThanOrEqual(20_000);await runtime.dispose();});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex b9bc9565f..a5706ad19 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -234,6 +234,7 @@ import {effectiveModelContextWindow,estimateOutputCapInputTokens,requestTranscript,+ truncateTextWithinOutputCap,} from "./output-cap.js";import {composeSubagentSystemPrompt,@@ -1584,11 +1585,6 @@ function appendToolProgress(current: string, chunk: string): string {return `${head}${TOOL_PROGRESS_TRUNCATION_MARKER}${tail}`;}-/** Bound a checkpoint message's text, naming the cut the way pi's tail does. */-function truncateTextForCheckpoint(text: string, maxChars: number): string {- return truncateTextWithMarker(text, maxChars, CHECKPOINT_TRUNCATION_MARKER);-}-/*** Flatten a user message to plain text so it can be truncated at a token* budget. Images and other non-text blocks are named rather than kept: a@@ -1609,11 +1605,20 @@ function truncateUserMessageForCheckpoint(message: UserMessage,tokenBudget: number,): UserMessage {+ const text = userMessageTextForCheckpoint(message);+ // Same ASCII ceiling as before (budget * 3.5). CJK is then shrunk to the+ // output-cap estimate, which charges about one token per character.+ const ceiling = Math.max(+ 1,+ Math.floor(tokenBudget * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ );return {...message,- content: truncateTextForCheckpoint(- userMessageTextForCheckpoint(message),- Math.max(1, Math.floor(tokenBudget * ESTIMATED_TEXT_CHARS_PER_TOKEN)),+ content: truncateTextWithinOutputCap(+ text,+ tokenBudget,+ CHECKPOINT_TRUNCATION_MARKER,+ ceiling,),};}@@ -1632,7 +1637,15 @@ function selectRetainedUserMessages(let remaining = Math.max(0, maxTokens);for (let index = candidates.length - 1; index >= 0 && remaining > 0; index -= 1) {const message = candidates[index];- const tokens = estimateTokens(message);+ // pi-ai's chars/3.5 estimate under-counts Han, kana, and Hangul, so a long+ // CJK message looks like it fits and is kept whole. The output-cap+ // estimate is the one the next request is gated on.+ const tokens = Math.max(+ estimateTokens(message),+ estimateOutputCapInputTokens({+ messages: [{ role: "user", content: message.content }],+ }),+ );if (tokens <= remaining) {selected.push(message);remaining -= tokens;diff --git a/packages/agent-runtime/src/subagent-context.test.ts b/packages/agent-runtime/src/subagent-context.test.tsindex 3ffebbd76..9d7e4f7c6 100644--- a/packages/agent-runtime/src/subagent-context.test.ts+++ b/packages/agent-runtime/src/subagent-context.test.ts@@ -17,7 +17,14 @@ import {buildProviderModel,type RuntimeProviderConfig,} from "./provider-binding.js";-import { automaticCompactionThresholdFor, contextBudgetFor } from "./context-budget.js";+import {+ automaticCompactionThresholdFor,+ contextBudgetFor,+ contextBudgetLimitsFor,+ retainedUserMessageBudget,+} from "./context-budget.js";+import { estimateOutputCapInputTokens } from "./output-cap.js";+import { ESTIMATED_TEXT_CHARS_PER_TOKEN } from "./pi-runtime-estimates.js";import {degradedDelegateMessages,delegateRetentionMode,@@ -45,6 +52,18 @@ function smallModel(): Model<Api> {};}+/**+ * Window whose retention cap is half the hard budget (8 000) while the summary+ * prompt can still carry a brief larger than that cap times 3.5 characters.+ */+function retentionModel(): Model<Api> {+ return {+ ...buildProviderModel(provider),+ contextWindow: 32_000,+ maxTokens: 4_096,+ };+}+const ZERO_USAGE: Usage = {input: 0,output: 0,@@ -355,6 +374,65 @@ describe("prepareDelegateTurnContext", () => {expect(fit.tokens).toBeLessThan(fit.hardLimit);});+ it("truncates a long CJK brief to the output-cap retention budget", async () => {+ const brief = "中".repeat(32_000);+ const model = retentionModel();+ const { factory } = summaryModels(() => summarySuccess("SUMMARY TEXT"));+ const outcome = await prepareDelegateTurnContext({+ messages: [+ userMessage(brief),+ assistantToolCall("call-1"),+ toolResult("a".repeat(3_000), "call-1"),+ ],+ model,+ taskBrief: brief,+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ if (outcome.kind !== "compacted") return;+ const retained = outcome.messages.at(-1) as { role?: string; content?: unknown };+ expect(retained.role).toBe("user");+ expect(typeof retained.content).toBe("string");+ const text = retained.content as string;+ const budget = retainedUserMessageBudget(contextBudgetLimitsFor(model));+ expect(text).toContain("中");+ expect(text).toContain("delegate context truncated");+ expect(estimateOutputCapInputTokens({+ messages: [{ role: "user", content: text }],+ })).toBeLessThanOrEqual(budget);+ expect(text.length).toBeLessThan(+ Math.floor(budget * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ );+ });++ it("keeps an ASCII brief at the character ceiling when the retention cap cuts it", async () => {+ const brief = "a".repeat(60_000);+ const model = retentionModel();+ const { factory } = summaryModels(() => summarySuccess("SUMMARY TEXT"));+ const outcome = await prepareDelegateTurnContext({+ messages: [+ userMessage(brief),+ assistantToolCall("call-1"),+ toolResult("b".repeat(3_000), "call-1"),+ ],+ model,+ taskBrief: brief,+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ if (outcome.kind !== "compacted") return;+ const text = (outcome.messages.at(-1) as { content?: unknown }).content;+ expect(typeof text).toBe("string");+ const budget = retainedUserMessageBudget(contextBudgetLimitsFor(model));+ expect((text as string).length).toBeGreaterThan(budget * 3);+ });+it("retains no bare user message across a completed turn", async () => {const { factory } = summaryModels(() => summarySuccess("SUMMARY TEXT"));const outcome = await prepareDelegateTurnContext({diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.tsindex 913caaafc..51d656f41 100644--- a/packages/agent-runtime/src/subagent-context.ts+++ b/packages/agent-runtime/src/subagent-context.ts@@ -36,6 +36,7 @@ import {} from "./context-budget.js";import {estimateOutputCapInputTokens,+ truncateTextWithinOutputCap,type OutputCapContext,type OutputCapReplayTarget,} from "./output-cap.js";@@ -461,26 +462,19 @@ function truncateDelegateUserMessage(tokenBudget: number,): UserMessage {const text = delegateUserMessageText(message);- const maxChars = Math.max(+ const ceiling = Math.max(1,- Math.floor(tokenBudget * ESTIMATED_TEXT_CHARS_PER_TOKEN),+ Math.floor(Math.max(1, tokenBudget) * ESTIMATED_TEXT_CHARS_PER_TOKEN),);- if (text.length <= maxChars) return message;- if (maxChars <= DELEGATE_RETENTION_TRUNCATION_MARKER.length) {- return {- ...message,- content: DELEGATE_RETENTION_TRUNCATION_MARKER.trim().slice(0, maxChars),- };- }- const retainedChars = maxChars - DELEGATE_RETENTION_TRUNCATION_MARKER.length;- const headChars = Math.ceil(retainedChars * 0.75);- const tailChars = retainedChars - headChars;- return {- ...message,- content: `${text.slice(0, headChars)}${DELEGATE_RETENTION_TRUNCATION_MARKER}${- tailChars > 0 ? text.slice(-tailChars) : ""- }`,- };+ const content = truncateTextWithinOutputCap(+ text,+ tokenBudget,+ DELEGATE_RETENTION_TRUNCATION_MARKER,+ ceiling,+ );+ // A block-shaped brief that already fits stays a block-shaped message.+ if (content === text) return message;+ return { ...message, content };}/** Flatten a user message the way the session's checkpoint truncation does. */