trouteai 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.build/next/BUILD_ID +1 -1
  2. package/.build/next/build-manifest.json +3 -3
  3. package/.build/next/fallback-build-manifest.json +3 -3
  4. package/.build/next/prerender-manifest.json +3 -3
  5. package/.build/next/server/app/(dashboard)/dashboard/activity/page_client-reference-manifest.js +1 -1
  6. package/.build/next/server/app/(dashboard)/dashboard/analytics/combo-health/page_client-reference-manifest.js +1 -1
  7. package/.build/next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
  8. package/.build/next/server/app/(dashboard)/dashboard/analytics/utilization/page_client-reference-manifest.js +1 -1
  9. package/.build/next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
  10. package/.build/next/server/app/(dashboard)/dashboard/audit/page_client-reference-manifest.js +1 -1
  11. package/.build/next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
  12. package/.build/next/server/app/(dashboard)/dashboard/cache/page_client-reference-manifest.js +1 -1
  13. package/.build/next/server/app/(dashboard)/dashboard/combos/[id]/page_client-reference-manifest.js +1 -1
  14. package/.build/next/server/app/(dashboard)/dashboard/combos/live/page_client-reference-manifest.js +1 -1
  15. package/.build/next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
  16. package/.build/next/server/app/(dashboard)/dashboard/combos/playground/page_client-reference-manifest.js +1 -1
  17. package/.build/next/server/app/(dashboard)/dashboard/costs/budget/page_client-reference-manifest.js +1 -1
  18. package/.build/next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
  19. package/.build/next/server/app/(dashboard)/dashboard/costs/pricing/page_client-reference-manifest.js +1 -1
  20. package/.build/next/server/app/(dashboard)/dashboard/costs/quota-share/page_client-reference-manifest.js +1 -1
  21. package/.build/next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
  22. package/.build/next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
  23. package/.build/next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
  24. package/.build/next/server/app/(dashboard)/dashboard/logs/activity/page_client-reference-manifest.js +1 -1
  25. package/.build/next/server/app/(dashboard)/dashboard/logs/console/page_client-reference-manifest.js +1 -1
  26. package/.build/next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
  27. package/.build/next/server/app/(dashboard)/dashboard/logs/proxy/page_client-reference-manifest.js +1 -1
  28. package/.build/next/server/app/(dashboard)/dashboard/logs/timeline/page_client-reference-manifest.js +1 -1
  29. package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page_client-reference-manifest.js +1 -1
  30. package/.build/next/server/app/(dashboard)/dashboard/media-providers/[kind]/page_client-reference-manifest.js +1 -1
  31. package/.build/next/server/app/(dashboard)/dashboard/media-providers/page_client-reference-manifest.js +1 -1
  32. package/.build/next/server/app/(dashboard)/dashboard/more/page_client-reference-manifest.js +1 -1
  33. package/.build/next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
  34. package/.build/next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
  35. package/.build/next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
  36. package/.build/next/server/app/(dashboard)/dashboard/provider-stats/page_client-reference-manifest.js +1 -1
  37. package/.build/next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
  38. package/.build/next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
  39. package/.build/next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
  40. package/.build/next/server/app/(dashboard)/dashboard/quota/page_client-reference-manifest.js +1 -1
  41. package/.build/next/server/app/(dashboard)/dashboard/runtime/page_client-reference-manifest.js +1 -1
  42. package/.build/next/server/app/(dashboard)/dashboard/settings/advanced/page_client-reference-manifest.js +1 -1
  43. package/.build/next/server/app/(dashboard)/dashboard/settings/ai/page_client-reference-manifest.js +1 -1
  44. package/.build/next/server/app/(dashboard)/dashboard/settings/appearance/page_client-reference-manifest.js +1 -1
  45. package/.build/next/server/app/(dashboard)/dashboard/settings/cache/page_client-reference-manifest.js +1 -1
  46. package/.build/next/server/app/(dashboard)/dashboard/settings/feature-flags/page_client-reference-manifest.js +1 -1
  47. package/.build/next/server/app/(dashboard)/dashboard/settings/general/page_client-reference-manifest.js +1 -1
  48. package/.build/next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
  49. package/.build/next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
  50. package/.build/next/server/app/(dashboard)/dashboard/settings/resilience/page_client-reference-manifest.js +1 -1
  51. package/.build/next/server/app/(dashboard)/dashboard/settings/routing/page_client-reference-manifest.js +1 -1
  52. package/.build/next/server/app/(dashboard)/dashboard/settings/security/page_client-reference-manifest.js +1 -1
  53. package/.build/next/server/app/(dashboard)/dashboard/settings/sidebar/page_client-reference-manifest.js +1 -1
  54. package/.build/next/server/app/(dashboard)/dashboard/system/page_client-reference-manifest.js +1 -1
  55. package/.build/next/server/app/(dashboard)/dashboard/system/proxy/page_client-reference-manifest.js +1 -1
  56. package/.build/next/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
  57. package/.build/next/server/app/(dashboard)/home/page_client-reference-manifest.js +1 -1
  58. package/.build/next/server/app/400/page_client-reference-manifest.js +1 -1
  59. package/.build/next/server/app/401/page_client-reference-manifest.js +1 -1
  60. package/.build/next/server/app/403/page_client-reference-manifest.js +1 -1
  61. package/.build/next/server/app/408/page_client-reference-manifest.js +1 -1
  62. package/.build/next/server/app/429/page_client-reference-manifest.js +1 -1
  63. package/.build/next/server/app/500/page_client-reference-manifest.js +1 -1
  64. package/.build/next/server/app/502/page_client-reference-manifest.js +1 -1
  65. package/.build/next/server/app/503/page_client-reference-manifest.js +1 -1
  66. package/.build/next/server/app/_global-error.html +1 -1
  67. package/.build/next/server/app/_global-error.rsc +1 -1
  68. package/.build/next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  69. package/.build/next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  70. package/.build/next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  71. package/.build/next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  72. package/.build/next/server/app/auth/callback/page_client-reference-manifest.js +1 -1
  73. package/.build/next/server/app/callback/page_client-reference-manifest.js +1 -1
  74. package/.build/next/server/app/connect/codex/[token]/page_client-reference-manifest.js +1 -1
  75. package/.build/next/server/app/forbidden/page_client-reference-manifest.js +1 -1
  76. package/.build/next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
  77. package/.build/next/server/app/login/page_client-reference-manifest.js +1 -1
  78. package/.build/next/server/app/maintenance/page_client-reference-manifest.js +1 -1
  79. package/.build/next/server/app/offline/page_client-reference-manifest.js +1 -1
  80. package/.build/next/server/app/page_client-reference-manifest.js +1 -1
  81. package/.build/next/server/chunks/_02r_3f8xhg8a_._.js +4 -4
  82. package/.build/next/server/chunks/_07ymisy5dfwkw._.js +19 -19
  83. package/.build/next/server/chunks/_0bjni2b0bk48x._.js +1 -1
  84. package/.build/next/server/chunks/_0ccwywk_11oi5._.js +4 -4
  85. package/.build/next/server/chunks/_0lyzza9-jf0-p._.js +19 -19
  86. package/.build/next/server/chunks/_0miuo2l-inne9._.js +1 -1
  87. package/.build/next/server/chunks/_0ox6qf339bblb._.js +1 -1
  88. package/.build/next/server/chunks/_11g3_85xlffm_._.js +4 -4
  89. package/.build/next/server/chunks/_11hbt4c_vm6y3._.js +1 -1
  90. package/.build/next/server/chunks/_11hiw0cib9wo0._.js +1 -1
  91. package/.build/next/server/chunks/_16ueh-qq73qi8._.js +1 -1
  92. package/.build/next/server/chunks/_1a403tptlxihn._.js +1 -1
  93. package/.build/next/server/chunks/_1eqaw8kjn2rij._.js +19 -19
  94. package/.build/next/server/chunks/_1grc87rsv-ywz._.js +19 -19
  95. package/.build/next/server/chunks/_1po50cfv-3hj5._.js +1 -1
  96. package/.build/next/server/chunks/_1qcfk-jj0sgeo._.js +1 -1
  97. package/.build/next/server/chunks/_1sv8j92e_8eg7._.js +19 -19
  98. package/.build/next/server/chunks/_1wdvkgutsnz5f._.js +1 -1
  99. package/.build/next/server/chunks/_1z2m2jbpenszh._.js +1 -1
  100. package/.build/next/server/chunks/src_0jsr5vm5qt_kk._.js +1 -1
  101. package/.build/next/server/chunks/src_shared_constants_appConfig_ts_1rww0w9vzhopb._.js +1 -1
  102. package/.build/next/server/chunks/ssr/src_shared_constants_appConfig_ts_06ksyl9fe46j1._.js +1 -1
  103. package/.build/next/server/middleware-build-manifest.js +3 -3
  104. package/.build/next/server/pages/500.html +1 -1
  105. package/.build/next/server/preview-props.json +3 -3
  106. package/.build/next/server/server-reference-manifest.js +1 -1
  107. package/.build/next/server/server-reference-manifest.json +1 -1
  108. package/.build/next/static/chunks/{3gn5_x94r-eu3.js → 3vmjmyyjjzrt7.js} +1 -1
  109. package/open-sse/executors/kiro.ts +122 -9
  110. package/open-sse/handlers/responseTranslator.ts +7 -2
  111. package/open-sse/services/combo/runtimeUnits.ts +11 -1
  112. package/open-sse/services/combo/validateQuality.ts +93 -2
  113. package/open-sse/services/combo.ts +28 -3
  114. package/open-sse/services/errorClassifier.ts +3 -1
  115. package/open-sse/translator/response/claude-to-openai.ts +2 -0
  116. package/open-sse/utils/diagnostics.ts +4 -0
  117. package/open-sse/utils/stream.ts +16 -2
  118. package/open-sse/utils/streamReadiness.ts +1 -0
  119. package/package.json +1 -1
  120. package/src/app/api/v1/messages/route.ts +7 -1
  121. package/src/sse/handlers/chat.ts +14 -1
  122. package/src/sse/services/auth.ts +18 -1
  123. /package/.build/next/static/{LGz_fo9LopKkmUPljx3JR → tMQffjZE6QpGQdmaJrSAi}/_buildManifest.js +0 -0
  124. /package/.build/next/static/{LGz_fo9LopKkmUPljx3JR → tMQffjZE6QpGQdmaJrSAi}/_clientMiddlewareManifest.js +0 -0
  125. /package/.build/next/static/{LGz_fo9LopKkmUPljx3JR → tMQffjZE6QpGQdmaJrSAi}/_ssgManifest.js +0 -0
