Skip to content

Commit 2668cb6

Browse files
fix(responses): sanitize Codex user metadata and preserve optional-control failover
1 parent df7dc1b commit 2668cb6

21 files changed

Lines changed: 297 additions & 6 deletions

File tree

‎docs-site/src/content/docs/fr/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,3 +365,9 @@ message de validation.
365365

366366
L’erreur était terminale plutôt que spécifique à la cible. Corriger une entrée invalide, réduire un contexte surdimensionné,
367367
gérer un refus de politique ou corriger l’origine de la demande rejetée. Les combos ne sautent pas dans ces cas-là.
368+
369+
## Compatibilité des paramètres facultatifs
370+
371+
Exception aux erreurs 400 terminales : un rejet structuré de `user` ou une valeur non prise en charge pour `reasoning.effort`/`reasoning_effort` peut faire passer le combo à la cible admissible suivante, sans délai de refroidissement. Le refus de sécurité, l’annulation et une sortie déjà commencée restent non rejouables.
372+
373+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎docs-site/src/content/docs/guides/combos.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,8 @@ Combo failures are divided into **hop** failures and **terminal** failures.
213213
| HTTP 401, 403, 404, 408, 429, or any 5xx | Cool the target and hop to the next eligible target. |
214214
| HTTP 410 with an explicit model end-of-life, retired, deprecated, sunset, decommissioned, or no-longer-available signal | Cool that target and hop. Unrelated 410 responses remain terminal. |
215215
| Classified authentication, subscription, quota, rate-limit, overload, or upstream-server error | Cool the target and hop, even when the status alone is not sufficient. |
216-
| Client cancellation (499), `origin_rejected`, cyber-policy refusal, context overflow, or invalid request | Stop and return the error; another target would not make the request valid. |
216+
| Client cancellation (499), `origin_rejected`, cyber-policy refusal, context overflow, or other invalid request | Stop and return the error; another target would not make the request valid. |
217+
| Structured HTTP 400 rejecting optional `user`, an unsupported reasoning effort, or model-scoped image input | Hop before output commitment without cooling; see optional-control compatibility below. |
217218
| Any other unclassified error | Stop and return the error. |
218219

219220
When `cooldownMs` is unset, a hopped target uses an upstream fallback: 5 seconds for request-rate
@@ -227,8 +228,8 @@ fallback for upstream rate-limit codes `1302`/`1305` → the 60-second default.
227228
`Retry-After: 0` remains an immediate upstream directive rather than being replaced by a configured
228229
cooldown.
229230

230-
The current request never retries the same attempted target. Later requests skip it until its
231-
cooldown expires. A `Retry-After` HTTP-date that is already in the past is also preserved as an
231+
The current request never retries the same attempted target. Later requests skip a cooled target until its
232+
cooldown expires; request-local compatibility rejections do not cool the target. A `Retry-After` HTTP-date that is already in the past is also preserved as an
232233
immediate upstream directive, just like `Retry-After: 0`. Set `waitForCooldownMs` to allow a later
233234
request to wait for the earliest eligible target cooldown, up to that cap on each selection attempt,
234235
and then make one fresh selection. A request may therefore wait up to `hops × waitForCooldownMs`
@@ -254,6 +255,12 @@ another provider, which prevents duplicate text and tool execution. If the pre-o
254255
its safety cap without a terminal or output boundary, OpenCodex also commits the current target
255256
instead of growing memory without a bound.
256257

258+
## Request-local target compatibility
259+
260+
When routing Claude Code to the canonical ChatGPT Codex backend, OpenCodex removes the unsupported top-level `user` metadata field without changing the session/cache key, input messages, tool schemas, or safety identifiers. Public Responses API and noncanonical forward gateways keep that field.
261+
262+
A combo can also advance after an intact HTTP 400 `invalid_request_error` that specifically rejects `user`, reports `unsupported_value` for `reasoning.effort`/`reasoning_effort`, or reports `param: input` with an exact model-scoped `does not support image inputs` rejection. This is a mismatch for that request, not evidence that the target is unhealthy, so it records no cooldown. This compatibility recovery does not silently change `none` into a different effort or broaden this exception to arbitrary invalid requests. Policy refusals, cancellation and already-committed output remain non-replayable. A single-target request still returns an unresolved upstream rejection.
263+
257264
## Default reasoning effort
258265

259266
`defaultEffort` fills an absent `reasoning.effort` when the combo has a non-null default and the selected target has a known, nonempty supported ladder. If the target supports the configured value, it is retained; otherwise the highest supported rung at or below it is used, or the lowest supported rung when none is lower. Unknown or empty ladders omit the default.

‎docs-site/src/content/docs/ja/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,3 +260,9 @@ ocx combo remove <id> --yes
260260
### 最初のエラーの後にフェイルオーバーが停止したのはなぜですか?
261261

