Skip to content

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

fix(agent-runtime): clamp max_tokens to a stated output ceiling

xpeng5278-web76ed6ca5e48c
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 76cabcdba..935d24fff 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -293,10 +293,16 @@ that the model intended an action.
Before surfacing a pre-stream `PROVIDER_ERROR` for HTTP 400/422 whose message
ends in `(no body)`, the runtime makes at most one silent repair attempt with
the generated output-limit fields removed: `max_tokens`,
-`max_completion_tokens`, and `max_output_tokens`. This repair does not consume
+`max_completion_tokens`, and `max_output_tokens`. The same one attempt clamps
+those fields down to the ceiling when the body states one (`at most N
+completion tokens`, `max_tokens: N > M, which is the maximum allowed number of
+output tokens`, or `expected a value <= N`) instead of deleting them.
+Anthropic rejects a request that omits `max_tokens`. A field that is absent or
+already within the ceiling is left unchanged. Credit exhaustion and context
+overflow stay on their existing terminal paths. This repair does not consume
the transient retry budget or add backoff, and the caller's `onPayload` rewrite
-remains active. A second opaque failure is terminal, and an abort before the
-repair starts prevents the repair request.
+remains active. A second failure of the same kind is terminal, and an abort
+before the repair starts prevents the repair request.
The non-429 delay honors the server first: `retry-after-ms`, `retry-after`
seconds, then `retry-after` HTTP-date, capped at 8 seconds. Captured headers are
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 285429a01..f53e3c9ae 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8111,15 +8111,20 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
removed. The caller's payload rewrite remains active, the repair consumes no
transient retry budget or backoff, and both Chat Completions and Responses
fixtures complete on their second request. A second opaque failure remains
- terminal.
+ terminal. A 400/422 that names an output ceiling (`at most N completion
+ tokens`, `max_tokens: N > M, which is the maximum allowed number of output
+ tokens`, or `expected a value <= N`) gets one silent repair that clamps
+ those fields to that ceiling instead of removing them. Credit exhaustion
+ and context overflow do not take this repair.
- If the turn is aborted after the first opaque failure, the repair request is
not started and the result is `aborted`.
- A mid-stream HTTP 429 is covered by E2E-149's separate ten-retry path; the
two budgets do not draw from each other.
- Authentication, model-selection, context, and descriptive
malformed-request failures do not enter either provider replay path. The
- opaque empty-body 400/422 case is the bounded repair exception described
- above. Infinite mode changes no classification and only removes the retry
+ opaque empty-body 400/422 case and the explicit output-ceiling case are
+ the bounded repair exceptions described above. Infinite mode changes no
+ classification and only removes the retry
ceiling for admitted network/transient failures; it remains abortable and
is visibly marked with an unbounded retry indicator.
- **Specs linked**: `03-runtime/01-ipc-protocol.md`,
diff --git a/packages/agent-runtime/src/provider-retry.test.ts b/packages/agent-runtime/src/provider-retry.test.ts
index 7c276caef..eadab7aca 100644
--- a/packages/agent-runtime/src/provider-retry.test.ts
+++ b/packages/agent-runtime/src/provider-retry.test.ts
@@ -1090,6 +1090,150 @@ describe("opaque bad-request repair", () => {
});
});
+const OPENAI_OUTPUT_CEILING =
+ "OpenAI API error (400): max_tokens is too large: 16384. This model supports at most 4096 completion tokens, whereas you provided 16384.";
+const ANTHROPIC_OUTPUT_CEILING =
+ 'API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"max_tokens: 65537 > 64000, which is the maximum allowed number of output tokens for claude-opus-4-5-20251101"}}';
+
+describe("explicit output-limit repair", () => {
+ async function repairPayload(
+ errorMessage: string,
+ payload: Record<string, unknown>,
+ ): Promise<{ attempts: number; repaired: unknown; claim: ReturnType<typeof vi.fn>; sleep: ReturnType<typeof vi.fn> }> {
+ let attempts = 0;
+ let repairOptions: { onPayload?: (payload: unknown) => Promise<unknown> } | undefined;
+ const claim = vi.fn(() => undefined);
+ const sleep = vi.fn(async () => undefined);
+ const stream = createProviderRetryStream(
+ model,
+ context,
+ {
+ onPayload: async (body: unknown) => ({
+ ...(body as Record<string, unknown>),
+ marked: true,
+ }),
+ } as any,
+ (options) => {
+ attempts += 1;
+ if (attempts === 1) return failedStream({ errorMessage });
+ repairOptions = options as typeof repairOptions;
+ return successfulStream();
+ },
+ {
+ claim,
+ headers: () => undefined,
+ status: () => undefined,
+ sleep,
+ },
+ );
+ for await (const _event of stream) {
+ // Drain so the repair hook is installed before we inspect it.
+ }
+ return {
+ attempts,
+ repaired: await repairOptions?.onPayload?.(payload),
+ claim,
+ sleep,
+ };
+ }
+
+ it("clamps an OpenAI completion ceiling instead of failing the turn", async () => {
+ const result = await repairPayload(OPENAI_OUTPUT_CEILING, {
+ model: "ft:gpt-4o",
+ max_tokens: 16384,
+ max_completion_tokens: 16384,
+ temperature: 0,
+ });
+
+ expect(result.attempts).toBe(2);
+ expect(result.claim).not.toHaveBeenCalled();
+ expect(result.sleep).not.toHaveBeenCalled();
+ expect(result.repaired).toEqual({
+ marked: true,
+ model: "ft:gpt-4o",
+ max_tokens: 4096,
+ max_completion_tokens: 4096,
+ temperature: 0,
+ });
+ });
+
+ it("clamps an Anthropic output ceiling without dropping max_tokens", async () => {
+ const result = await repairPayload(ANTHROPIC_OUTPUT_CEILING, {
+ model: "claude-opus-4-5-20251101",
+ max_tokens: 65537,
+ messages: [{ role: "user", content: "hi" }],
+ });
+
+ expect(result.attempts).toBe(2);
+ expect(result.claim).not.toHaveBeenCalled();
+ expect(result.sleep).not.toHaveBeenCalled();
+ expect(result.repaired).toEqual({
+ marked: true,
+ model: "claude-opus-4-5-20251101",
+ max_tokens: 64000,
+ messages: [{ role: "user", content: "hi" }],
+ });
+ });
+
+ it("leaves credit and context-overflow 400s terminal", async () => {
+ const credit = await repairPayload(
+ "400 This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, but can only afford 1000.",
+ { max_tokens: 65536 },
+ );
+ const overflow = await repairPayload(
+ "400 prompt is too long: 213462 tokens > 200000 maximum",
+ { max_tokens: 64000 },
+ );
+
+ expect(credit.attempts).toBe(1);
+ expect(overflow.attempts).toBe(1);
+ expect(credit.claim).toHaveBeenCalledTimes(1);
+ expect(overflow.claim).toHaveBeenCalledTimes(1);
+ });
+
+ it("clamps a proxy expected-value ceiling without adding a missing field", async () => {
+ const result = await repairPayload(
+ '400 {"error":{"code":"InvalidParameter","message":"The parameter max_tokens specified in the request is not valid: integer above maximum value, expected a value <= 32768, but got 64000 instead."}}',
+ { max_tokens: 64000, stream: true },
+ );
+
+ expect(result.attempts).toBe(2);
+ expect(result.repaired).toEqual({
+ marked: true,
+ max_tokens: 32768,
+ stream: true,
+ });
+ });
+
+ it("surfaces the original ceiling error when the clamped attempt fails the same way", async () => {
+ let attempts = 0;
+ const claim = vi.fn(() => undefined);
+ const stream = createProviderRetryStream(
+ model,
+ context,
+ {},
+ () => {
+ attempts += 1;
+ return failedStream({ errorMessage: OPENAI_OUTPUT_CEILING });
+ },
+ {
+ claim,
+ headers: () => undefined,
+ status: () => undefined,
+ sleep: async () => undefined,
+ },
+ );
+
+ const events: string[] = [];
+ for await (const event of stream) events.push(event.type);
+
+ expect(attempts).toBe(2);
+ expect(events).toEqual(["error"]);
+ expect((await stream.result()).errorMessage).toBe(OPENAI_OUTPUT_CEILING);
+ expect(claim).toHaveBeenCalledTimes(1);
+ });
+});
+
describe("stream idle watchdog", () => {
it("reads the idle budget from the environment with a safe default", () => {
const previous = process.env.PI_DESKTOP_STREAM_IDLE_TIMEOUT_MS;
diff --git a/packages/agent-runtime/src/provider-retry.ts b/packages/agent-runtime/src/provider-retry.ts
index bb13aa0b1..cbddc35d0 100644
--- a/packages/agent-runtime/src/provider-retry.ts
+++ b/packages/agent-runtime/src/provider-retry.ts
@@ -123,6 +123,82 @@ export function withoutDerivedOutputLimit(
};
}
+/**
+ * Output ceilings providers state on a 400. These are not context overflows:
+ * the prompt fit, and the catalog's `max_tokens` is above that model's
+ * completion cap (a fine-tune, a proxy, or a stale catalog entry).
+ *
+ * - OpenAI: "max_tokens is too large: 16384. This model supports at most 4096 completion tokens"
+ * - Anthropic: "max_tokens: 65537 > 64000, which is the maximum allowed number of output tokens"
+ * - Anthropic-compatible proxies: "expected a value <= 32768, but got 64000 instead"
+ */
+const OUTPUT_TOKEN_CEILING_PATTERNS = [
+ /max_(?:completion_|output_)?tokens is too large:[\s\S]{0,240}?at most (\d[\d,]*) completion tokens/i,
+ /max_tokens:\s*\d[\d,]*\s*>\s*(\d[\d,]*)\s*,\s*which is the maximum allowed number of\s+output tokens/i,
+ /max_tokens[\s\S]{0,180}?expected a value <=\s*(\d[\d,]*)/i,
+];
+
+/** The completion cap named in `message`, when it is one of the shapes above. */
+export function outputTokenCeiling(message: string): number | undefined {
+ for (const pattern of OUTPUT_TOKEN_CEILING_PATTERNS) {
+ const match = message.match(pattern);
+ const raw = match?.[1];
+ if (raw === undefined) continue;
+ const value = Number(raw.replaceAll(",", ""));
+ if (Number.isSafeInteger(value) && value > 0) return value;
+ }
+ return undefined;
+}
+
+/**
+ * A terminal or status-less bad request that names an output ceiling. Credit
+ * exhaustion and context overflow use other codes, so they cannot take this
+ * repair. A 5xx that merely mentions `max_tokens` stays on the transient path.
+ */
+export function isOutputLimitRejection(error: ClassifiedAgentError): boolean {
+ if (error.code !== "PROVIDER_ERROR") return false;
+ if (outputTokenCeiling(error.message) === undefined) return false;
+ const providerStatus = error.details?.providerStatus;
+ return (
+ providerStatus === undefined ||
+ providerStatus === 400 ||
+ providerStatus === 422
+ );
+}
+
+/**
+ * Lower output-limit fields that are above `ceiling`. Absent fields stay
+ * absent — Anthropic rejects a request that omits `max_tokens` — and a value
+ * already within the ceiling is left alone.
+ */
+export function clampOutputLimitFields(payload: unknown, ceiling: number): unknown {
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
+ return payload;
+ }
+ const next = { ...(payload as Record<string, unknown>) };
+ for (const field of OUTPUT_LIMIT_FIELDS) {
+ const value = next[field];
+ if (typeof value === "number" && Number.isFinite(value) && value > ceiling) {
+ next[field] = ceiling;
+ }
+ }
+ return next;
+}
+
+/** One repair attempt that clamps the derived output limit to `ceiling`. */
+export function withClampedOutputLimit(
+ options: SimpleStreamOptions,
+ ceiling: number,
+): SimpleStreamOptions {
+ return {
+ ...options,
+ onPayload: async (payload, model) => {
+ const rewritten = await options.onPayload?.(payload, model);
+ return clampOutputLimitFields(rewritten ?? payload, ceiling);
+ },
+ };
+}
+
export type ProviderResponseSnapshot = {
status: number;
headers: Record<string, string>;
@@ -433,14 +509,21 @@ export function createProviderRetryStream(
const sleep = controller.sleep ?? delayWithAbort;
void (async () => {
- // One repair per logical turn: after an opaque 400/422 the next attempt
- // drops the derived output limit. Repairing never consumes the shared
- // transient budget, and a second opaque failure surfaces untouched.
+ // One repair per logical turn. An opaque 400/422 drops the derived output
+ // limit; a body that names a completion ceiling clamps it instead.
+ // Repairing never consumes the shared transient budget, and a second
+ // failure of the same kind surfaces untouched.
let limitRepairTried = false;
+ let outputCeiling: number | undefined;
for (;;) {
if (options.signal?.aborted) throw requestAbortedError();
+ const requestOptions = !limitRepairTried
+ ? options
+ : outputCeiling !== undefined
+ ? withClampedOutputLimit(options, outputCeiling)
+ : withoutDerivedOutputLimit(options);
const inner = createStream({
- ...(limitRepairTried ? withoutDerivedOutputLimit(options) : options),
+ ...requestOptions,
maxRetries: 0,
});
let sawStart = false;
@@ -468,6 +551,12 @@ export function createProviderRetryStream(
opaqueLimitRejection = error;
break;
}
+ const ceiling = !limitRepairTried ? outputTokenCeiling(error.message) : undefined;
+ if (ceiling !== undefined && isOutputLimitRejection(error)) {
+ outputCeiling = ceiling;
+ opaqueLimitRejection = error;
+ break;
+ }
const attempt = error.details?.origin === "local"
? undefined : controller.claim(error, "request");
if (attempt !== undefined) {