@@ -882,6 +882,8 @@ export async function handleComboChat({
882
882
  let lastError: string | null = null;
883
883
  let earliestRetryAfter: ComboRetryAfter | null = null;
884
884
  let lastStatus: number | null = null;
885
+ // The first step answer that was a refusal with no output: sent when no step answers.
886
+ let refusedAnswer: Response | null = null;
885
887
  // Every failed step's status, and whether every 429 among them was a used-up usage window:
886
888
  // the final answer is a 429 only when every step was refused for a limit.
887
889
  const stepStatuses: number[] = [];
@@ -1268,7 +1270,8 @@ export async function handleComboChat({
1268
1270
  qualityClone,
1269
1271
  clientRequestedStream,
1270
1272
  log,
1271
- config.responseValidation
1273
+ config.responseValidation,
1274
+ { holdReasoning: i < orderedTargets.length - 1 }
1272
1275
  );
1273
1276
  releaseQualityClone(qualityClone, result, quality);
1274
1277
  if (!quality.valid) {
@@ -1280,6 +1283,12 @@ export async function handleComboChat({
1280
1283
  // A quality-rejected 200 never marks the connection row
1281
1284
  // unhealthy, so the sticky pin's lazy headroom recheck would never
1282
1285
  // catch it either — release it here, on the failing response.
1286
+ if (quality.refused && quality.refusedBody !== undefined && !refusedAnswer) {
1287
+ refusedAnswer = new Response(quality.refusedBody, {
1288
+ status: result.status,
1289
+ headers: result.headers,
1290
+ });
1291
+ }
1283
1292
  releaseStickyPinOnFailure(_sticky.messageHash, effectiveConnectionId);
1284
1293
  recordComboRequest(combo.name, modelStr, {
1285
1294
  success: false,
@@ -1295,7 +1304,8 @@ export async function handleComboChat({
1295
1304
  lastStatus = 502;
1296
1305
  stepStatuses.push(502);
1297
1306
  if (i > 0) fallbackCount++;
1298
- if (provider && rawModel) {
1307
+ // A refusal is about this request, not the model: no lockout for it.
1308
+ if (provider && rawModel && !quality.refused) {
1299
1309
  const mlSettings = resolveModelLockoutSettings(settings);
1300
1310
  if (mlSettings.enabled && mlSettings.errorCodes.includes(502)) {
1301
1311
  recordModelLockoutFailure(
@@ -2103,6 +2113,9 @@ export async function handleComboChat({
2103
2113
  // Retry the entire set if more attempts remain
2104
2114
  if (setTry < maxSetRetries) continue;
2105
2115
 
2116
+ // No step answered, and one refused with no output: that refusal is the answer.
2117
+ if (refusedAnswer) return refusedAnswer;
2118
+
2106
2119
  // All set retries exhausted — return the final error
2107
2120
  if (!lastStatus) {
2108
2121
  notifyWebhookEvent("request.failed", {
@@ -2550,6 +2563,8 @@ async function handleRoundRobinCombo({
2550
2563
  const startTime = Date.now();
2551
2564
  let lastError: string | null = null;
2552
2565
  let lastStatus: number | null = null;
2566
+ // The first step answer that was a refusal with no output: sent when no step answers.
2567
+ let refusedAnswer: Response | null = null;
2553
2568
  let earliestRetryAfter: ComboRetryAfter | null = null;
2554
2569
  const stepStatuses: number[] = [];
2555
2570
  let limitsAreUsageLimits = true;
@@ -2790,11 +2805,18 @@ async function handleRoundRobinCombo({
2790
2805
  rrClone,
2791
2806
  clientRequestedStream,
2792
2807
  log,
2793
- config.responseValidation
2808
+ config.responseValidation,
2809
+ { holdReasoning: visitOrder.length > 0 }
2794
2810
  );
2795
2811
  releaseQualityClone(rrClone, result, quality);
2796
2812
  if (!quality.valid) {
2797
2813
  releaseRejectedQualityResponse(rrClone, result);
2814
+ if (quality.refused && quality.refusedBody !== undefined && !refusedAnswer) {
2815
+ refusedAnswer = new Response(quality.refusedBody, {
2816
+ status: result.status,
2817
+ headers: result.headers,
2818
+ });
2819
+ }
2798
2820
  log.warn(
2799
2821
  "COMBO-RR",
2800
2822
  `${modelStr} returned 200 but failed quality check: ${quality.reason}`
@@ -3240,6 +3262,9 @@ async function handleRoundRobinCombo({
3240
3262
  });
3241
3263
  }
3242
3264
 
3265
+ // No step answered, and one refused with no output: that refusal is the answer.
3266
+ if (refusedAnswer) return refusedAnswer;
3267
+
3243
3268
  if (!lastStatus) {
3244
3269
  return new Response(
3245
3270
  JSON.stringify({
@@ -11,7 +11,9 @@ import { getProviderCategory, getRegistryEntry } from "../config/providerRegistr
11
11
  // successful completion (truncated at the token limit, or a tool-call turn) —
12
12
  // NOT a silent "fake success" failure. Used to avoid rewriting a valid HTTP 200
13
13
  // (e.g. a Claude Code `max_tokens: 1` connectivity ping) into a synthetic 502.
14
- const LEGIT_EMPTY_CLAUDE_STOP = new Set(["max_tokens", "tool_use"]);
14
+ // A refusal is a finished answer too: the Messages API sends it as a 200 with no content and
15
+ // stop_reason "refusal" (an OpenAI-format upstream: finish_reason "content_filter").
16
+ const LEGIT_EMPTY_CLAUDE_STOP = new Set(["max_tokens", "tool_use", "refusal"]);
15
17
  const LEGIT_EMPTY_OPENAI_FINISH = new Set(["length", "tool_calls", "content_filter"]);
16
18
 
17
19
  export function isEmptyContentResponse(responseBody: unknown): boolean {
@@ -335,6 +335,8 @@ function convertStopReason(reason) {
335
335
  return "tool_calls";
336
336
  case "stop_sequence":
337
337
  return "stop";
338
+ case "refusal":
339
+ return "content_filter";
338
340
  default:
339
341
  return "stop";
340
342
  }
@@ -211,6 +211,8 @@ export function detectMalformedNonStream(resp: unknown): MalformedReason | null
211
211
  // `choices`. Without this branch every non-streaming Claude response (incl. plain text)
212
212
  // falls through to `empty_choices` → a false 502.
213
213
  if (body.type === "message" && Array.isArray(body.content)) {
214
+ // A refusal is an answer with no content (the Messages API's own shape for it).
215
+ if (body.stop_reason === "refusal") return null;
214
216
  const hasOutput = (body.content as unknown[]).some((block) => {
215
217
  // A malformed/partial provider response could carry a null (or non-object)
216
218
  // entry in `content`; guard before type-asserting so the detector never
@@ -255,6 +257,8 @@ export function detectMalformedNonStream(resp: unknown): MalformedReason | null
255
257
 
256
258
  const anyHasOutput = choices.some((choice) => {
257
259
  const c = choice as Record<string, unknown>;
260
+ // A refusal (content filter) is an answer with no content.
261
+ if (c?.finish_reason === "content_filter") return true;
258
262
  const msg = c?.message as Record<string, unknown> | undefined;
259
263
  if (typeof msg?.content === "string" && (msg.content as string).length > 0) return true;
260
264
  // Some OpenAI-compatible upstreams (e.g. Cline via OAuth) return
@@ -483,6 +483,8 @@ type ClaudeEmptyResponseLifecycle = {
483
483
  hasMessageDelta: boolean;
484
484
  hasMessageStop: boolean;
485
485
  hasError: boolean;
486
+ // The message ended with stop_reason "refusal": an answer with no content, not an empty one.
487
+ refused?: boolean;
486
488
  syntheticContentInjected: boolean;
487
489
  warningLogged: boolean;
488
490
  };
@@ -529,6 +531,7 @@ function updateClaudeEmptyResponseLifecycle(
529
531
  break;
530
532
  case "message_delta":
531
533
  lifecycle.hasMessageDelta = true;
534
+ if (isClaudeRefusalDelta(payload)) lifecycle.refused = true;
532
535
  break;
533
536
  case "message_stop":
534
537
  lifecycle.hasMessageStop = true;
@@ -541,6 +544,11 @@ function updateClaudeEmptyResponseLifecycle(
541
544
  }
542
545
  }
543
546
 
547
+ function isClaudeRefusalDelta(payload: unknown): boolean {
548
+ const delta = (payload as JsonRecord | null)?.delta as JsonRecord | undefined;
549
+ return !!delta && typeof delta === "object" && delta.stop_reason === "refusal";
550
+ }
551
+
544
552
  function hasClaudeAssistantLifecycle(lifecycle: ClaudeEmptyResponseLifecycle): boolean {
545
553
  return lifecycle.hasMessageStart || lifecycle.hasMessageDelta || lifecycle.hasMessageStop;
546
554
  }
@@ -550,13 +558,19 @@ function shouldInjectClaudeEmptyResponseBeforeCurrentEvent(
550
558
  payload: unknown
551
559
  ): boolean {
552
560
  const type = getClaudeEventType(payload);
553
- if (!type || lifecycle.hasError || lifecycle.hasContentBlock) return false;
561
+ if (!type || lifecycle.hasError || lifecycle.hasContentBlock || lifecycle.refused) return false;
554
562
  if (!hasClaudeAssistantLifecycle(lifecycle)) return false;
563
+ if (type === "message_delta") {
564
+ // A refusal is the model's answer. An `event:` line alone does not carry the stop reason
565
+ // yet: its data line is judged when it arrives.
566
+ const delta = (payload as JsonRecord).delta;
567
+ if (delta === undefined || isClaudeRefusalDelta(payload)) return false;
568
+ }
555
569
  return type === "message_delta" || type === "message_stop";
556
570
  }
557
571
 
558
572
  function shouldInjectClaudeEmptyResponseOnFlush(lifecycle: ClaudeEmptyResponseLifecycle): boolean {
559
- if (lifecycle.hasError || lifecycle.hasContentBlock) return false;
573
+ if (lifecycle.hasError || lifecycle.hasContentBlock || lifecycle.refused) return false;
560
574
  return hasClaudeAssistantLifecycle(lifecycle);
561
575
  }
562
576
 
@@ -149,6 +149,7 @@ const LEGIT_EMPTY_TERMINAL_REASONS = new Set([
149
149
  "content_filter",
150
150
  "max_tokens",
151
151
  "tool_use",
152
+ "refusal",
152
153
  ]);
153
154
 
154
155
  const TERMINAL_REASON_PATTERN = /"(?:finish_reason|stop_reason)"\s*:\s*"([^"]+)"/g;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trouteai",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "Your AI. Your Models. Your Rules. An open-source, self-hosted AI gateway to route, manage, and optimize multiple LLM providers through a single OpenAI- and Anthropic-compatible API.",
5
5
  "keywords": [
6
6
  "ai",
@@ -105,6 +105,12 @@ async function postHandler(request: any, context: any, preParsedBody: any = null
105
105
  const guardedPost = withInjectionGuard(postHandler);
106
106
 
107
107
  // Errors leave this route in the Messages API's own shape ({type: "error", error: {type, ...}}).
108
+ // A refused key (401) is not cured by asking again: `x-should-retry: false` tells the client so
109
+ // (Claude Code otherwise retried it ten times, for minutes), as the count-tokens route does.
108
110
  export async function POST(request: any, context: any) {
109
- return withAnthropicErrorShape(await guardedPost(request, context));
111
+ const response = await withAnthropicErrorShape(await guardedPost(request, context));
112
+ if (response.status !== 401 || response.headers.get("x-should-retry")) return response;
113
+ const headers = new Headers(response.headers);
114
+ headers.set("x-should-retry", "false");
115
+ return new Response(response.body, { status: response.status, headers });
110
116
  }
@@ -725,6 +725,11 @@ async function handleChatRequest(
725
725
  let comboEarliestRetryAfterMs: number | null = null;
726
726
  const comboSkipStatuses: number[] = [];
727
727
  let comboSkipsAreUsageLimits = true;
728
+ // Steps answered 401 because every account of the step has a key the provider refused (known
729
+ // before any request), and steps answered 401 by the upstream itself. Only the first kind
730
+ // lets the global fallback answer, as when such a step was skipped; an upstream 401 stays.
731
+ let comboRefusedKeyAnswers = 0;
732
+ let comboOther401Answers = 0;
728
733
  const comboHiddenModelCache = new Map<string, boolean>();
729
734
  const noteComboRetryAfter = (creds: any) => {
730
735
  const status = Number(creds?.cooldownStatus) || Number(creds?.lastErrorCode) || 429;
@@ -923,6 +928,11 @@ async function handleChatRequest(
923
928
  target?.effectiveComboStrategy ?? combo.strategy,
924
929
  true
925
930
  ).then(async (res: Response) => {
931
+ if (res?.status === 401) {
932
+ const pre = comboPreselectedCredentials.get(getComboCredentialCacheKey(m, target));
933
+ if (pre?.allExpired && pre.expiredStatus === "expired") comboRefusedKeyAnswers++;
934
+ else comboOther401Answers++;
935
+ }
926
936
  // Auto-promote the winning combo model to position #1 (opt-in flag).
927
937
  if (res?.ok)
928
938
  await promoteSuccessfulComboModel(
@@ -951,9 +961,11 @@ async function handleChatRequest(
951
961
 
952
962
  // ── Global Fallback Provider ────────────────────────────────────
953
963
  // If combo exhausted all models, try the global fallback before giving up.
964
+ const allRefusedKeys =
965
+ response.status === 401 && comboRefusedKeyAnswers > 0 && comboOther401Answers === 0;
954
966
  if (
955
967
  !response.ok &&
956
- [502, 503].includes(response.status) &&
968
+ ([502, 503].includes(response.status) || allRefusedKeys) &&
957
969
  typeof (settings as any)?.globalFallbackModel === "string" &&
958
970
  (settings as any).globalFallbackModel.trim()
959
971
  ) {
@@ -2023,6 +2035,7 @@ async function handleSingleModelChatInner(
2023
2035
  (failureKind === "rate_limit" || failureKind === "transient")
2024
2036
  ),
2025
2037
  isCombo,
2038
+ retryAfterMs: typeof result.retryAfterMs === "number" ? result.retryAfterMs : null,
2026
2039
  }
2027
2040
  );
2028
2041
 
@@ -1456,6 +1456,15 @@ export async function getProviderCredentials(
1456
1456
  excludedConnectionIds
1457
1457
  );
1458
1458
  if (syntheticFallback) return syntheticFallback;
1459
+ // Every account left is one whose key the provider refused (401): say so, as for
1460
+ // switched-off accounts. Answering "unavailable" here made a client read a refused key as
1461
+ // an outage and retry it for minutes. Out-of-credit and banned accounts keep their old
1462
+ // answer (a combo's global fallback still answers for them).
1463
+ const left = connections.filter((c) => !excludedConnectionIds.has(c.id));
1464
+ if (left.length > 0 && left.every((c) => normalizeStatus(c.testStatus) === "expired")) {
1465
+ log.warn("AUTH", `${provider} | all ${left.length} accounts have a refused key`);
1466
+ return { allExpired: true, expiredCount: left.length, expiredStatus: "expired" };
1467
+ }
1459
1468
  log.warn("AUTH", `${provider} | all ${connections.length} accounts unavailable`);
1460
1469
  return null;
1461
1470
  }
@@ -1987,6 +1996,8 @@ export async function markAccountUnavailable(
1987
1996
  persistUnavailableState?: boolean;
1988
1997
  /** Caller is the combo engine — it records its own model-level lockouts. */
1989
1998
  isCombo?: boolean;
1999
+ /** The upstream's own Retry-After (ms), read from its answer headers. */
2000
+ retryAfterMs?: number | null;
1990
2001
  } = {}
1991
2002
  ) {
1992
2003
  const currentMutex = markMutexes.get(connectionId) || Promise.resolve();
@@ -2101,13 +2112,19 @@ export async function markAccountUnavailable(
2101
2112
  // lockout sites (per-model quota, grok-web 403, local 404) never did, so the cap
2102
2113
  // fell back to BACKOFF_CONFIG.max here. Resolve it once and pass it at every site.
2103
2114
  const mlSettings = resolveModelLockoutSettings(await getCachedSettings());
2115
+ // The upstream's Retry-After travels as a number (the headers are gone by now); without it
2116
+ // a rate limit of 20 minutes from an OpenAI-format upstream became a 3 s cooldown.
2117
+ const retryAfterSec =
2118
+ typeof options.retryAfterMs === "number" && options.retryAfterMs > 0
2119
+ ? Math.ceil(options.retryAfterMs / 1000)
2120
+ : 0;
2104
2121
  const fallbackResult = checkFallbackError(
2105
2122
  status,
2106
2123
  errorText,
2107
2124
  backoffLevel,
2108
2125
  model,
2109
2126
  provider,
2110
- null,
2127
+ retryAfterSec > 0 ? { "retry-after": String(retryAfterSec) } : null,
2111
2128
  effectiveProviderProfile
2112
2129
  );
2113
2130