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): cap output tokens to the model window
Xing Zhang2b9d34b320db
diff --git a/packages/agent-runtime/src/output-cap.test.ts b/packages/agent-runtime/src/output-cap.test.tsnew file mode 100644index 000000000..66c6d80a3--- /dev/null+++ b/packages/agent-runtime/src/output-cap.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from "vitest";+import {+ clampOutputToContext,+ estimateOutputCapInputTokens,+ type OutputCapContext,+} from "./output-cap.js";++const BASE_CONTEXT: OutputCapContext = {+ messages: [],+};++/** A generic 256k-window model; tests must not depend on any concrete vendor. */+const LARGE_WINDOW_MODEL = { contextWindow: 262_144, maxTokens: 32_768 };++describe("estimateOutputCapInputTokens", () => {+ it("counts ASCII text at the chars/4 baseline", () => {+ const context: OutputCapContext = {+ messages: [{ role: "user", content: "a".repeat(4000) }],+ };+ expect(estimateOutputCapInputTokens(context)).toBe(1000);+ });++ it("counts CJK text at ~1 token per char instead of 0.25", () => {+ const context: OutputCapContext = {+ messages: [{ role: "user", content: "中".repeat(1000) }],+ };+ // chars/4 baseline = 250; CJK correction adds ceil(1000 * 0.75) = 750.+ expect(estimateOutputCapInputTokens(context)).toBe(1000);+ });++ it("counts image blocks via the wire-format estimate", () => {+ const context: OutputCapContext = {+ messages: [+ {+ role: "user",+ content: [+ { type: "image", image: { mediaType: "image/png" } },+ { type: "text", text: "abc" },+ ],+ },+ ],+ };+ // 4800 chars for the image + 3 for the text → ceil(4803 / 4).+ expect(estimateOutputCapInputTokens(context)).toBe(1201);+ });++ it("counts the system prompt and tool schemas", () => {+ const context: OutputCapContext = {+ systemPrompt: "a".repeat(4000),+ messages: [],+ tools: [{ name: "x", description: "b".repeat(4000) }],+ };+ // 1000 (system) + ceil(4030 / 4) for the serialized tool array (the JSON+ // wrapper carries 30 extra chars on top of the 4000-char description).+ expect(estimateOutputCapInputTokens(context)).toBe(2008);+ });++ it("treats a raw string content and empty content consistently", () => {+ expect(+ estimateOutputCapInputTokens({+ messages: [{ role: "user", content: "".repeat(0) }],+ }),+ ).toBe(0);+ });+});++describe("clampOutputToContext", () => {+ it("keeps the requested budget when the input leaves enough room", () => {+ expect(+ clampOutputToContext(LARGE_WINDOW_MODEL, BASE_CONTEXT, 32_768),+ ).toBe(32_768);+ });++ it("uses the model default when no budget is requested", () => {+ expect(clampOutputToContext(LARGE_WINDOW_MODEL, BASE_CONTEXT, undefined)).toBe(+ 32_768,+ );+ });++ it("returns a concrete clamped number even when the requested budget is huge", () => {+ const context: OutputCapContext = {+ // 500,000 estimated tokens already exceeds the 262,144 window, so the+ // output budget collapses to the 1-token floor.+ messages: [{ role: "user", content: "a".repeat(2_000_000) }],+ };+ const clamped = clampOutputToContext(LARGE_WINDOW_MODEL, context, 100_000);+ expect(clamped).toBe(1);+ });++ it("cuts the output budget for a CJK-heavy session near the window edge", () => {+ // A CJK-heavy session near the edge of the window must have its output+ // budget cut so `estimated input + output + reserve` still fits. The+ // chars/4 baseline alone would under-count the input by ~0.75 token per+ // CJK char and could let a large configured output slip through.+ const context: OutputCapContext = {+ messages: [+ { role: "user", content: "中".repeat(200_000) },+ {+ role: "assistant",+ content: [+ { type: "text", text: "已" },+ {+ type: "toolCall",+ name: "read_file",+ arguments: JSON.stringify({ path: "/tmp/a.md" }),+ },+ ],+ },+ ],+ };+ const estimate = estimateOutputCapInputTokens(context);+ const clamped = clampOutputToContext(LARGE_WINDOW_MODEL, context, 92_709);+ expect(estimate).toBeGreaterThan(160_000);+ // estimate (≥160k) + clamped + reserve (4096) must fit the 262144 window.+ expect(estimate + clamped + 4096).toBeLessThanOrEqual(+ LARGE_WINDOW_MODEL.contextWindow,+ );+ expect(clamped).toBeLessThan(92_709);+ });++ it("keeps the requested budget when the window is unknown", () => {+ const model = { contextWindow: 0, maxTokens: 4096 };+ expect(clampOutputToContext(model, BASE_CONTEXT, 8888)).toBe(8888);+ });++ it("never exceeds the requested budget", () => {+ const context: OutputCapContext = {+ messages: [{ role: "user", content: "a".repeat(100) }],+ };+ for (const requested of [1, 128, 4096, 32_768, 100_000]) {+ expect(+ clampOutputToContext(LARGE_WINDOW_MODEL, context, requested),+ ).toBeLessThanOrEqual(requested);+ }+ });+});diff --git a/packages/agent-runtime/src/output-cap.ts b/packages/agent-runtime/src/output-cap.tsnew file mode 100644index 000000000..1aa201a41--- /dev/null+++ b/packages/agent-runtime/src/output-cap.ts@@ -0,0 +1,164 @@+/**+ * Output-token capping enforced at the pi-desktop stream layer (issue B).+ *+ * pi-ai only clamps `max_tokens` on the `streamSimple` path+ * (`buildBaseOptions` → `clampMaxTokensToContext`). The low-level stream+ * adapter used for `thinkingLevel: "omit"` sends `options.maxTokens`+ * untouched, and the estimate that feeds pi-ai's clamp (`chars / 4`,+ * `CHARS_PER_TOKEN = 4`) systematically under-counts CJK text. Both routes+ * can therefore hand the provider an output budget that pushes+ * `input + output` past the model's real context window, ending in a+ * `maximum context length` 400/413/503.+ *+ * This module re-clamps the effective output budget for *both* routes at the+ * pi-desktop layer, using a CJK-aware input estimate (a CJK character runs+ * ~1 token, not the 0.25 the chars/4 baseline charges) and a safety margin+ * that scales with the window instead of pi-ai's fixed 4096. It is applied+ * in `runtime.ts` and `subagent-model-binding.ts` before either adapter+ * branch runs, so the clamp holds for `streamSimple` and `stream` alike.+ */++/** Structural view of the request context; assignable from pi-ai's `Context`. */+export type OutputCapContext = {+ systemPrompt?: string;+ messages: Array<{ role: string; content: unknown }>;+ tools?: Array<unknown>;+};++/** Structural view of the active model. */+export type OutputCapModel = {+ contextWindow: number;+ maxTokens: number;+};++/** Fallback reserve when the window is too small to afford the ratio. */+const OUTPUT_SAFETY_FLOOR_TOKENS = 4096;+/** Window-proportional reserve; at 262k this is ~4k, at 1M ~10k. */+const OUTPUT_SAFETY_WINDOW_RATIO = 0.01;+/** Wire-format estimate constants, matching pi-ai's internal estimator. */+const CHARS_PER_TOKEN = 4;+const ESTIMATED_CHARS_PER_IMAGE = 4800;++function countCjkChars(text: string): number {+ let count = 0;+ for (const ch of text) {+ const code = ch.codePointAt(0) ?? 0;+ if (+ // CJK Unified Ideographs + Extension A.+ (code >= 0x3400 && code <= 0x9fff) ||+ // CJK Extension B..F (historical/supplementary plane).+ (code >= 0x20000 && code <= 0x2ebef) ||+ // CJK punctuation and full-width forms.+ (code >= 0x3000 && code <= 0x303f) ||+ (code >= 0xff00 && code <= 0xffef)+ ) {+ count += 1;+ }+ }+ return count;+}++function stringifyForEstimate(value: unknown): string {+ try {+ const serialized = JSON.stringify(value);+ return serialized === undefined ? "" : serialized;+ } catch {+ return "[unserializable]";+ }+}++/** Token estimate for one message's content (text/thinking/tool/image). */+function estimateMessageTokens(content: unknown): {+ baseline: number;+ cjkChars: number;+} {+ if (typeof content === "string") {+ return {+ baseline: Math.ceil(content.length / CHARS_PER_TOKEN),+ cjkChars: countCjkChars(content),+ };+ }+ if (!Array.isArray(content)) return { baseline: 0, cjkChars: 0 };+ let chars = 0;+ let cjkChars = 0;+ for (const block of content) {+ if (!block || typeof block !== "object") continue;+ const b = block as { type?: unknown; [key: string]: unknown };+ if (b.type === "text" && typeof b.text === "string") {+ chars += b.text.length;+ cjkChars += countCjkChars(b.text);+ } else if (b.type === "thinking" && typeof b.thinking === "string") {+ chars += b.thinking.length;+ cjkChars += countCjkChars(b.thinking);+ } else if (+ (b.type === "toolCall" || b.type === "functionCall") &&+ typeof b.name === "string"+ ) {+ const payload = stringifyForEstimate(b.arguments ?? b.input);+ chars += b.name.length + payload.length;+ cjkChars += countCjkChars(b.name);+ } else {+ chars += ESTIMATED_CHARS_PER_IMAGE;+ }+ }+ return { baseline: Math.ceil(chars / CHARS_PER_TOKEN), cjkChars };+}++/**+ * Estimate the input tokens of a request. Mirrors pi-ai's internal estimator+ * (chars/4, 1200 tokens per image, serialized tool schemas) and adds the+ * missing CJK correction: a CJK char costs ~1 token while the baseline+ * charges 0.25, so the shortfall is added back.+ */+export function estimateOutputCapInputTokens(+ context: OutputCapContext,+): number {+ let baseline = 0;+ let cjkChars = 0;+ for (const message of context.messages) {+ const estimated = estimateMessageTokens(message.content);+ baseline += estimated.baseline;+ cjkChars += estimated.cjkChars;+ }+ if (context.systemPrompt) {+ baseline += Math.ceil(context.systemPrompt.length / CHARS_PER_TOKEN);+ cjkChars += countCjkChars(context.systemPrompt);+ }+ if (context.tools?.length) {+ baseline += Math.ceil(+ stringifyForEstimate(context.tools).length / CHARS_PER_TOKEN,+ );+ }+ // CJK chars are ~1 token each; the chars/4 baseline charged them 0.25.+ return baseline + Math.ceil(cjkChars * 0.75);+}++/**+ * Cap the effective output budget so `estimatedInput + output` stays inside+ * the model's context window, regardless of which adapter branch the caller+ * picks (omit → low-level `stream`, everything else → `streamSimple`).+ *+ * Returns a concrete number so the low-level `stream` path, which never+ * re-derives `max_tokens`, still goes out clamped.+ */+export function clampOutputToContext(+ model: OutputCapModel,+ context: OutputCapContext,+ requestedMaxTokens: number | undefined,+): number {+ const contextWindow = Math.max(1, Math.round(model.contextWindow || 0));+ const desired = Math.max(+ 1,+ Math.round(requestedMaxTokens ?? model.maxTokens),+ );+ // Unknown window: there is nothing context-based to clamp against; keep the+ // configured budget (mirrors pi-ai's `contextWindow <= 0` behavior).+ if (model.contextWindow <= 0) return desired;+ const inputTokens = estimateOutputCapInputTokens(context);+ const reserve = Math.max(+ OUTPUT_SAFETY_FLOOR_TOKENS,+ Math.ceil(contextWindow * OUTPUT_SAFETY_WINDOW_RATIO),+ );+ const byContext = Math.max(1, contextWindow - inputTokens - reserve);+ return Math.min(desired, byContext);+}diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 359324422..63c286968 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -144,6 +144,7 @@ import {seedDelegateMessages,type DelegationChain,} from "./delegation-history.js";+import { clampOutputToContext } from "./output-cap.js";import {composeSubagentSystemPrompt,SubagentRun,@@ -1846,6 +1847,12 @@ Delegation rules:const stallAbort = new AbortController();const attemptOptions: SimpleStreamOptions = {...hookedOptions,+ // Cap the output budget at the pi-desktop layer so the estimate+ // holds for both adapter branches: `streamSimple` re-derives+ // max_tokens, but the low-level `stream` path used by+ // `thinkingLevel: "omit"` would otherwise send it untouched, and+ // both consume an estimate that under-counts CJK text (issue B).+ maxTokens: clampOutputToContext(m, context, hookedOptions.maxTokens),signal: AbortSignal.any([...(hookedOptions.signal ? [hookedOptions.signal] : []),stallAbort.signal,diff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.tsindex 65fbbfe6f..e899ec9c0 100644--- a/packages/agent-runtime/src/subagent-model-binding.ts+++ b/packages/agent-runtime/src/subagent-model-binding.ts@@ -10,7 +10,11 @@ import {withOpenCodeSessionHeaders,} from "./opencode-session-headers.js";import { mergeProviderHeaders, withProviderHeaders } from "./provider-headers.js";-import { agentThinkingLevel as agentThinkingLevelFor, omitThinkingModel as withOmittedThinking } from "./thinking-level.js";+import { clampOutputToContext } from "./output-cap.js";+import {+ agentThinkingLevel as agentThinkingLevelFor,+ omitThinkingModel as withOmittedThinking,+} from "./thinking-level.js";import { captureProviderResponse, carriesRetryDelayHeaders, createProviderRetryStream } from "./provider-retry.js";import type { AgentOptions } from "@earendil-works/pi-agent-core";import type { SubagentThinkingLevel } from "@pi-desktop/shared";@@ -58,6 +62,10 @@ export function subagentModelBinding(opts: {withOpenCodeSessionHeaders({...options,+ // Same request-side output cap as the parent runtime: the+ // `omit` branch hits pi-ai's low-level `stream` which never+ // re-derives max_tokens (issue B).+ maxTokens: clampOutputToContext(m, context, options?.maxTokens),maxRetries: 0,sessionId: opts.sessionId,fetch: captureProviderResponse(options?.fetch, (response) => {