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): classify every overflow pi-ai recovers from as CONTEXT_TOO_LARGE
xpeng5278-web3bbc59bcbcab
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 0ffa964ba..506edb8a8 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -589,8 +589,11 @@ fallback cannot be prepared, persisted, or kept below the safe budget, the userrow and an assistant error remain durable and no provider request starts.Provider-reported context overflow is the last recovery layer: omit the failedassistant from model context, compact once, and retry once. A second overflow-remains terminal. Bedrock's `prompt is too long: N tokens > M maximum` form-maps to this path.+remains terminal and is reported as `CONTEXT_TOO_LARGE`: the error classifier+recognizes every overflow wording pi-ai's `isContextOverflow` recognizes, so a+provider such as DashScope/Qwen or z.ai is not recovered as an overflow and then+reported as a generic `PROVIDER_ERROR`. Bedrock's+`prompt is too long: N tokens > M maximum` form maps to this path.Automatic protection is always enabled and is not user-configurable. Theruntime still accepts a construction-time override that disables it, used bydiff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.mdindex e0281588f..ac7fc80ef 100644--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@ -360,11 +360,25 @@ Node sidecar maps provider SDK errors into:- `PROVIDER_UNAUTHORIZED`- `PROVIDER_RATE_LIMITED`+- `CONTEXT_TOO_LARGE`- `MODEL_NOT_CONFIGURED` (provider rejects the selected model with 404)- `PROVIDER_ERROR`- `NETWORK_ERROR`- `STREAM_FAILED`+A provider message is `CONTEXT_TOO_LARGE` when pi-ai's `isContextOverflow`+recognizes it from the message text — the same check that starts provider+overflow recovery — or when it carries the context-length wording the+classifier already matched (HTTP 413 always). The terminal code therefore+agrees with the recovery decision for every overflow wording pi-ai knows, for+example DashScope/Qwen `Range of input length should be`, z.ai `Prompt+exceeds max length`, xAI `maximum prompt length is`, Groq, llama.cpp, and+Bedrock `Input is too long for requested model`. `CONTEXT_TOO_LARGE` is never+replayed by either retry budget, and a delegate reports it as+`SUBAGENT_CONTEXT_OVERFLOW`. Rate-limit wording, including Bedrock's+`Throttling error: Too many tokens, please wait before trying again.`, is+classified first and stays `PROVIDER_RATE_LIMITED`.+An exact `terminated` provider message and equivalent premature stream-closemessages map to `STREAM_FAILED`. A request-setup or post-response`PROVIDER_RATE_LIMITED` uses the shared runtime budget: ten retries after thediff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex a67f6473f..be236cdf2 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -447,7 +447,9 @@ Headroom 是 16,384 个代币储备底线的最大值,模型最大输出低于安全预算,用户行和助理错误仍然持久并且没有提供商请求开始。提供商报告的上下文溢出是最后一个恢复层:从模型上下文中省略失败的助手,压缩一次,-并重试一次。第二次溢出仍处于终止状态。基岩的+并重试一次。第二次溢出仍处于终止状态,并报告为 `CONTEXT_TOO_LARGE`:错误分类器+识别 pi-ai 的 `isContextOverflow` 能识别的每种溢出措辞,因此 DashScope/Qwen 或+z.ai 等提供商不会先按溢出恢复、随后又被报告为通用的 `PROVIDER_ERROR`。基岩的`prompt is too long: N tokens > M maximum` 形式映射到此路径。自动保护始终启用且用户不可配置。的diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.mdindex a7d42bc46..b6e3de64f 100644--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md@@ -353,11 +353,23 @@ Node sidecar 将提供商 SDK 错误映射到:- `PROVIDER_UNAUTHORIZED`- `PROVIDER_RATE_LIMITED`+- `CONTEXT_TOO_LARGE`- `MODEL_NOT_CONFIGURED`(提供商拒绝选择的模型并返回 404)- `PROVIDER_ERROR`- `NETWORK_ERROR`- `STREAM_FAILED`+当 pi-ai 的 `isContextOverflow` 仅凭消息文本识别出上下文溢出(即启动提供商+溢出恢复的同一检查),或消息带有分类器原本就匹配的上下文长度措辞(HTTP 413+始终如此)时,提供商消息归类为 `CONTEXT_TOO_LARGE`。因此对 pi-ai 已知的每种+溢出措辞,终止错误码都与恢复决策一致,例如 DashScope/Qwen 的+`Range of input length should be`、z.ai 的 `Prompt exceeds max length`、xAI 的+`maximum prompt length is`、Groq、llama.cpp,以及 Bedrock 的+`Input is too long for requested model`。`CONTEXT_TOO_LARGE` 不会进入任何重试+预算,子代理会将其报告为 `SUBAGENT_CONTEXT_OVERFLOW`。限流措辞(包括 Bedrock 的+`Throttling error: Too many tokens, please wait before trying again.`)优先判定,+仍为 `PROVIDER_RATE_LIMITED`。+精确的 `terminated` 提供商消息和等效的过早流关闭消息映射到 `STREAM_FAILED`。请求设置阶段或响应后的`PROVIDER_RATE_LIMITED` 使用共享的运行时预算:初始尝试之后最多 10 次重试,diff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.tsindex 707f33832..4290ee0d0 100644--- a/packages/agent-runtime/src/agent-errors.test.ts+++ b/packages/agent-runtime/src/agent-errors.test.ts@@ -1,8 +1,10 @@import { describe, expect, it } from "vitest";+import { isContextOverflow, type AssistantMessage } from "@earendil-works/pi-ai";import {classifyAgentError,describeNetworkFailure,} from "./agent-errors.js";+import { classifyProviderError } from "./provider-retry.js";describe("classifyAgentError", () => {it.each(["context-validation", "context-estimation", "request-preparation"])(@@ -279,6 +281,43 @@ describe("classifyAgentError", () => {.toMatchObject({ code: "CONTEXT_TOO_LARGE" });});+ // Each message is what pi-ai 1.1.0 reports for that provider's overflow:+ // OpenAI-compatible bodies arrive as "<status>: <body>", Bedrock as its+ // exception prefix. pi-ai's `isContextOverflow` already sends every one of+ // them to overflow recovery, so the terminal code has to agree.+ it.each([+ ["DashScope/Qwen", '400: {"code":"invalid_parameter_error","type":"invalid_request_error","message":"Range of input length should be [1, 98304]"}'],+ ["z.ai", '400: {"code":"1261","message":"Prompt exceeds max length"}'],+ ["xAI", "400: {\"message\":\"This model's maximum prompt length is 131072 but the request contains 537812 tokens.\"}"],+ ["Groq", '400: {"message":"Please reduce the length of the messages or completion.","type":"invalid_request_error"}'],+ ["llama.cpp", '400: {"code":400,"message":"the request exceeds the available context size, try increasing it","type":"exceed_context_size_error"}'],+ ["Bedrock", "Validation error: Input is too long for requested model."],+ ])("classifies the %s overflow pi-ai recovers from as CONTEXT_TOO_LARGE", (_provider, errorMessage) => {+ const message = { role: "assistant", stopReason: "error", errorMessage };+ expect(isContextOverflow(message as AssistantMessage)).toBe(true);+ expect(classifyAgentError(message)).toMatchObject({+ code: "CONTEXT_TOO_LARGE",+ retriable: false,+ });+ expect(classifyProviderError(message)).toMatchObject({+ code: "CONTEXT_TOO_LARGE",+ retriable: false,+ });+ });++ it("classifies Bedrock's token throttle as rate limiting, not an overflow", () => {+ const message = {+ role: "assistant",+ stopReason: "error",+ errorMessage: "Throttling error: Too many tokens, please wait before trying again.",+ };+ expect(isContextOverflow(message as AssistantMessage)).toBe(false);+ expect(classifyAgentError(message)).toMatchObject({+ code: "PROVIDER_RATE_LIMITED",+ retriable: true,+ });+ });+it("keeps context checkpoint failures distinct from provider failures", () => {expect(classifyAgentError(diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.tsindex 05bc51886..eb6b4ece1 100644--- a/packages/agent-runtime/src/agent-errors.ts+++ b/packages/agent-runtime/src/agent-errors.ts@@ -8,6 +8,7 @@* "error") and the rejected-promise paths.*/+import { isContextOverflow, type AssistantMessage } from "@earendil-works/pi-ai";import { ErrorCodes, isCertificateVerificationError } from "@pi-desktop/shared";import { readLocalRequestErrorDetails } from "./local-request-errors.js";@@ -30,6 +31,37 @@ const NETWORK_PATTERN =const CONTEXT_PATTERN =/context[ _-]?length|maximum context|context window|too many tokens|prompt is too long|input token count|exceeds the (?:maximum|model)|token limit/i;+/**+ * Rate limiting worded without a 429. Probed before overflow wording: Bedrock+ * reports its tokens-per-minute throttle as "Throttling error: Too many tokens,+ * please wait before trying again.", which `CONTEXT_PATTERN` would otherwise+ * read as an overflow (pi-ai's `isContextOverflow` excludes it the same way).+ */+const RATE_LIMIT_PATTERN = /rate.?limit|too many requests|quota|overloaded|throttl/i;++/**+ * Whether a provider message reports a context overflow.+ *+ * The runtime decides overflow *recovery* with pi-ai's `isContextOverflow`, so+ * the classifier asks the same question first; otherwise a provider whose+ * wording only pi-ai knows (DashScope/Qwen "Range of input length", z.ai+ * "Prompt exceeds max length", xAI "maximum prompt length", Groq, llama.cpp,+ * Bedrock "Input is too long for requested model") is recovered as an overflow+ * but reported, and retried by delegates, as a generic provider error.+ * `CONTEXT_PATTERN` keeps the wording this classifier already accepted. Only+ * the message text is consulted: no provider id, usage, or context window, so+ * pi-ai's silent-overflow and provider-specific bodyless checks stay with the+ * runtime, which has those facts.+ */+function isContextOverflowMessage(message: string): boolean {+ const probe = {+ role: "assistant",+ stopReason: "error",+ errorMessage: message,+ } as AssistantMessage;+ return isContextOverflow(probe) || CONTEXT_PATTERN.test(message);+}+const STREAM_TERMINATION_PATTERN =/\bterminated\b|stream ended without finish_reason|premature(?:ly)?\s+(?:closed|ended)|(?:stream|response).*(?:closed|interrupted)/i;@@ -479,7 +511,7 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {if (status === 404) return result("MODEL_NOT_CONFIGURED", false);if (status >= 500) return result("PROVIDER_ERROR", true);if (status === 400 || status === 422) {- if (CONTEXT_PATTERN.test(rawMessage)) return result("CONTEXT_TOO_LARGE", false);+ if (isContextOverflowMessage(rawMessage)) return result("CONTEXT_TOO_LARGE", false);// Malformed request (wrong apiStyle, bad params) — retrying won't help.return result("PROVIDER_ERROR", false);}@@ -489,10 +521,10 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {if (/invalid[ _]api[ _]key|api key not valid|unauthorized|authentication|permission denied/i.test(rawMessage)) {return result("PROVIDER_UNAUTHORIZED", false);}- if (/rate.?limit|too many requests|quota|overloaded/i.test(rawMessage)) {+ if (RATE_LIMIT_PATTERN.test(rawMessage)) {return result("PROVIDER_RATE_LIMITED", true);}- if (CONTEXT_PATTERN.test(rawMessage)) {+ if (isContextOverflowMessage(rawMessage)) {return result("CONTEXT_TOO_LARGE", false);}if (/model.{0,20}(not found|does not exist|unknown)|unknown model/i.test(rawMessage)) {diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 55a678610..1450938ed 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -4712,6 +4712,66 @@ describe("DesktopAgentRuntime assistant thinking events", () => {await runtime.dispose();});+ it.each([+ ["DashScope/Qwen", '400: {"code":"invalid_parameter_error","message":"Range of input length should be [1, 98304]"}'],+ ["z.ai", '400: {"code":"1261","message":"Prompt exceeds max length"}'],+ ["Bedrock", "Validation error: Input is too long for requested model."],+ ])("reports a second %s overflow with the code its recovery used", async (_provider, errorMessage) => {+ const onEvent = vi.fn();+ const runtime = createRuntime({ onEvent });+ const agent = (runtime as any).agent;+ const handleAgentEvent = (runtime as any).handleAgentEvent.bind(runtime);+ const user = { role: "user", content: "hello", timestamp: 1 };+ const overflowMessage = (timestamp: number) => ({+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage,+ timestamp,+ });++ agent.prompt = vi.fn(async () => {+ const failed = overflowMessage(2);+ agent.state.messages = [user, failed];+ await handleAgentEvent({ type: "message_start", message: failed });+ await handleAgentEvent({ type: "message_end", message: failed });+ await handleAgentEvent({ type: "turn_end" });+ await handleAgentEvent({ type: "agent_end", messages: [] });+ });+ agent.waitForIdle = vi.fn(async () => undefined);+ const runCompaction = vi.fn(async () => true);+ (runtime as any).runCompaction = runCompaction;+ agent.continue = vi.fn(async () => {+ const failed = overflowMessage(3);+ await handleAgentEvent({ type: "agent_start" });+ await handleAgentEvent({ type: "turn_start" });+ await handleAgentEvent({+ type: "message_start",+ message: { role: "assistant", content: [] },+ });+ await handleAgentEvent({ type: "message_end", message: failed });+ await handleAgentEvent({ type: "turn_end" });+ await handleAgentEvent({ type: "agent_end", messages: [] });+ });++ await runtime.prompt("hello", "user-1");++ // The first failure was recovered as an overflow...+ expect(runCompaction).toHaveBeenCalledTimes(1);+ expect(agent.continue).toHaveBeenCalledTimes(1);+ // ...so the terminal one is reported as one, not as a provider error.+ const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);+ expect(events).toContainEqual(+ expect.objectContaining({+ type: "error",+ error: expect.objectContaining({+ code: "CONTEXT_TOO_LARGE",+ retriable: false,+ }),+ }),+ );++ await runtime.dispose();+ });+it("does not recover provider overflow when automatic compaction is disabled", async () => {const onEvent = vi.fn();const runtime = createRuntime({diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.tsindex 16f9ef9a0..e148894a1 100644--- a/packages/agent-runtime/src/subagent.test.ts+++ b/packages/agent-runtime/src/subagent.test.ts@@ -976,6 +976,42 @@ describe("SubagentRun context budget (ADR 0299)", () => {expect(result.report).toContain("Narrow the task");});+ it.each([+ ["DashScope/Qwen", '400: {"code":"invalid_parameter_error","message":"Range of input length should be [1, 98304]"}'],+ ["Bedrock", "Validation error: Input is too long for requested model."],+ ])("remaps a %s overflow without retrying the same request", async (_provider, errorMessage) => {+ const { run } = createRun();+ const failure = {+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage,+ };+ const state = { messages: [] as Array<Record<string, unknown>> };+ const prompt = vi.fn(async () => {+ state.messages = [{ role: "user", content: "task" }, failure];+ run.handleEvent({ type: "message_start", message: failure });+ run.handleEvent({ type: "message_end", message: failure });+ // An overflow re-sent unchanged fails identically; it must not claim+ // the transient budget the way a gateway 502 does.+ expect(run.pendingProviderRetry).toBeUndefined();+ });+ const continueRun = vi.fn(async () => undefined);+ run.agent = {+ state,+ prompt,+ continue: continueRun,+ waitForIdle: vi.fn(async () => undefined),+ abort: vi.fn(),+ };++ const result = await (run as unknown as SubagentRun).run();++ expect(result.status).toBe("failed");+ expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");+ expect(result.report).toContain("Narrow the task");+ expect(prompt).toHaveBeenCalledTimes(1);+ expect(continueRun).not.toHaveBeenCalled();+ });+it("keeps the boundary guard's overflow code instead of classifying its thrown text", () => {const { run } = createRun();run.pendingContextOverflow = {