diff --git a/docs-site/src/content/docs/es/guides/providers.md b/docs-site/src/content/docs/es/guides/providers.md
index 7910734110f..89555fafcbd 100644
--- a/docs-site/src/content/docs/es/guides/providers.md
+++ b/docs-site/src/content/docs/es/guides/providers.md
@@ -7,6 +7,12 @@ Un **proveedor** es un punto final de LLM ascendente más cómo llegar a él: un
La vista general del proveedor del panel separa los detalles de conexión, el uso de la cuenta y las notas editables. Las notas aparecen una vez, debajo de las secciones de conexión y autenticación. Los ajustes preestablecidos de patrocinador compatibles también muestran una breve introducción, una etiqueta de patrocinador y enlaces al sitio o consola del proveedor. Estos enlaces conservan los parámetros de referencia del preset. La información del patrocinador se muestra solo cuando el nombre del proveedor configurado, el adaptador y el punto final coinciden con el ajuste preestablecido; nunca cambia el enrutamiento, la selección de la cuenta o los valores predeterminados.
+
+
+## Diagnósticos de rechazo del esfuerzo de razonamiento
+
+Los reintentos al mismo proveedor y modelo con un esfuerzo menor, y el aprendizaje de niveles no admitidos, usan un diagnóstico de error completo de hasta 1.024 unidades de código UTF-16, incluido cualquier texto envolvente. Un diagnóstico mayor no autoriza estos reintentos ni el aprendizaje a partir de su prefijo. El cuerpo original sigue disponible para el manejo habitual de errores, incluida la conmutación ordinaria de Combo; se mantienen los límites existentes de visualización de errores del cliente. Un error legítimo pero demasiado largo tampoco activa la reducción automática del esfuerzo ni actualiza los niveles aprendidos. Los diagnósticos breves como `cannot use parameter 'reasoning_effort'` siguen identificando el esfuerzo; un campo ajeno real sigue bloqueando el reintento y el aprendizaje.
+
## Modos de cuenta OpenAI
diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md
index 2b4408fa77c..8d1483f6d9a 100644
--- a/docs-site/src/content/docs/es/reference/configuration/providers.md
+++ b/docs-site/src/content/docs/es/reference/configuration/providers.md
@@ -7,6 +7,12 @@ description: "Entradas de proveedores, autenticación, puntos finales, catálogo
Un proveedor le dice a opencodex dónde vive un modelo, qué adaptador de cable habla y cómo se autentican las solicitudes.
+
+
+## Diagnósticos de rechazo del esfuerzo de razonamiento
+
+Consulte los [límites de los diagnósticos de esfuerzo de razonamiento](/es/guides/providers/#reasoning-effort-rejection-diagnostics) antes de depender de la reducción automática del esfuerzo o del aprendizaje de niveles admitidos.
+
## DeepSeek: tokens y bytes de imágenes
diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md
index 5ba44ed6250..5ca453a2b1c 100644
--- a/docs-site/src/content/docs/guides/providers.md
+++ b/docs-site/src/content/docs/guides/providers.md
@@ -16,6 +16,17 @@ account selection or defaults.
While a provider login is in progress, its Accounts panel offers **Cancel** once sign-in
instructions appear.
+## Reasoning-effort rejection diagnostics
+
+Automatic retries of the same provider and model at a lower effort, and learned unsupported
+efforts, use a complete upstream error diagnostic of at most 1,024 UTF-16 code units, including
+any wrapper text. Larger diagnostics cannot authorize this retry or learning from their prefix.
+The original error body remains available to normal handling, including ordinary Combo failover;
+existing client error-display limits still apply. A long but legitimate effort error therefore
+does not trigger automatic effort repair or update the learned effort ladder. Short diagnostics such as
+`cannot use parameter 'reasoning_effort'` still identify effort; an actual unrelated field
+continues to block this retry and learning.
+
## OpenAI account modes
| Provider id | Use | Credential/account rule |
diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md
index 4e4ffa0569d..19a2b194de2 100644
--- a/docs-site/src/content/docs/ko/reference/configuration/providers.md
+++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md
@@ -5,6 +5,12 @@ description: 공급자 항목, 인증, 엔드포인트, 모델 카탈로그, 할
공급자는 opencodex에 모델의 위치, 사용하는 와이어 어댑터, 요청 인증 방식을 알려줍니다.
+
+
+## 추론 수준 거절 진단
+
+같은 공급자·모델로 추론 수준을 낮춰 다시 보내는 복구와 미지원 수준 학습은 래퍼를 포함한 전체 오류 진단이 UTF-16 코드 단위 1,024개 이하일 때만 수행합니다. 이 한도를 넘으면 앞부분만 근거로 재시도·학습하지 않습니다. 일반 Combo 전환을 포함한 기존 오류 처리에 원문을 그대로 전달하며, 기존 클라이언트 오류 표시 길이 제한은 계속 적용됩니다. 정상적인 오류라도 길이가 한도를 넘으면 자동 하향·학습 대상이 되지 않습니다. `cannot use parameter 'reasoning_effort'` 같은 짧은 진단은 추론 수준 거절로 인식하며, 실제로 다른 필드를 지목한 오류는 계속 재시도·학습을 막습니다.
+
## Mistral 요청당 이미지 수
Mistral 요청의 이미지 수 제한과 `mistralMaxImages` 설정은 [영문 기준 문서](/reference/configuration/providers/#mistral-images-per-request)를 참조하세요. 제한기에 도달한 `image_url` 항목의 이미지 참조가 누락되거나 비어 있거나 문자열이 아니면 전송용 사본에서 텍스트로 대체되며 이미지 한도를 소비하지 않습니다. 번역되는 Responses 요청에서 사용 가능한 URL과 파일 ID가 모두 없는 `input_image`는 파서가 제외합니다. 메시지나 도구 출력 블록 안에서 비어 있지 않은 `file_id`만 있고 비어 있지 않은 `image_url`이 없으면 미디어 가드가 Mistral 전송 전에 요청을 거절합니다. 가드가 검사하지 않는 재생된 `agent_message` 내부에서는 파서가 대신 `[image: ]` 텍스트 마커를 내보내며 일반 텍스트로 전송되고 이미지 한도를 소비하지 않습니다. 제한기는 `image_url` 또는 `image_url.url`의 비어 있지 않은 문자열만 계산하고 URL 문법이나 접근 가능성은 검증하지 않습니다. 다른 대상의 동작은 바뀌지 않습니다.
diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md
index 5934b559866..45c442f8a8b 100644
--- a/docs-site/src/content/docs/reference/configuration/providers.md
+++ b/docs-site/src/content/docs/reference/configuration/providers.md
@@ -1827,6 +1827,10 @@ their previous behavior. See the
[ordering migration note](/guides/model-ordering/#migration-note-native-ids-in-existing-orders).
`modelDisplayNames` on a provider controls readable labels without changing wire ids.
+## Reasoning-effort rejection diagnostics
+
+See the [reasoning-effort diagnostic limits](/guides/providers/#reasoning-effort-rejection-diagnostics) before relying on automatic effort repair or learned effort support.
+
## Routed agent messages
With the [`openai-responses` adapter](/reference/adapters/#openai-responses), Codex
diff --git a/src/combos/failover.ts b/src/combos/failover.ts
index a687b4b821e..cda376af207 100644
--- a/src/combos/failover.ts
+++ b/src/combos/failover.ts
@@ -643,7 +643,7 @@ function isExactInvalidReasoningEffortRefusal(status: number, message: string, c
if (code !== undefined && code !== null && typeof code !== "string") return false;
const outerCode = normalizedFailureCode(code);
if (!EXACT_EFFORT_COMPATIBLE_CODES.has(outerCode)) return false;
- if (isHardPolicyOrOriginRefusal(message) || hasConflictingReasoningEffortCode(message)) return false;
+ if (isHardPolicyOrOriginRefusal(message) || hasConflictingReasoningEffortCode(message, 16_384)) return false;
let text = message.trim();
for (let depth = 0; depth < 3; depth += 1) {
if (text.startsWith("Provider error 400: ")) text = text.slice("Provider error 400: ".length).trim();
diff --git a/src/providers/reasoning-metadata.ts b/src/providers/reasoning-metadata.ts
index ba4e281b962..1dbd7153d9e 100644
--- a/src/providers/reasoning-metadata.ts
+++ b/src/providers/reasoning-metadata.ts
@@ -443,6 +443,12 @@ const REJECTION_LANGUAGE = /unsupported|not supported|does not support|invalid|n
* every 400 that mentions effort as a refusal of it.
*/
const REJECTION_WINDOW = 48;
+/**
+ * Optional effort repair only analyzes a complete, short diagnostic (UTF-16 code units).
+ * Longer input is conflicting evidence, never a prefix to retry or learn from. This bounds
+ * the remaining heuristic scans; it does not truncate the upstream response body.
+ */
+const MAX_REASONING_DIAGNOSTIC_CHARS = 1_024;
/**
* The `invalid_request_error` type tag rides along on essentially every 400 an OpenAI-shaped
@@ -951,7 +957,7 @@ function diagnosticTextNamesOtherParameter(text: string, authoritativeEffortSubj
const s = text.replace(GENERIC_ERROR_TYPE, " ");
if (authoritativeEffortSubject) return diagnosticTextNamesConcreteOtherField(s);
- const paramPattern = /\b(?:parameter|param|argument|arg|field|property)\s*(?:[:=]\s*['"`]?|['"`]|\s+)['"`]?([a-zA-Z0-9_\-\.]+)['"`]?/gi;
+ const paramPattern = /\b(?:parameter|param|argument|arg|field|property)(?:\s*[:=]\s*['"`]?|\s*['"`]|\s+)['"`]?([a-zA-Z0-9_\-\.]+)['"`]?/gi;
for (let m = paramPattern.exec(s); m; m = paramPattern.exec(s)) {
const tokenIndex = tokenStartIndex(m, m[1], false);
if (isCompetingParameterToken(s, tokenIndex, m[1])) return true;
@@ -960,6 +966,11 @@ function diagnosticTextNamesOtherParameter(text: string, authoritativeEffortSubj
const prefixParamPattern = /\b['"`]?([a-zA-Z0-9_\-\.]+)['"`]?\s+(?:parameter|param|argument|arg|field|property)\b/gi;
for (let m = prefixParamPattern.exec(s); m; m = prefixParamPattern.exec(s)) {
const tokenIndex = tokenStartIndex(m, m[1], true);
+ const beforeToken = s.slice(0, tokenIndex);
+ // In "cannot use parameter 'x'", use introduces the label, not a field named use.
+ // Quoted field names and verbs outside that diagnostic phrase remain competing subjects.
+ if (!/['"`]$/.test(beforeToken) && (m[1].toLowerCase() === "missing"
+ || (/^(?:specify|use|set|pass|provide)$/i.test(m[1]) && /\bcannot\s+$/i.test(beforeToken)))) continue;
if (isCompetingParameterToken(s, tokenIndex, m[1])) return true;
}
@@ -984,7 +995,7 @@ function diagnosticTextNamesOtherParameter(text: string, authoritativeEffortSubj
}
const rejectionExtra =
- /\b(?:unexpected|missing|cannot\s+(?:specify|use|set|pass|provide))\s+(?:field|param|parameter|argument|property)?\s*['"`]?([a-zA-Z0-9_\-\.]+)['"`]?/gi;
+ /\b(?:unexpected|missing|cannot\s+(?:specify|use|set|pass|provide))\s+(?:(?:field|param|parameter|argument|property)\b\s*)?['"`]?([a-zA-Z0-9_\-\.]+)['"`]?/gi;
for (let m = rejectionExtra.exec(s); m; m = rejectionExtra.exec(s)) {
const tokenIndex = tokenStartIndex(m, m[1], false);
if (isCompetingParameterToken(s, tokenIndex, m[1])) return true;
@@ -1007,6 +1018,7 @@ function diagnosticTextNamesOtherParameter(text: string, authoritativeEffortSubj
function isConflictingDiagnosticProse(str: string | undefined, authoritativeEffortSubject = false): boolean {
if (!str) return false;
+ if (str.length > MAX_REASONING_DIAGNOSTIC_CHARS) return true;
const s = str.trim();
if (!s) return false;
if (
@@ -1054,8 +1066,14 @@ function isHttpStatusNumber(value: unknown): boolean {
* (e.g. reasoning_effort at root with an inner error identifying temperature) so they stay terminal
* or proceed to combo failover without false reasoning-effort learning or same-target ladder retries (#8173).
*/
-export function hasConflictingReasoningEffortCode(text: string | undefined): boolean {
+export function hasConflictingReasoningEffortCode(
+ text: string | undefined,
+ maxEnvelopeChars: 1_024 | 16_384 = MAX_REASONING_DIAGNOSTIC_CHARS,
+): boolean {
if (!text) return false;
+ // Exact-refusal failover may inspect a larger complete envelope; prose heuristics
+ // retain the short limit even when unrelated metadata makes that envelope larger.
+ if (text.length > maxEnvelopeChars) return true;
if (isIncompleteStructuredWrapper(text)) return true;
let unescaped = text.trim();
for (let d = 0; d < 3; d += 1) {
@@ -1333,7 +1351,7 @@ function diagnosticRecordBlamesReasoningEffort(rec: Record, dep
* (such as temperature or max_tokens errors) as effort refusals (#8173).
*/
export function isReasoningEffortRejection(text: string | undefined, depth = 0): boolean {
- if (!text || depth > 4) return false;
+ if (!text || text.length > MAX_REASONING_DIAGNOSTIC_CHARS || depth > 4) return false;
if (isHardPolicyOrOriginRefusal(text)) return false;
if (hasConflictingReasoningEffortCode(text)) return false;
diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md
index 1c312121cdc..ecfb36582b0 100644
--- a/structure/providers-and-adapters.md
+++ b/structure/providers-and-adapters.md
@@ -588,7 +588,7 @@ Account-row projection is loaded with `import()` after each account probe in `sr
## Combo model refusal evidence
-`src/combos/failover.ts` recognizes a bounded, exact HTTP 400 plan/model refusal, not credential or entitlement evidence. It also permits OpenRouter's exact opaque numeric-400 wrapper (`Provider returned error` with `metadata.raw: "ERROR"`, without `type`) to try another combo target. Typed uncoded 400s, malformed `response_format` schema errors and other terminal `invalid_request_error` cases stop and cool the target. An envelope root that states a terminal code of its own stops too (`origin_rejected`, `content_policy_violation`, `context_length_exceeded`, `invalid_request_error`, the shared terminal-refusal set and the non-replayable post-send codes, not a blanket inequality); a root that states only an ordinary hop signal adds no verdict, and an empty code counts as absent. The root code and the record it wraps are both consulted, so a hop needs each to authorize one and a root hard stop is never hidden behind a retryable nested record. Request-local target incompatibilities recognized by `isRequestLocalTargetIncompatibility` and `isResponseFormatCapabilityRefusal` may advance without cooling. So may a provider or gateway moderation verdict on HTTP 400/422 (`isProviderModerationRefusal`), granted on structured evidence only and only for the known shape of a refusal: a `moderation_refusal` or `content_filter` code (the caller's, or a `code`/`error_code` in the body; a `type` or an incomplete `reason` of `content_filter` alone is a model's own output filter and stays terminal) and nothing else. The walk (`moderationVerdictFields`) admits a closed set of fields: verdict codes and types on a short compatible list, a stated status of 400/422 (or a Responses `failed`/`incomplete` state), a `param` naming the prompt or input (or an AI SDK error object read as a record), bare identifiers (`id`, `request_id`, `model`, `name`...), `innererror`, Azure's per-category filter results in their own shape only (category objects of flags and numbers, a `severity` of safe/low/medium/high, bare `id`/`url`/`license` tokens and compatible codes; any other text, or a key naming a state, status, error or message, stops), and a gateway's `providerMetadata` holding plain routing tokens under keys that name no state. Any other field stops. Prose (`message`, a string `error`, plain text with a caller's code) must be known refusal copy as a whole, after whitespace is collapsed: one verdict sentence (OpenAI's "The input was refused by moderation", Azure's content-management sentence, a bare "filtered"...) optionally followed by the category list, the advice to change the prompt and retry, and Azure's documentation pointer; anything else, an account, model, parameter or billing problem in any phrasing, keeps dev's decision. A Responses event's own `response.*` type is read as the carrier, whose response object is read without the fields that echo the caller's request (`instructions`, `tools`, `text`, `reasoning`, `input`, `output`, `usage`...); its `metadata` must be empty. Prose alone never hops (owner decision on #8428). It never outranks a stop: an envelope root verdict code, a hard-refusal token in any spelling (JSON-escaped, camelCase, or with hyphens, dots, slashes or spaces for underscores), safety or terminal-refusal copy, a malformed `response_format` diagnostic, subscription-gate wording, or any text the shared `classifyError` files more specifically than a generic invalid request keeps the terminal decision and its cooldown, and quota, billing or account-state evidence (including such wording beside a moderation code) still cools the provider. The verdict needs the whole body: `consumeComboFailure`, the responses stream preflight, the Messages native preflight and `policy-fallback.ts` judge the complete bounded body or event and pass `providerModerationRefusal`; a preflight that rebuilds a slim envelope attaches the whole event as combo failure evidence whenever either reads as a moderation verdict, and an event that states a non-400/422 status of its own is never a moderation refusal; and without it a classification text of 500 characters or more (possibly cut) never hops.
+`src/combos/failover.ts` recognizes a bounded, exact HTTP 400 plan/model refusal, not credential or entitlement evidence. It also permits OpenRouter's exact opaque numeric-400 wrapper (`Provider returned error` with `metadata.raw: "ERROR"`, without `type`) to try another combo target. Typed uncoded 400s, malformed `response_format` schema errors and other terminal `invalid_request_error` cases stop and cool the target. An envelope root that states a terminal code of its own stops too (`origin_rejected`, `content_policy_violation`, `context_length_exceeded`, `invalid_request_error`, the shared terminal-refusal set and the non-replayable post-send codes, not a blanket inequality); a root that states only an ordinary hop signal adds no verdict, and an empty code counts as absent. The root code and the record it wraps are both consulted, so a hop needs each to authorize one and a root hard stop is never hidden behind a retryable nested record. Request-local target incompatibilities recognized by `isRequestLocalTargetIncompatibility` and `isResponseFormatCapabilityRefusal` may advance without cooling. So may a provider or gateway moderation verdict on HTTP 400/422 (`isProviderModerationRefusal`), granted on structured evidence only and only for the known shape of a refusal: a `moderation_refusal` or `content_filter` code (the caller's, or a `code`/`error_code` in the body; a `type` or an incomplete `reason` of `content_filter` alone is a model's own output filter and stays terminal) and nothing else. The walk (`moderationVerdictFields`) admits a closed set of fields: verdict codes and types on a short compatible list, a stated status of 400/422 (or a Responses `failed`/`incomplete` state), a `param` naming the prompt or input (or an AI SDK error object read as a record), bare identifiers (`id`, `request_id`, `model`, `name`...), `innererror`, Azure's per-category filter results in their own shape only (category objects of flags and numbers, a `severity` of safe/low/medium/high, bare `id`/`url`/`license` tokens and compatible codes; any other text, or a key naming a state, status, error or message, stops), and a gateway's `providerMetadata` holding plain routing tokens under keys that name no state. Any other field stops. Prose (`message`, a string `error`, plain text with a caller's code) must be known refusal copy as a whole, after whitespace is collapsed: one verdict sentence (OpenAI's "The input was refused by moderation", Azure's content-management sentence, a bare "filtered"...) optionally followed by the category list, the advice to change the prompt and retry, and Azure's documentation pointer; anything else, an account, model, parameter or billing problem in any phrasing, keeps dev's decision. A Responses event's own `response.*` type is read as the carrier, whose response object is read without the fields that echo the caller's request (`instructions`, `tools`, `text`, `reasoning`, `input`, `output`, `usage`...); its `metadata` must be empty. Prose alone never hops (owner decision on #8428). It never outranks a stop: an envelope root verdict code, a hard-refusal token in any spelling (JSON-escaped, camelCase, or with hyphens, dots, slashes or spaces for underscores), safety or terminal-refusal copy, a malformed `response_format` diagnostic, subscription-gate wording, or any text the shared `classifyError` files more specifically than a generic invalid request keeps the terminal decision and its cooldown, and quota, billing or account-state evidence (including such wording beside a moderation code) still cools the provider. The verdict needs the whole body: `consumeComboFailure`, the responses stream preflight, the Messages native preflight and `policy-fallback.ts` judge the complete bounded body or event and pass `providerModerationRefusal`; a preflight that rebuilds a slim envelope attaches the whole event as combo failure evidence whenever either reads as a moderation verdict, and an event that states a non-400/422 status of its own is never a moderation refusal; and without it a classification text of 500 characters or more (possibly cut) never hops. Effort-repair inference in `src/providers/reasoning-metadata.ts` accepts at most 1,024 UTF-16 code units across the complete diagnostic. The repair classifier and the conflict check's default budget reject longer input before parsing or prose scans, without truncating the error or authorizing downgrade or learning from a prefix. Exact-refusal Combo and policy fallback retain their 16,384-unit complete-envelope budget for unrelated metadata, while each diagnostic prose scan remains capped at 1,024 units; conflicting diagnostic fields anywhere in the accepted envelope still veto the hop. Separator grammar avoids overlapping whitespace runs; optional field labels match whole words, and unquoted diagnostic verbs such as "cannot use parameter" are not competing field names. Quoted or separately named fields still conflict, and the remaining heuristics have a finite input bound.
`src/server/responses/core-combo-failure.ts` captures its finite classification before display truncation;
`src/server/responses/combo-stream-preflight.ts` preserves it before rebuilding terminal SSE errors.
`src/server/responses/core-options.ts` carries the value to the combo decision. An inspected non-match
diff --git a/tests/codex-integration/reasoning-metadata.test.ts b/tests/codex-integration/reasoning-metadata.test.ts
index f8d660404db..ba25cda1bc1 100644
--- a/tests/codex-integration/reasoning-metadata.test.ts
+++ b/tests/codex-integration/reasoning-metadata.test.ts
@@ -385,6 +385,113 @@ describe("learned rung refusals", () => {
});
});
+describe("reasoning diagnostic analysis budget", () => {
+ const limit = 1024;
+ const refusal = JSON.stringify({ error: { param: "reasoning_effort", message: "Invalid reasoning effort." } });
+
+ test("accepts a complete refusal at the limit, but not one extra character", async () => {
+ const { metadata } = await load();
+ const exact = refusal.padEnd(limit, " ");
+ expect(exact.length).toBe(limit);
+ expect(metadata.hasConflictingReasoningEffortCode(exact)).toBe(false);
+ expect(metadata.isReasoningEffortRejection(exact)).toBe(true);
+ expect(metadata.hasConflictingReasoningEffortCode(exact + " ")).toBe(true);
+ expect(metadata.isReasoningEffortRejection(exact + " ")).toBe(false);
+ });
+
+ test("exact-refusal failover allows long metadata without widening prose or repair budgets", async () => {
+ const { metadata } = await load();
+ const error = { param: "reasoning_effort", message: "Invalid reasoning effort." };
+ const longMetadata = JSON.stringify({ request_id: "x".repeat(1100), error });
+ expect(metadata.hasConflictingReasoningEffortCode(longMetadata, 16_384)).toBe(false);
+ expect(metadata.hasConflictingReasoningEffortCode(longMetadata)).toBe(true);
+ expect(metadata.isReasoningEffortRejection(longMetadata)).toBe(false);
+ expect(metadata.hasConflictingReasoningEffortCode(longMetadata.padEnd(16_385, " "), 16_384)).toBe(true);
+ for (const message of ["parameter" + " ".repeat(1100) + "!", "a-".repeat(550) + "!"]) {
+ const hostile = JSON.stringify({ error: { ...error, message } });
+ expect(metadata.hasConflictingReasoningEffortCode(hostile, 16_384)).toBe(true);
+ }
+ const conflicting = JSON.stringify({ request_id: "x".repeat(1100), error,
+ details: { param: "temperature", message: "Invalid temperature." } });
+ expect(metadata.hasConflictingReasoningEffortCode(conflicting, 16_384)).toBe(true);
+ });
+
+ test.each([
+ ["parameter whitespace", "parameter" + " ".repeat(1024) + "!"],
+ ["optional field whitespace", "missing" + " ".repeat(1024) + "!"],
+ ["hyphenated token", "a-".repeat(512) + "!"],
+ ["dotted token", "a.".repeat(512) + "!"],
+ ])("declines an oversized %s diagnostic", async (_name, message) => {
+ const { metadata } = await load();
+ const text = JSON.stringify({ error: { message } });
+ expect(text.length).toBeGreaterThan(limit);
+ expect(metadata.hasConflictingReasoningEffortCode(text)).toBe(true);
+ expect(metadata.isReasoningEffortRejection(text)).toBe(false);
+ });
+
+ test("counts the entire envelope and never learns from an accepted prefix", async () => {
+ const { metadata } = await load();
+ const provider = { ...ZEN_GO, reasoningEfforts: ["low", "high", "max"] } as OcxProviderConfig;
+ const conflictingTail = JSON.stringify({ error: { details: { param: "temperature", message: "Invalid temperature." } } });
+ const manySmallFields = JSON.stringify({ error: { param: "reasoning_effort", message: "Invalid reasoning effort.",
+ details: Array.from({ length: 20 }, () => ({ message: "ordinary diagnostic note ".repeat(3) })) } });
+ const inputs = [refusal.padEnd(limit, " ") + conflictingTail, manySmallFields, refusal.padEnd(limit + 1, " ")];
+ try {
+ for (const rejectionText of inputs) {
+ expect(rejectionText.length).toBeGreaterThan(limit);
+ expect(metadata.hasConflictingReasoningEffortCode(rejectionText)).toBe(true);
+ expect(metadata.isReasoningEffortRejection(rejectionText)).toBe(false);
+ expect(metadata.planReasoningEffortDowngrade({ provider, modelId: MUSE_SPARK, requested: "max", rejectionText })).toBeUndefined();
+ expect(metadata.isReasoningEffortLearnedUnsupported(provider, MUSE_SPARK, "max")).toBe(false);
+ }
+ } finally {
+ metadata.resetReasoningMetadataCachesForTests();
+ }
+ });
+
+ test.each([
+ ["cannot use parameter 'reasoning_effort'", false],
+ ["cannot use parameter'reasoning_effort'", false],
+ ["missing parameter `reasoning_effort`", false],
+ ['cannot set param"reasoning.effort"', false],
+ ["unexpected field`reasoning_effort`", false],
+ ["cannot use parameter 'sampling_knob'", true],
+ ["cannot use field`sampling_knob`", true],
+ ["cannot use parametersampling_knob", true],
+ ["the use parameter is invalid", true],
+ ["cannot 'use' parameter", true],
+ ["'missing' parameter is invalid", true],
+ ] as const)("matches complete diagnostic labels: %s", async (diagnostic, conflicting) => {
+ const { metadata } = await load();
+ const message = `Invalid reasoning effort. ${diagnostic}`;
+ for (const text of [message, JSON.stringify({ error: { message } })]) {
+ expect(metadata.hasConflictingReasoningEffortCode(text)).toBe(conflicting);
+ expect(metadata.isReasoningEffortRejection(text)).toBe(!conflicting);
+ }
+ });
+
+ test("keeps separators and quoted field names distinct from effort refusals", async () => {
+ const { metadata } = await load();
+ const forms = [
+ ["Unsupported parameter: 'reasoning_effort'", false],
+ ["Unsupported parameter: 'sampling.knob'", true],
+ ['Unsupported param = "sampling_knob"', true],
+ ["Unsupported argument\tsampling_knob", true],
+ ["Unsupported arg\nsampling_knob", true],
+ ["Unsupported field`sampling_knob`", true],
+ ['Unsupported property \'"custom-flag"', true],
+ ["missing\t'sampling_knob'", true],
+ ["unexpected\tfield 'sampling_knob'", true],
+ ["cannot use\tparameter 'sampling_knob'", true],
+ ] as const;
+ for (const [diagnostic, conflicting] of forms) {
+ const text = JSON.stringify({ error: { message: `Invalid reasoning effort. ${diagnostic}` } });
+ expect(metadata.hasConflictingReasoningEffortCode(text)).toBe(conflicting);
+ expect(metadata.isReasoningEffortRejection(text)).toBe(!conflicting);
+ }
+ });
+});
+
describe("destination resolution", () => {
const ZEN = { ...ZEN_GO, baseUrl: "https://opencode.ai/zen/v1" } as OcxProviderConfig;
const MODEL = { [MUSE_SPARK]: { reasoning: true, options: [{ type: "effort", values: ["low", "high"] }] } };
diff --git a/tests/responses/responses-reasoning-effort-diagnostics.test.ts b/tests/responses/responses-reasoning-effort-diagnostics.test.ts
index 85dff429c41..5f5d0d292dd 100644
--- a/tests/responses/responses-reasoning-effort-diagnostics.test.ts
+++ b/tests/responses/responses-reasoning-effort-diagnostics.test.ts
@@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { handleResponses } from "../../src/server/responses/core";
+import { handleResponses as dispatchResponses } from "../../src/server/responses/core";
+import { refusedReasoningEffortDowngrade } from "../../src/server/responses/core-opaque-recovery";
import { clearComboSelectionState, clearComboTargetCooldowns } from "../../src/combos";
import {
hasConflictingReasoningEffortCode,
@@ -14,6 +15,11 @@ import type { RequestLogContext } from "../../src/server/request-log";
import type { OcxConfig } from "../../src/types";
import { chatSuccess } from "../helpers/combo-failover-upstream";
import { acquireOwnedSpendHome } from "../helpers/owned-spend-home";
+import { withStubbedProviderFetch } from "../helpers/catalog-provider-fetch";
+
+// These configs contain only synthetic providers; use their fetch stubs on the pinned transport too.
+const handleResponses: typeof dispatchResponses = (request, config, ...args) =>
+ dispatchResponses(request, withStubbedProviderFetch(config), ...args);
/**
* Diagnostic envelope and boundary tests for reasoning effort refusals (#8173).
@@ -272,6 +278,41 @@ afterEach(() => {
});
describe("reasoning effort diagnostic envelopes and boundaries", () => {
+ test.each(["openai-chat", "openai-responses"] as const)("%s keeps oversized effort errors without replay or learning", async adapter => {
+ writeSnapshot(["low", "high", "max"]);
+ const message = "Invalid reasoning effort. " + "x".repeat(1024) + " ORIGINAL-ERROR-TAIL";
+ const body = JSON.stringify({ error: { param: "reasoning_effort", message } });
+ const outbound: Array> = [];
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ outbound.push(JSON.parse(String(init?.body)) as Record);
+ if (outbound.length > 1) return adapter === "openai-chat" ? chatSuccess("unexpected replay")
+ : Response.json({ id: "unexpected-replay", object: "response", status: "completed", model: MODEL, output: [] });
+ return new Response(body, { status: 400, headers: { "content-type": "application/json" } });
+ }) as typeof fetch;
+ const cfg = adapter === "openai-chat" ? config() : passthroughConfig();
+ const response = await handleResponses(request(), cfg, { model: "", provider: "" });
+ const text = await response.text();
+ expect(outbound, `${response.status}: ${text}`).toHaveLength(1);
+ expect(effortOf(outbound[0])).toBe("max");
+ expect(response.status).toBe(400);
+ expect(text).toContain("Invalid reasoning effort.");
+ if (adapter === "openai-responses") expect(text).toContain(message);
+ expect(isReasoningEffortLearnedUnsupported(cfg.providers.first, MODEL, "max")).toBe(false);
+ });
+
+ test("oversized diagnostics leave the original response readable when no effort was requested", async () => {
+ const body = JSON.stringify({ error: { message: "parameter" + " ".repeat(1024) + "!" } });
+ const upstream = new Response(body, { status: 400 });
+ const guard = { attempted: false };
+ const cfg = config();
+ globalThis.fetch = (() => { throw new Error("unexpected network in diagnostic fixture"); }) as typeof fetch;
+ expect(await refusedReasoningEffortDowngrade(upstream, new AbortController().signal, guard, false,
+ { provider: cfg.providers.first, modelId: MODEL, requested: undefined })).toBeUndefined();
+ expect(guard.attempted).toBe(false);
+ expect(await upstream.text()).toBe(body);
+ expect(isReasoningEffortLearnedUnsupported(cfg.providers.first, MODEL, "max")).toBe(false);
+ });
+
test("hasConflictingReasoningEffortCode unit checks", () => {
expect(hasConflictingReasoningEffortCode(SERIALIZED_WRAPPER_CONFLICTING_REFUSAL)).toBe(true);
expect(hasConflictingReasoningEffortCode(UNEXHAUSTED_QUEUE_CANDIDATES_REFUSAL)).toBe(true);
diff --git a/tests/responses/responses-reasoning-effort-downgrade.test.ts b/tests/responses/responses-reasoning-effort-downgrade.test.ts
index 04fe9a87f6d..cc2b328faf8 100644
--- a/tests/responses/responses-reasoning-effort-downgrade.test.ts
+++ b/tests/responses/responses-reasoning-effort-downgrade.test.ts
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { handleResponses } from "../../src/server/responses/core";
+import { handleResponses as dispatchResponses } from "../../src/server/responses/core";
import { withRawBodyReasoningEffort } from "../../src/server/responses/core-opaque-recovery";
import { clearComboSelectionState, clearComboTargetCooldowns, isComboTargetInCooldown } from "../../src/combos";
import {
@@ -15,6 +15,11 @@ import type { RequestLogContext } from "../../src/server/request-log";
import type { OcxConfig } from "../../src/types";
import { chatSuccess } from "../helpers/combo-failover-upstream";
import { acquireOwnedSpendHome } from "../helpers/owned-spend-home";
+import { withStubbedProviderFetch } from "../helpers/catalog-provider-fetch";
+
+// These configs contain only synthetic providers; use their fetch stubs on the pinned transport too.
+const handleResponses: typeof dispatchResponses = (request, config, ...args) =>
+ dispatchResponses(request, withStubbedProviderFetch(config), ...args);
/**
* Rejected-rung learning on the request path: a rung the catalog advertises can still be refused
diff --git a/tests/routing/routing-policy-fallback.test.ts b/tests/routing/routing-policy-fallback.test.ts
index af2b721648a..f82f1ec0a1b 100644
--- a/tests/routing/routing-policy-fallback.test.ts
+++ b/tests/routing/routing-policy-fallback.test.ts
@@ -79,6 +79,34 @@ describe("policy candidate fallback", () => {
let previousHome: string | undefined;
beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-policy-fallback-")); process.env.OPENCODEX_HOME = home; });
afterEach(() => { if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; removeTreeWithRetry(home); });
+ test.each(["long request id", "envelope limit", "over limit", "conflicting tail", "hostile diagnostic"] as const)(
+ "exact effort fallback checks the complete bounded envelope: %s", async kind => {
+ const error = { type: "invalid_request_error", param: "reasoning_effort", message: "Invalid reasoning effort." };
+ let body = JSON.stringify({ request_id: "x".repeat(1100), error,
+ ...(kind === "conflicting tail" ? { details: { param: "temperature", message: "Invalid temperature." } } : {}),
+ ...(kind === "hostile diagnostic" ? { details: { message: "parameter" + " ".repeat(1100) + "!" } } : {}),
+ });
+ if (kind === "envelope limit" || kind === "over limit") body = body.padEnd(16_384 + (kind === "over limit" ? 1 : 0), " ");
+ const shouldHop = kind === "long request id" || kind === "envelope limit";
+ const seenModels: string[] = [];
+ const response = await handleResponsesWithPolicyFallback(request(), fixtureConfig(), {}, {}, {
+ runCore: async (req, _config, context, options) => {
+ const parsed = await req.json();
+ options.onRequestBodyParsed?.(parsed);
+ context.routeDecision = policyTrace();
+ seenModels.push(parsed.model);
+ return seenModels.length === 1
+ ? new Response(body, { status: 400, headers: { "content-type": "application/json" } })
+ : Response.json({ status: "completed" });
+ },
+ });
+ expect(body.length).toBeGreaterThan(1024);
+ expect(seenModels).toEqual(shouldHop ? ["policy/daily", "provider-b/model-b"] : ["policy/daily"]);
+ expect(response.status).toBe(shouldHop ? 200 : 400);
+ if (shouldHop) expect(await response.json()).toEqual({ status: "completed" });
+ else expect(await response.text()).toBe(body);
+ },
+ );
test.each([401, 402, 429, "local"] as const)("synthetic failure attribution across candidates (%s)", async outcome => {
clearProviderCacheAffinityForTests();
const lane = "policy-terminal-source";