Skip to content

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

fix(agent-runtime): CJK-aware compaction summary sizing and chunked delegate summaries (#2364)

koeria509bad64319a
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 0df091425..4ce17e13e 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -708,7 +708,9 @@ request. The automatic summary request retries transient provider failures
under a bounded pi-ai retry policy (3 retries, 2s/4s/8s backoff, cancelled by
Stop); deterministic failures such as quota or auth return at once. The
preflight guard sizes the prompt pi actually serializes — tool results already
-capped — rather than the raw messages, and when that prompt still exceeds the
+capped — rather than the raw messages, with the CJK correction the output-cap
+estimator carries (Han, kana, and Hangul run ~1 token per character, not the
+1/3.5 the chars-per-token baseline bills), and when that prompt still exceeds the
window it tries exactly one reduced input (tool results cut to a short prefix,
thinking dropped, no message removed). If even that input does not fit, the range
is split into contiguous chunks that each do: at most 16 requests, each carrying
diff --git a/packages/agent-runtime/src/compaction-summary-input.test.ts b/packages/agent-runtime/src/compaction-summary-input.test.ts
index 56731f5a4..443383501 100644
--- a/packages/agent-runtime/src/compaction-summary-input.test.ts
+++ b/packages/agent-runtime/src/compaction-summary-input.test.ts
@@ -13,7 +13,9 @@ import {
COMPACTION_SUMMARY_PROMPT_SAFETY_TOKENS,
COMPACTION_SUMMARY_RETRY_BASE_MS,
COMPACTION_SUMMARY_RETRY_POLICY,
+ COMPACTION_SUMMARY_CHUNK_MARGIN,
compactionSummaryReserveTokens,
+ estimatePromptTextTokens,
estimateSummaryPromptTokens,
planSummaryChunks,
reduceSummaryInput,
@@ -120,6 +122,34 @@ describe("estimateSummaryPromptTokens", () => {
const unsplit = input(history, { isSplitTurn: false, turnPrefixMessages: prefix });
expect(estimateSummaryPromptTokens(unsplit)).toBe(estimateSummaryPromptTokens(input(history)));
});
+
+ // Issue #2364: Han tokenizes at ~1 token per character while the chars/3.5
+ // baseline bills it 1/3.5, so a CJK prompt that "fits" is sent whole and
+ // rejected as a context overflow. The estimate must carry the correction.
+ it("does not treat 1600 CJK characters as a few hundred tokens", () => {
+ const cjk = input([user("中".repeat(1_600))]);
+ const ascii = input([user("a".repeat(1_600))]);
+ const cjkTokens = estimateSummaryPromptTokens(cjk);
+ const asciiTokens = estimateSummaryPromptTokens(ascii);
+
+ expect(cjkTokens).toBeGreaterThanOrEqual(1_500);
+ expect(cjkTokens).toBeLessThanOrEqual(1_700);
+ expect(asciiTokens).toBeGreaterThan(400);
+ expect(asciiTokens).toBeLessThan(500);
+ });
+
+ it("sizes a CJK history over the summary input limit the guard rejects", () => {
+ // A limit of 800 must not wave the 1600-character CJK prompt through.
+ const cjk = input([user("中".repeat(1_600))]);
+ expect(estimateSummaryPromptTokens(cjk)).toBeGreaterThan(800);
+ });
+
+ it("carries the CJK correction for a CJK previous summary", () => {
+ const base = input([user("ask")], { previousSummary: "摘".repeat(3_500) });
+ const tokens = estimateSummaryPromptTokens(base);
+ expect(tokens).toBeGreaterThan(3_500);
+ expect(tokens).toBeLessThan(4_000);
+ });
});
describe("reduceSummaryInput", () => {
@@ -259,6 +289,35 @@ describe("planSummaryChunks", () => {
expect(planSummaryChunks(input([]), options)).toBeUndefined();
});
+ // Issue #2364: a CJK range that the chars/3.5 estimate believes fits one
+ // chunk is split so every chunk meets the CJK-aware guard's budget, and a
+ // single over-budget CJK message is truncated further, not left oversized.
+ it("splits a CJK range the chars-per-token estimate would send whole", () => {
+ // budget = floor(800*0.9) = 720 tokens; a 400-CJK-char message costs ~415,
+ // so two per chunk would exceed it — while chars/3.5 sees only ~115.
+ const messages = Array.from({ length: 4 }, () => user("中".repeat(400)));
+ const chunks = planSummaryChunks(input(messages), {
+ summaryInputLimit: 800,
+ reserveTokens: 0,
+ });
+ expect(chunks).toBeDefined();
+ expect(chunks!.length).toBeGreaterThan(1);
+ expect(chunks!.flat()).toEqual(messages);
+ });
+
+ it("truncates an oversized CJK message inside the chunk's token budget", () => {
+ const chunks = planSummaryChunks(input([user("中".repeat(5_000))]), {
+ summaryInputLimit: 800,
+ reserveTokens: 0,
+ });
+ expect(chunks).toHaveLength(1);
+ const text = (chunks![0]![0] as { content: Array<{ text: string }> }).content[0]!.text;
+ expect(text).toContain(SUMMARY_CHUNK_TRUNCATION_MARKER.trim());
+ expect(estimatePromptTextTokens(text)).toBeLessThanOrEqual(
+ Math.floor(800 * COMPACTION_SUMMARY_CHUNK_MARGIN),
+ );
+ });
+
it("refuses a range that would need more requests than the bound allows", () => {
const tiny = { summaryInputLimit: 100, reserveTokens: 0 };
const messages = Array.from({ length: COMPACTION_SUMMARY_MAX_CHUNKS + 4 }, (_, index) =>
diff --git a/packages/agent-runtime/src/compaction-summary-input.ts b/packages/agent-runtime/src/compaction-summary-input.ts
index e18d35afc..aa24fc5c8 100644
--- a/packages/agent-runtime/src/compaction-summary-input.ts
+++ b/packages/agent-runtime/src/compaction-summary-input.ts
@@ -8,6 +8,7 @@ import {
estimateTokens,
} from "./pi-runtime-estimates.js";
import { convertToLlm, serializeConversation } from "./pi-runtime-messages.js";
+import { countCjkChars } from "./output-cap.js";
import type { CompactionPreparation } from "./pi-runtime-types.js";
import { DEFAULT_MAX_TOKENS } from "./provider-binding.js";
@@ -77,6 +78,62 @@ export type CompactionSummaryInput = Pick<
"messagesToSummarize" | "turnPrefixMessages" | "isSplitTurn" | "previousSummary"
>;
+/**
+ * CJK-aware token estimate of one serialized prompt string: the chars/3.5
+ * baseline pi's text estimator uses, plus the shortfall the baseline charges
+ * CJK text — Han, kana, and Hangul tokenize at ~1 token per character while
+ * the baseline bills them 1/3.5, so 0.75 tokens per CJK character are added
+ * back (issue #2364). A CJK prompt that looks like it fits at chars/3.5 is
+ * otherwise sent whole and rejected as a context overflow.
+ */
+export function estimatePromptTextTokens(text: string): number {
+ return (
+ Math.ceil(text.length / ESTIMATED_TEXT_CHARS_PER_TOKEN) +
+ Math.ceil(countCjkChars(text) * 0.75)
+ );
+}
+
+/** CJK characters carried by one message's text-bearing content blocks. */
+function messageCjkChars(message: AgentMessage): number {
+ const content: unknown = (message as { content?: unknown }).content;
+ if (typeof content === "string") return countCjkChars(content);
+ if (!Array.isArray(content)) return 0;
+ let count = 0;
+ for (const block of content) {
+ if (!block || typeof block !== "object") continue;
+ const record = block as { type?: unknown; [key: string]: unknown };
+ if (record.type === "text" && typeof record.text === "string") {
+ count += countCjkChars(record.text);
+ } else if (record.type === "thinking" && typeof record.thinking === "string") {
+ count += countCjkChars(record.thinking);
+ } else if (
+ (record.type === "toolCall" || record.type === "functionCall") &&
+ typeof record.name === "string"
+ ) {
+ // JSON.stringify leaves Han unescaped, so the arguments the provider
+ // receives carry the same characters the correction has to charge.
+ const payload = (() => {
+ try {
+ const serialized = JSON.stringify(record.arguments ?? record.input);
+ return serialized === undefined ? "" : serialized;
+ } catch {
+ return "";
+ }
+ })();
+ count += countCjkChars(record.name) + countCjkChars(payload);
+ }
+ }
+ return count;
+}
+
+/** Per-message chunk cost: pi's estimator plus the CJK shortfall it ignores. */
+function estimateChunkMessageTokens(message: AgentMessage): number {
+ return (
+ Math.ceil(estimateTokens(message)) +
+ Math.ceil(messageCjkChars(message) * 0.75)
+ );
+}
+
/**
* Tokens the summary request(s) will carry for this input, using pi's own
* serialization and text-token estimate. A split turn issues two requests
@@ -84,16 +141,14 @@ export type CompactionSummaryInput = Pick<
* the larger one is the one that has to fit.
*/
export function estimateSummaryPromptTokens(input: CompactionSummaryInput): number {
- const historyChars =
- serializeConversation(convertToLlm(input.messagesToSummarize)).length +
- (input.previousSummary?.length ?? 0);
- const turnPrefixChars =
+ const history =
+ serializeConversation(convertToLlm(input.messagesToSummarize)) +
+ (input.previousSummary ?? "");
+ const turnPrefix =
input.isSplitTurn && input.turnPrefixMessages.length > 0
- ? serializeConversation(convertToLlm(input.turnPrefixMessages)).length
- : 0;
- return Math.ceil(
- Math.max(historyChars, turnPrefixChars) / ESTIMATED_TEXT_CHARS_PER_TOKEN,
- );
+ ? serializeConversation(convertToLlm(input.turnPrefixMessages))
+ : "";
+ return Math.max(estimatePromptTextTokens(history), estimatePromptTextTokens(turnPrefix));
}
/**
@@ -194,7 +249,9 @@ export function compactionSummaryReserveTokens(input: {
outputBudget: number;
}): number {
return Math.max(
- Math.ceil((input.previousSummary?.length ?? 0) / ESTIMATED_TEXT_CHARS_PER_TOKEN),
+ input.previousSummary
+ ? estimatePromptTextTokens(input.previousSummary)
+ : 0,
input.outputBudget,
);
}
@@ -214,6 +271,30 @@ export function compactionSummaryReserveTokens(input: {
* message larger than the budget is truncated rather than dropped, so no message
* ever leaves the summary's scope.
*/
+/**
+ * Largest character budget that keeps a truncated message inside the chunk's
+ * token budget. Plain ASCII keeps the chars/3.5 cap; a CJK-bearing message is
+ * cut further by binary search so the truncated text still meets the same
+ * CJK-aware estimate the guard and the planner use (issue #2364).
+ */
+function chunkTruncationChars(message: AgentMessage, budgetTokens: number): number {
+ const asciiCap = Math.floor(budgetTokens * ESTIMATED_TEXT_CHARS_PER_TOKEN);
+ if (messageCjkChars(message) === 0) return asciiCap;
+ let lo = 0;
+ let hi = asciiCap;
+ while (lo < hi) {
+ const mid = lo + Math.ceil((hi - lo) / 2);
+ const truncated = truncateMessageText(
+ message,
+ mid,
+ SUMMARY_CHUNK_TRUNCATION_MARKER,
+ );
+ if (estimateChunkMessageTokens(truncated) <= budgetTokens) lo = mid;
+ else hi = mid - 1;
+ }
+ return lo;
+}
+
export function planSummaryChunks(
input: CompactionSummaryInput,
options: { summaryInputLimit: number; reserveTokens: number },
@@ -234,7 +315,7 @@ export function planSummaryChunks(
let current: AgentMessage[] = [];
let tokens = 0;
for (const message of range) {
- const cost = Math.max(1, Math.ceil(estimateTokens(message)));
+ const cost = Math.max(1, estimateChunkMessageTokens(message));
if (current.length > 0 && tokens + cost > budget) {
chunks.push(current);
if (chunks.length >= COMPACTION_SUMMARY_MAX_CHUNKS) return undefined;
@@ -245,7 +326,7 @@ export function planSummaryChunks(
cost > budget
? truncateMessageText(
message,
- Math.floor(budget * ESTIMATED_TEXT_CHARS_PER_TOKEN),
+ chunkTruncationChars(message, budget),
SUMMARY_CHUNK_TRUNCATION_MARKER,
)
: message,
diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.ts
index 0e7cf3670..308ab3f56 100644
--- a/packages/agent-runtime/src/output-cap.ts
+++ b/packages/agent-runtime/src/output-cap.ts
@@ -116,7 +116,13 @@ const ESTIMATED_CHARS_PER_IMAGE = 4800;
// Han, Japanese kana, and Korean Hangul tokenize at ~1 token per character,
// as do CJK punctuation and full-width forms. The chars/4 baseline charges
// all of these 0.25.
-function countCjkChars(text: string): number {
+/**
+ * CJK characters (Han, kana, Hangul, full-width forms) tokenize at roughly one
+ * token each. Exposed for estimators outside this module — e.g. the compaction
+ * summary prompt sizer, which sizes serialized prompt text with the chars/3.5
+ * baseline — that need the same CJK definition and correction coefficient.
+ */
+export function countCjkChars(text: string): number {
let count = 0;
for (const ch of text) {
const code = ch.codePointAt(0) ?? 0;
diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.ts
index 51d656f41..b43733740 100644
--- a/packages/agent-runtime/src/subagent-context.ts
+++ b/packages/agent-runtime/src/subagent-context.ts
@@ -42,7 +42,12 @@ import {
} from "./output-cap.js";
import {
COMPACTION_SUMMARY_RETRY_POLICY,
+ addSummaryUsage,
+ compactionSummaryInputLimit,
+ compactionSummaryOutputBudget,
+ compactionSummaryReserveTokens,
estimateSummaryPromptTokens,
+ planSummaryChunks,
reduceSummaryInput,
type CompactionSummaryInput,
} from "./compaction-summary-input.js";
@@ -309,41 +314,69 @@ async function compactDelegateContext(
previousSummary,
};
// The summary request itself must fit the window; shrink it one bounded
- // step the way the session does, then give up to the degradation path.
+ // step the way the session does. When even the reduced input cannot fit one
+ // prompt — a CJK-bearing range the chars/3.5 baseline under-counts (issue
+ // #2364) — the shared chunk planner splits it into requests that each fit,
+ // the same machinery the session compaction uses (issue #827).
+ let chunkedRequests: AgentMessage[][] | undefined;
if (delegateSummaryInputExceedsBudget(summaryInput, input.model, budget)) {
const reduced = reduceSummaryInput(summaryInput);
- if (
- !reduced ||
- delegateSummaryInputExceedsBudget(reduced, input.model, budget)
- ) {
- return undefined;
+ if (reduced) summaryInput = reduced;
+ if (delegateSummaryInputExceedsBudget(summaryInput, input.model, budget)) {
+ // The reduced input still cannot fit one prompt — a CJK-bearing range
+ // the chars/3.5 baseline under-counts (issue #2364) — so the shared
+ // chunk planner splits it into requests that each fit, the same
+ // machinery the session compaction uses (issue #827).
+ const chunks = planSummaryChunks(summaryInput, {
+ summaryInputLimit: compactionSummaryInputLimit({
+ hardLimit: budget.hardLimit,
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: input.model.maxTokens,
+ }),
+ reserveTokens: compactionSummaryReserveTokens({
+ previousSummary: summaryInput.previousSummary,
+ outputBudget: compactionSummaryOutputBudget({
+ requestHeadroom: budget.requestHeadroom,
+ modelMaxTokens: input.model.maxTokens,
+ }),
+ }),
+ });
+ if (!chunks) return undefined;
+ chunkedRequests = chunks;
}
- summaryInput = reduced;
}
- const result = await generateSummaryWithUsage(
- summaryInput.messagesToSummarize,
- input.summaryModels(),
- input.model,
- budget.requestHeadroom,
- undefined,
- summaryInput.previousSummary,
- input.thinkingLevel,
- COMPACTION_SUMMARY_RETRY_POLICY,
- undefined,
- input.signal,
- );
- if (!result.ok) {
- if (result.error.code === "aborted" || input.signal.aborted) {
- // A stop that landed mid-summary is an abort, not a compaction failure.
- throw new Error("Turn aborted while compacting context");
+ let runningSummary = summaryInput.previousSummary;
+ let summaryUsage: Usage | undefined;
+ for (const chunk of chunkedRequests ?? [summaryInput.messagesToSummarize]) {
+ const result = await generateSummaryWithUsage(
+ chunk,
+ input.summaryModels(),
+ input.model,
+ budget.requestHeadroom,
+ undefined,
+ runningSummary,
+ input.thinkingLevel,
+ COMPACTION_SUMMARY_RETRY_POLICY,
+ undefined,
+ input.signal,
+ );
+ if (!result.ok) {
+ if (result.error.code === "aborted" || input.signal.aborted) {
+ // A stop that landed mid-summary is an abort, not a compaction failure.
+ throw new Error("Turn aborted while compacting context");
+ }
+ return undefined;
}
- return undefined;
+ runningSummary = result.value.text;
+ summaryUsage = addSummaryUsage(summaryUsage, result.value.usage);
}
return {
messages: [
createCompactionSummaryMessage(
- result.value.text,
+ // The loop always summarizes at least one chunk, so the running
+ // summary is the last request's text by the time we get here.
+ runningSummary ?? "",
prepared.value.tokensBefore,
Date.now(),
),
@@ -354,7 +387,7 @@ async function compactDelegateContext(
),
],
tokensBefore: prepared.value.tokensBefore,
- summaryUsage: result.value.usage,
+ summaryUsage,
};
}