262262
このエラーはターゲット固有のものではなく、最終的なものでした。無効な入力を修正し、大きすぎるコンテキストを削減し、ポリシーの拒否を処理し、拒否されたリクエストの送信元を修正します。コンボはそのような場合には機能しません。
263+
264+
## 任意パラメーターの互換性
265+
266+
通常の 400 エラーは終了扱いですが、`user` の明示的な拒否、または `reasoning.effort`/`reasoning_effort` の非対応値を示す構造化エラーでは、出力開始前に次の適格なターゲットへ進めます。この不一致ではクールダウンを記録しません。安全ポリシーによる拒否、キャンセル、出力開始後の再実行は禁止のままです。
267+
268+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎docs-site/src/content/docs/ko/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,3 +272,9 @@ opencodex 인스턴스에 기록했는지 확인하세요.
272272
대상별 오류가 아니라 종결 오류였기 때문입니다. 잘못된 입력을 수정하고, 너무 큰 context를 줄이고,
273273
정책 거부를 처리하거나, 거부된 요청 origin을 바로잡으세요. combo는 이런 경우 다음 대상으로 넘어가지
274274
않습니다.
275+
276+
## 선택적 매개변수 호환성
277+
278+
일반적인 400 오류는 종료되지만, `user`를 명시적으로 거부하거나 `reasoning.effort`/`reasoning_effort`의 지원되지 않는 값을 나타내는 구조화된 오류는 출력 시작 전에 다음 적격 대상으로 넘어갈 수 있습니다. 이 경우 쿨다운을 기록하지 않습니다. 보안 정책 거부, 취소 및 이미 시작된 출력은 재실행하지 않습니다.
279+
280+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎docs-site/src/content/docs/ru/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,9 @@ CLI и дашборд показывают точное сообщение ва
319319
Ошибка была terminal, а не специфичной для конкретной цели. Исправьте некорректный ввод, сократите
320320
слишком большой контекст, обработайте отказ политики или исправьте отклонённое происхождение
321321
запроса. В таких случаях combo не выполняют hop.
322+
323+
## Совместимость необязательных параметров
324+
325+
Исключение для завершающих ошибок 400: структурированный отказ от `user` или неподдерживаемое значение `reasoning.effort`/`reasoning_effort` позволяет до начала вывода перейти к следующей допустимой цели без периода охлаждения. Отказ политики безопасности, отмена и уже начавшийся вывод по-прежнему запрещают повторное выполнение.
326+
327+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎docs-site/src/content/docs/tr/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,3 +404,9 @@ Hata hedefe özgü olmaktan ziyade uç (terminal) bir hataydı. Geçersiz girdiy
404404
düzeltin, aşırı büyük bir bağlamı azaltın, bir politika reddini işleyin veya
405405
reddedilen istek kaynağını düzeltin. Kombolar bu durumlar için atlama yapmaz.
406406

407+
408+
## İsteğe bağlı parametre uyumluluğu
409+
410+
Sonlandırıcı 400 hatalarının dar bir istisnası vardır: `user` alanını açıkça reddeden veya `reasoning.effort`/`reasoning_effort` için desteklenmeyen değer bildiren yapılandırılmış hata, çıktı başlamadan sonraki uygun hedefe geçebilir. Bu uyumsuzluk için bekleme süresi kaydedilmez. Güvenlik politikası reddi, iptal ve başlamış çıktı yeniden yürütülmez.
411+
412+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎docs-site/src/content/docs/zh-cn/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,9 @@ combo id 不存在。响应是 HTTP 404,类型为 `invalid_request_error`。
290290
### 为什么故障切换在第一次错误后就停止了?
291291

292292
该错误是终止性的,而不是针对目标的。修复无效输入、缩小过大的上下文、处理策略拒绝,或者纠正被拒绝的请求来源。对于这些情况,combo 不会继续跳转。
293+
294+
## 可选参数兼容性
295+
296+
一般 400 错误仍会终止请求,但明确拒绝 `user`,或对 `reasoning.effort`/`reasoning_effort` 返回不支持值的结构化错误,可让 combo 在输出开始前尝试下一个符合条件的目标,而不记录冷却时间。安全策略拒绝、取消以及已经开始的输出仍不可重放。
297+
298+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎docs-site/src/content/docs/zh-tw/guides/combos.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,9 @@ Combo id 未知。回應為 HTTP 404 並帶 type `invalid_request_error`。執
290290
### 為什麼 failover 在第一個錯誤後就停止了?
291291

292292
該錯誤是終端的而非目標特定的。修正無效輸入、縮減過大的上下文、處理策略拒絕,或更正被拒的請求來源。Combo 對那些情況不會跳轉。
293+
294+
## 選用參數相容性
295+
296+
一般 400 錯誤仍會終止請求,但明確拒絕 `user`,或對 `reasoning.effort`/`reasoning_effort` 回傳不支援值的結構化錯誤,可讓 combo 在輸出開始前嘗試下一個符合條件的目標,而不記錄冷卻時間。安全政策拒絕、取消及已開始的輸出仍不可重播。
297+
298+
[Canonical compatibility details](/guides/combos/#request-local-target-compatibility).

‎src/adapters/openai-responses.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,6 +1285,15 @@ function stripUnsupportedForwardParams(body: unknown): unknown {
12851285
return rest;
12861286
}
12871287

1288+
/** Drop client identity metadata only at the canonical Codex destination, not public gateways.
1289+
* Claude translation still owns local session/cache identity; never mutate its replay body.
1290+
*/
1291+
function stripCanonicalForwardUser(body: unknown): unknown {
1292+
if (!isPlainObject(body) || !Object.hasOwn(body, "user")) return body;
1293+
const { user: _user, ...rest } = body;
1294+
return rest;
1295+
}
1296+
12881297
/** Return the lossless text represented by one system message, or null when it is multimodal. */
12891298
function canonicalForwardSystemText(item: Record<string, unknown>): string | null {
12901299
const content = item.content;
@@ -2256,6 +2265,7 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
22562265
if (isCanonicalOpenAiForwardProvider(provider)) {
22572266
outBody = stripDeprecatedPromptCacheRetention(outBody, parsed.modelId);
22582267
outBody = stripCanonicalForwardPromptCacheOptions(outBody);
2268+
outBody = stripCanonicalForwardUser(outBody);
22592269
outBody = normalizeCanonicalForwardPromptEnvelope(outBody);
22602270
outBody = normalizeCanonicalForwardContinuationEnvelope(outBody);
22612271
}

‎src/combos/failover.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,45 @@ const PROVIDER_SCOPED_FAILURE_CODES = new Set([
351351
"insufficient_balance",
352352
]);
353353

354+
/**
355+
* Two concrete optional-control incompatibilities are request-local, not terminal for a combo.
356+
* Require a bounded, intact provider envelope; never infer compatibility from echoed prompt text.
357+
* Only OpenCodex's exact error wrapper may be unwrapped, with a fixed depth budget. Unknown or
358+
* conflicting codes fail closed. No fields are removed here and no same-target replay is added.
359+
*/
360+
function isOptionalControlIncompatibility(status: number, message: string, code?: string | null): boolean {
361+
if (status !== 400 || message.length > 16_384) return false;
362+
const genericCodes = new Set(["", "invalid_request_error", "unsupported_parameter", "unsupported_value"]);
363+
if (!genericCodes.has(normalizedFailureCode(code))) return false;
364+
let text = message.trim();
365+
for (let depth = 0; depth < 3; depth += 1) {
366+
if (text.startsWith("Provider error 400: ")) text = text.slice("Provider error 400: ".length);
367+
let payload: unknown;
368+
try { payload = JSON.parse(text); } catch { return false; }
369+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
370+
const error = (payload as Record<string, unknown>).error;
371+
if (!error || typeof error !== "object" || Array.isArray(error)) return false;
372+
const e = error as Record<string, unknown>;
373+
if (e.code !== undefined && typeof e.code !== "string") return false;
374+
const errorCode = normalizedFailureCode(e.code as string | undefined);
375+
if (!genericCodes.has(errorCode) || typeof e.message !== "string") return false;
376+
if (e.type !== "invalid_request_error" && e.type !== "upstream_error") return false;
377+
if (e.message.startsWith("Provider error 400: ") && e.param === undefined
378+
&& (errorCode === "" || errorCode === "invalid_request_error")) {
379+
text = e.message;
380+
continue;
381+
}
382+
if (e.type !== "invalid_request_error") return false;
383+
if (e.message === "Unsupported parameter: user") {
384+
return (e.param === undefined || e.param === "user") && errorCode !== "unsupported_value";
385+
}
386+
return errorCode === "unsupported_value"
387+
&& (e.param === "reasoning.effort" || e.param === "reasoning_effort")
388+
&& e.message.startsWith("Unsupported value:") && e.message.includes("not supported");
389+
}
390+
return false;
391+
}
392+
354393
export function comboFailureCooldownScope(
355394
status: number,
356395
message: string,
@@ -363,6 +402,7 @@ export function comboFailureCooldownScope(
363402
|| REQUEST_SHAPE_FAILURE_CODES.has(code)
364403
|| isRequestLocalFreePromptCap(status, message, options?.code)
365404
|| isProviderTargetContextOverflow(status, message, options?.code)
405+
|| isOptionalControlIncompatibility(status, message, options?.code)
366406
) return "none";
367407
if (isProviderScopedQuotaCap(status, message, options?.code)) return "provider";
368408
// A rejected or unpaid credential is provider-wide evidence: every target that routes
@@ -465,6 +505,7 @@ export function comboFailureDecision(
465505
// `free_rate_limited` no longer routes through `isProviderScopedQuotaCap` (it is a
466506
// per-request cap, not provider-wide evidence), so keep its hop verdict explicit here.
467507
if (failureCode === "free_rate_limited") return "hop";
508+
if (isOptionalControlIncompatibility(status, message, options?.code)) return "hop";
468509
if (["origin_rejected", "context_length_exceeded", "invalid_request_error"].includes(error.code ?? "")) {
469510
return "stop";
470511
}

0 commit comments

Comments
 (0)