tuxevil-rotator 4.2.2 → 4.4.0

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 (84) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +11 -4
  3. package/package.json +2 -1
  4. package/plugins/opencode-discovery/capabilities.d.mts +7 -0
  5. package/plugins/opencode-discovery/capabilities.mjs +54 -0
  6. package/plugins/opencode-discovery/index.d.mts +2 -1
  7. package/plugins/opencode-discovery/index.mjs +6 -1
  8. package/plugins/opencode-discovery/package.json +3 -1
  9. package/src/access-evidence.ts +153 -0
  10. package/src/access-probe.ts +85 -0
  11. package/src/admin-auth.ts +4 -1
  12. package/src/audio-transcription.ts +32 -6
  13. package/src/auto-access-shadow.ts +11 -0
  14. package/src/auto-model-access.ts +185 -0
  15. package/src/auto-output-health.ts +12 -0
  16. package/src/auto-routing-evaluation.ts +80 -0
  17. package/src/auto-routing-quality.ts +308 -0
  18. package/src/auto-routing.ts +403 -26
  19. package/src/cli.ts +3 -3
  20. package/src/compat/model-specs.ts +4 -0
  21. package/src/compat.ts +253 -37
  22. package/src/compression/index.ts +6 -6
  23. package/src/compression/lite.ts +3 -9
  24. package/src/compression/rtk/index.ts +0 -3
  25. package/src/config-defaults.ts +7 -0
  26. package/src/dashboard-app.ts +1 -0
  27. package/src/dashboard.ts +5 -0
  28. package/src/db-store.ts +10 -0
  29. package/src/index.ts +2 -0
  30. package/src/install-agent.ts +211 -129
  31. package/src/install-opencode.ts +80 -18
  32. package/src/model-access-api.ts +74 -0
  33. package/src/model-access.ts +56 -0
  34. package/src/ollama-output-gate.ts +18 -0
  35. package/src/onboarding.ts +1 -1
  36. package/src/provider-catalog-evidence.ts +26 -0
  37. package/src/providers/google-antigravity/catalog.ts +14 -6
  38. package/src/providers/google-antigravity/dynamic-catalog.ts +87 -3
  39. package/src/providers/google-antigravity/forward.ts +4 -2
  40. package/src/providers/google-antigravity/quota.ts +7 -0
  41. package/src/providers/ollama/context-window.ts +13 -0
  42. package/src/providers/ollama/forward.ts +10 -0
  43. package/src/providers/ollama/quota.ts +4 -0
  44. package/src/providers/ollama/translators.ts +19 -2
  45. package/src/providers/openai-codex/catalog.ts +157 -18
  46. package/src/providers/openai-codex/compat.ts +5 -1
  47. package/src/providers/openai-codex/credentials.ts +22 -6
  48. package/src/providers/openai-codex/index.ts +9 -1
  49. package/src/providers/openai-codex/quota.ts +19 -6
  50. package/src/providers/opencode-zen/forward.ts +1 -1
  51. package/src/providers/opencode-zen/quota.ts +2 -0
  52. package/src/proxy.ts +113 -5
  53. package/src/quota-observation.ts +26 -0
  54. package/src/quota-pools.ts +322 -0
  55. package/src/rotator.ts +167 -40
  56. package/src/settings-repository.ts +1 -0
  57. package/src/types.ts +106 -29
  58. package/src/usage-limits-auth.ts +24 -0
  59. package/src/usage-limits.ts +148 -0
  60. package/src/validators.ts +26 -0
  61. package/src/web/app.tsx +4 -0
  62. package/src/web/components/icons.tsx +15 -0
  63. package/src/web/components/overlays.tsx +4 -0
  64. package/src/web/components/ui.tsx +9 -9
  65. package/src/web/lib/audio-recorder.ts +159 -0
  66. package/src/web/lib/colors.ts +4 -0
  67. package/src/web/lib/playground-storage.ts +261 -0
  68. package/src/web/lib/playground.ts +483 -0
  69. package/src/web/lib/pool-navigation.ts +4 -0
  70. package/src/web/lib/pools.ts +2 -243
  71. package/src/web/nav.ts +1 -0
  72. package/src/web/pages/AccountDetail.tsx +2 -1
  73. package/src/web/pages/ModelAccess.tsx +88 -0
  74. package/src/web/pages/Models.tsx +2 -0
  75. package/src/web/pages/Overview.tsx +26 -9
  76. package/src/web/pages/Playground.tsx +1692 -0
  77. package/src/web/pages/Transcription.tsx +562 -0
  78. package/src/web/state/api.ts +6 -0
  79. package/src/web/state/playground-client.ts +136 -0
  80. package/src/web/state/playground.ts +69 -0
  81. package/src/web/state/router.ts +2 -2
  82. package/src/web/state/transcription-client.ts +93 -0
  83. package/src/web/styles/app.css +501 -0
  84. package/tools/telemetry-receiver/receiver.js +59 -46
package/src/compat.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { gateOllamaOutput } from "./ollama-output-gate.js";
2
+ import { markEmptyAutoOutput } from "./auto-output-health.js";
3
+ import { classifyAccessObservation } from "./access-evidence.js";
4
+ import { getCachedOllamaContextWindow } from "./providers/ollama/context-window.js";
1
5
  import type { IncomingMessage, ServerResponse } from "node:http";
2
6
  import { Readable } from "node:stream";
3
7
  import {
@@ -10,6 +14,7 @@ import {
10
14
  type CompressionStats,
11
15
  } from "./compression/index.js";
12
16
  import { idempotencyManager } from "./idempotency.js";
17
+ import { requireAdmin, isSameOriginRequest } from "./admin-auth.js";
13
18
  import {
14
19
  authenticateVirtualKey,
15
20
  isVirtualKeyModelAllowed,
@@ -197,12 +202,18 @@ function authorizeResolvedAutoModel(
197
202
  function buildAutoRoutingCatalog(
198
203
  rotator: AccountRotator,
199
204
  route: AutoRoutingRoute,
205
+ excludedCandidates: ReadonlySet<string> = new Set(),
200
206
  ): AutoRoutingCatalogEntry[] {
201
207
  return buildAllAutoRoutingCandidates(rotator, route).filter((entry) =>
202
- isModelServed(rotator, entry.providerId, entry.modelId),
208
+ isModelServed(rotator, entry.providerId, entry.modelId) &&
209
+ !excludedCandidates.has(autoCandidateKey(entry.providerId, entry.modelId)),
203
210
  );
204
211
  }
205
212
 
213
+ function autoCandidateKey(providerId: string, modelId: string): string {
214
+ return JSON.stringify([providerId, modelId]);
215
+ }
216
+
206
217
  function buildAllAutoRoutingCandidates(
207
218
  rotator: AccountRotator,
208
219
  route: AutoRoutingRoute,
@@ -237,7 +248,7 @@ function buildAllAutoRoutingCandidates(
237
248
  catalog.push({
238
249
  providerId: "ollama",
239
250
  modelId,
240
- contextWindow: 128_000,
251
+ contextWindow: getCachedOllamaContextWindow(modelId),
241
252
  multimodal: false,
242
253
  tools: true,
243
254
  reasoning: false,
@@ -264,6 +275,8 @@ async function resolveAutoModel(
264
275
  rotator: AccountRotator,
265
276
  route: AutoRoutingRoute,
266
277
  input: unknown,
278
+ auth: Awaited<ReturnType<typeof authenticateVirtualKey>>,
279
+ excludedCandidates: ReadonlySet<string> = new Set(),
267
280
  ): Promise<{
268
281
  model: string;
269
282
  providerId: string;
@@ -273,8 +286,8 @@ async function resolveAutoModel(
273
286
  } | null> {
274
287
  const selection = await selectAutoRoutingTarget(
275
288
  rotator,
276
- buildAutoRoutingCatalog(rotator, route),
277
- { route, input, requestedModel: "auto" },
289
+ buildAutoRoutingCatalog(rotator, route, excludedCandidates),
290
+ { route, input, requestedModel: "auto", tenantId: auth.key?.tokenHash ?? "anonymous", isModelAllowed: (model) => isVirtualKeyModelAllowed(auth.key, model) },
278
291
  );
279
292
  if (!selection) return null;
280
293
  return {
@@ -876,10 +889,14 @@ export async function streamCompatSse(
876
889
  openaiToolCallIndex: number;
877
890
  }
878
891
  const openAiStreamingTools = new Map<number, OpenAiStreamingToolState>();
892
+ let ollamaChunks = 0, ollamaThinkingChars = 0, ollamaContentChars = 0, ollamaRawToolCalls = 0;
893
+ let ollamaTerminal = false;
879
894
  const emitOllamaLine = (line: string): void => {
880
895
  try {
881
896
  const parsed = JSON.parse(line) as Record<string, unknown>;
897
+ ollamaChunks++;
882
898
  if (parsed.done === true) {
899
+ ollamaTerminal = true;
883
900
  if (typeof parsed.prompt_eval_count === "number")
884
901
  inputTokens = parsed.prompt_eval_count;
885
902
  if (typeof parsed.eval_count === "number")
@@ -887,6 +904,9 @@ export async function streamCompatSse(
887
904
  }
888
905
  const message = isRecord(parsed.message) ? parsed.message : null;
889
906
  if (!message) return;
907
+ ollamaThinkingChars += typeof message.thinking === "string" ? message.thinking.length : 0;
908
+ ollamaContentChars += typeof message.content === "string" ? message.content.length : 0;
909
+ ollamaRawToolCalls += Array.isArray(message.tool_calls) ? message.tool_calls.length : 0;
890
910
  const deltaText =
891
911
  typeof message.content === "string" ? message.content : "";
892
912
  if (deltaText) {
@@ -1353,6 +1373,11 @@ export async function streamCompatSse(
1353
1373
  responseEvents.off?.("close", closeUpstreamForClient);
1354
1374
  }
1355
1375
 
1376
+ if (upstream === "ollama" && !reqClosed && !streamError && !text.trim() && toolCallIndex === 0 && !anthropicHasToolUse) {
1377
+ streamError = "Ollama completed without a final answer or tool call";
1378
+ markEmptyAutoOutput("ollama", model);
1379
+ console.warn("[tuxevil-rotator]", JSON.stringify({ event: "empty-ollama-completion", model, chunks: ollamaChunks, terminalSeen: ollamaTerminal, upstreamContentChars: ollamaContentChars, upstreamThinkingChars: ollamaThinkingChars, upstreamToolCalls: ollamaRawToolCalls, convertedTextChars: text.length }));
1380
+ }
1356
1381
  if (!reqClosed && !res.writableEnded) {
1357
1382
  if (streamError) {
1358
1383
  writeCompatStreamError(res, format, streamError);
@@ -2360,6 +2385,7 @@ async function completeViaRotator(
2360
2385
  rawRequest?: unknown;
2361
2386
  rawResponse?: unknown;
2362
2387
  compressionStats?: CompressionStats | null;
2388
+ autoRecoveryEnabled?: boolean;
2363
2389
  },
2364
2390
  ): Promise<{
2365
2391
  completion: CompatCompletion;
@@ -2395,6 +2421,12 @@ async function completeViaRotator(
2395
2421
  : format === "ollama"
2396
2422
  ? parseOllamaNdjson(raw)
2397
2423
  : parseAntigravitySse(raw);
2424
+ if (format === "ollama" && completion.streamError) {
2425
+ if (body.displayModel?.toLowerCase() !== "auto") throw new Error(completion.streamError);
2426
+ markEmptyAutoOutput("ollama", body.model);
2427
+ recordCompatOutcome(rotator, body, context, 502, completion, undefined, options);
2428
+ return completion;
2429
+ }
2398
2430
  if (completion.inputTokens > 0 || completion.outputTokens > 0) {
2399
2431
  rotator.recordTokenUsage(
2400
2432
  context.displayModelKey,
@@ -2413,8 +2445,22 @@ async function completeViaRotator(
2413
2445
  );
2414
2446
  return completion;
2415
2447
  } else {
2448
+ let upstreamBody: ReadableStream<Uint8Array> | null = response.body;
2449
+ if (body.displayModel?.toLowerCase() === "auto" && upstreamFormat(context) === "ollama" && upstreamBody) {
2450
+ let gated;
2451
+ try { gated = await gateOllamaOutput(upstreamBody); }
2452
+ catch { if (controller.signal.aborted) throw controller.signal.reason; gated = { useful: false, body: new Response("").body! }; }
2453
+ upstreamBody = gated.body;
2454
+ if (!gated.useful) {
2455
+ markEmptyAutoOutput("ollama", body.model);
2456
+ const completion = { ...parseOllamaNdjson(await new Response(upstreamBody).text()), streamError: "Auto Ollama produced no useful output before commitment" };
2457
+ if (completion.inputTokens > 0 || completion.outputTokens > 0) rotator.recordTokenUsage(context.displayModelKey, completion.inputTokens, completion.outputTokens);
2458
+ recordCompatOutcome(rotator, body, context, 502, completion, undefined, options);
2459
+ return completion;
2460
+ }
2461
+ }
2416
2462
  const completion = await streamCompatSse(
2417
- response.body,
2463
+ upstreamBody,
2418
2464
  req,
2419
2465
  res,
2420
2466
  body.displayModel?.toLowerCase() === "auto"
@@ -2446,36 +2492,42 @@ async function completeViaRotator(
2446
2492
  }
2447
2493
  },
2448
2494
  controller.signal,
2495
+ { autoRecovery: options?.autoRecoveryEnabled === true && body.displayModel?.toLowerCase() === "auto" },
2449
2496
  );
2450
2497
 
2451
2498
  let outcome: RotationOutcome<CompatCompletion>;
2452
2499
  let isDeduplicated = false;
2453
2500
 
2454
- if (shouldDedup) {
2455
- const clientKey = idempotencyManager.extractClientKey(req);
2456
- const key = idempotencyManager.computeKey(
2457
- body.model,
2458
- options?.rawRequest || body,
2459
- clientKey,
2460
- );
2461
- const dedupRes = await idempotencyManager
2462
- .execute(key, windowMs, async () => {
2463
- const res = await runWithRotation();
2464
- if (!res.ok) {
2465
- throw new NonOkOutcomeError(res);
2466
- }
2467
- return res;
2468
- })
2469
- .catch((err) => {
2470
- if (err instanceof NonOkOutcomeError) {
2471
- return { result: err.outcome, isDeduplicated: false };
2472
- }
2473
- throw err;
2474
- });
2475
- outcome = dedupRes.result;
2476
- isDeduplicated = dedupRes.isDeduplicated;
2477
- } else {
2478
- outcome = await runWithRotation();
2501
+ try {
2502
+ if (shouldDedup) {
2503
+ const clientKey = idempotencyManager.extractClientKey(req);
2504
+ const key = idempotencyManager.computeKey(
2505
+ body.model,
2506
+ options?.rawRequest || body,
2507
+ clientKey,
2508
+ );
2509
+ const dedupRes = await idempotencyManager
2510
+ .execute(key, windowMs, async () => {
2511
+ const res = await runWithRotation();
2512
+ if (!res.ok) {
2513
+ throw new NonOkOutcomeError(res);
2514
+ }
2515
+ return res;
2516
+ })
2517
+ .catch((err) => {
2518
+ if (err instanceof NonOkOutcomeError) {
2519
+ return { result: err.outcome, isDeduplicated: false };
2520
+ }
2521
+ throw err;
2522
+ });
2523
+ outcome = dedupRes.result;
2524
+ isDeduplicated = dedupRes.isDeduplicated;
2525
+ } else {
2526
+ outcome = await runWithRotation();
2527
+ }
2528
+ } finally {
2529
+ req.off("aborted", abort);
2530
+ if (typeof res.off === "function") res.off("close", abort);
2479
2531
  }
2480
2532
 
2481
2533
  if (!outcome.ok) {
@@ -2497,6 +2549,7 @@ async function completeViaRotator(
2497
2549
  compressionStats: options?.compressionStats,
2498
2550
  };
2499
2551
  }
2552
+ if (outcome.result.streamError && !res.headersSent) return { completion: outcome.result, status: 502, errorText: outcome.result.streamError, streamed: false, context: outcome.context };
2500
2553
  return {
2501
2554
  completion: outcome.result,
2502
2555
  status: 200,
@@ -2669,6 +2722,8 @@ export function buildOpenAIModelCatalog(
2669
2722
  family: "openai-codex",
2670
2723
  provider: "openai-codex",
2671
2724
  reasoning: model.reasoning,
2725
+ ...(model.reasoning && model.reasoningEfforts ? { reasoning_efforts: model.reasoningEfforts } : {}),
2726
+ ...(model.reasoning && model.defaultReasoningEffort ? { default_reasoning_effort: model.defaultReasoningEffort } : {}),
2672
2727
  multimodal: model.multimodal,
2673
2728
  tool_calling: model.tools,
2674
2729
  },
@@ -2712,7 +2767,14 @@ export function buildOpenAIModelCatalog(
2712
2767
  });
2713
2768
  }
2714
2769
  }
2715
- return dedupeByRoute(catalog, source);
2770
+ const discovered = dedupeByRoute(catalog, source);
2771
+ if (rotator?.getConfig?.().typesafeRouting?.enabled && discovered.length > 0) {
2772
+ const context = Math.min(...discovered.map(entry => entry.context_window));
2773
+ discovered.unshift({ id: "auto", object: "model", created: 0, owned_by: "tuxevil-rotator",
2774
+ context_window: context, max_model_len: context,
2775
+ meta: { context_length: context, family: "automatic-routing", multimodal: discovered.some(entry => entry.meta.multimodal), tool_calling: discovered.some(entry => entry.meta.tool_calling) } });
2776
+ }
2777
+ return discovered;
2716
2778
  }
2717
2779
 
2718
2780
  /** Keep one entry per id: the one owned by the provider its requests go to. */
@@ -2837,7 +2899,7 @@ export async function handleGeminiGenerateContent(
2837
2899
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
2838
2900
 
2839
2901
  const autoSelection = autoRequested
2840
- ? await resolveAutoModel(rotator, "gemini", parsed)
2902
+ ? await resolveAutoModel(rotator, "gemini", parsed, auth)
2841
2903
  : null;
2842
2904
  if (autoRequested && !autoSelection) {
2843
2905
  return writeJson(res, 503, {
@@ -2935,14 +2997,126 @@ export async function handleGeminiGenerateContent(
2935
2997
  }, rotatorHeaders);
2936
2998
  }
2937
2999
 
3000
+ /** Dashboard inference: authorization is checked here, never from a client flag. */
3001
+ export async function handlePlaygroundChatCompletions(
3002
+ req: IncomingMessage,
3003
+ res: ServerResponse,
3004
+ rotator: AccountRotator,
3005
+ ): Promise<void> {
3006
+ if (!requireAdmin(req, res)) return;
3007
+ if (!isSameOriginRequest(req)) {
3008
+ return writeJson(res, 403, { error: { message: "Playground requests must come from the dashboard's own origin" } });
3009
+ }
3010
+ res.setHeader("Cache-Control", "no-store");
3011
+ req.headers["x-rotator-no-deduplicate"] = "true";
3012
+ await handleChatCompletions(req, res, rotator, true);
3013
+ }
3014
+
2938
3015
  export async function handleOpenAIChatCompletions(
2939
3016
  req: IncomingMessage,
2940
3017
  res: ServerResponse,
2941
3018
  rotator: AccountRotator,
3019
+ ): Promise<void> {
3020
+ await handleChatCompletions(req, res, rotator, false);
3021
+ }
3022
+
3023
+ interface AutoChatRecoveryState {
3024
+ failedCandidates: string[];
3025
+ lastFailure?: { status: number; message: string };
3026
+ }
3027
+
3028
+ const MAX_AUTO_CHAT_ATTEMPTS = 3;
3029
+
3030
+ function isRecoverableAutoChatFailure(
3031
+ status: number,
3032
+ errorText: string | undefined,
3033
+ model: string,
3034
+ provider: string,
3035
+ ): boolean {
3036
+ if (errorText === "Auto Ollama produced no useful output before commitment") return true;
3037
+ if ([402, 404, 408, 429, 503].includes(status)) return true;
3038
+ if (
3039
+ status === 400 &&
3040
+ provider === "openai-codex" &&
3041
+ classifyAccessObservation(status, errorText ?? "", false, provider, model) ===
3042
+ "model-unavailable"
3043
+ ) return true;
3044
+ return status >= 500 && status <= 599 && errorText !== "Upstream request failed";
3045
+ }
3046
+
3047
+ function describeAutoRecoveryFailure(
3048
+ status: number,
3049
+ errorText: string | undefined,
3050
+ provider: string,
3051
+ ): string {
3052
+ if (
3053
+ errorText === "Auto Ollama produced no useful output before commitment" ||
3054
+ errorText === "Ollama completed without a final answer or tool call"
3055
+ ) return "Ollama completed without a final answer or tool call";
3056
+ if (status === 402) return "Selected provider rejected the model for payment or plan reasons";
3057
+ if (status === 408) return "Selected provider timed out";
3058
+ if (status === 429) return "Selected provider is rate limited";
3059
+ if (status === 404) return "Selected model is unavailable";
3060
+ if (status === 400 && provider === "openai-codex") return "Selected Codex model is unavailable to this account";
3061
+ if (status === 503) return "Selected provider is temporarily unavailable";
3062
+ return "Selected model failed before the response began";
3063
+ }
3064
+
3065
+ async function recoverAutoChatCandidate(
3066
+ req: IncomingMessage,
3067
+ res: ServerResponse,
3068
+ rotator: AccountRotator,
3069
+ dashboardAdmin: boolean,
3070
+ input: unknown,
3071
+ state: AutoChatRecoveryState | undefined,
3072
+ failedModel: string | undefined,
3073
+ failedProvider: string | undefined,
3074
+ status: number,
3075
+ errorText: string | undefined,
3076
+ ): Promise<boolean> {
3077
+ if (
3078
+ !failedModel || !failedProvider ||
3079
+ !isRecoverableAutoChatFailure(status, errorText, failedModel, failedProvider) ||
3080
+ res.headersSent || req.aborted || res.destroyed
3081
+ ) return false;
3082
+
3083
+ const failedCandidates = new Set(state?.failedCandidates ?? []);
3084
+ const failedKey = autoCandidateKey(failedProvider, failedModel);
3085
+ if (failedCandidates.has(failedKey)) return false;
3086
+ failedCandidates.add(failedKey);
3087
+ if (failedCandidates.size >= MAX_AUTO_CHAT_ATTEMPTS) return false;
3088
+
3089
+ console.info("[tuxevil-rotator]", JSON.stringify({
3090
+ event: "auto-candidate-recovery",
3091
+ failed_provider: failedProvider,
3092
+ failed_model: failedModel,
3093
+ failed_status: status,
3094
+ failed_candidates: failedCandidates.size,
3095
+ max_attempts: MAX_AUTO_CHAT_ATTEMPTS,
3096
+ recovery_reason: errorText === "Auto Ollama produced no useful output before commitment"
3097
+ ? "empty-output"
3098
+ : status === 402
3099
+ ? "payment-or-plan"
3100
+ : "upstream-availability",
3101
+ }));
3102
+ await handleChatCompletions(req, res, rotator, dashboardAdmin, input, {
3103
+ failedCandidates: [...failedCandidates],
3104
+ lastFailure: { status, message: describeAutoRecoveryFailure(status, errorText, failedProvider) },
3105
+ });
3106
+ return true;
3107
+ }
3108
+
3109
+ async function handleChatCompletions(
3110
+ req: IncomingMessage,
3111
+ res: ServerResponse,
3112
+ rotator: AccountRotator,
3113
+ dashboardAdmin: boolean,
3114
+ retryInput?: unknown,
3115
+ recoveryState?: AutoChatRecoveryState,
2942
3116
  ): Promise<void> {
2943
3117
  let parsed: unknown;
2944
3118
  try {
2945
- parsed = await readJsonBody(req);
3119
+ parsed = retryInput ?? await readJsonBody(req);
2946
3120
  } catch (err) {
2947
3121
  if (err instanceof PayloadTooLargeError)
2948
3122
  return writeJson(res, 413, {
@@ -2965,7 +3139,9 @@ export async function handleOpenAIChatCompletions(
2965
3139
 
2966
3140
  const requestedModel = validation.value.model;
2967
3141
  const autoRequested = isAutoModel(requestedModel);
2968
- const auth = await authenticateVirtualKey(req, autoRequested ? undefined : requestedModel);
3142
+ const auth = dashboardAdmin
3143
+ ? { authenticated: true, key: null, rawKey: undefined }
3144
+ : await authenticateVirtualKey(req, autoRequested ? undefined : requestedModel);
2969
3145
  if (!auth.authenticated) {
2970
3146
  sendAuthErrorResponse(res, auth);
2971
3147
  return;
@@ -2973,9 +3149,20 @@ export async function handleOpenAIChatCompletions(
2973
3149
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
2974
3150
 
2975
3151
  const autoSelection = autoRequested
2976
- ? await resolveAutoModel(rotator, "openai-chat", validation.value)
3152
+ ? await resolveAutoModel(
3153
+ rotator,
3154
+ "openai-chat",
3155
+ validation.value,
3156
+ auth,
3157
+ new Set(recoveryState?.failedCandidates ?? []),
3158
+ )
2977
3159
  : null;
2978
3160
  if (autoRequested && !autoSelection) {
3161
+ if (recoveryState?.lastFailure) {
3162
+ return writeJson(res, recoveryState.lastFailure.status, {
3163
+ error: { message: recoveryState.lastFailure.message, type: "upstream_error" },
3164
+ });
3165
+ }
2979
3166
  return writeJson(res, 503, {
2980
3167
  error: { message: "No compatible model is currently available", type: "upstream_error" },
2981
3168
  });
@@ -3000,6 +3187,20 @@ export async function handleOpenAIChatCompletions(
3000
3187
  selectionMode: autoSelection?.mode,
3001
3188
  selectionConfidence: autoSelection?.confidence,
3002
3189
  selectionReason: autoSelection?.reason,
3190
+ autoRecovery: autoRequested
3191
+ ? (status, context, errorText) => recoverAutoChatCandidate(
3192
+ req,
3193
+ res,
3194
+ rotator,
3195
+ dashboardAdmin,
3196
+ validation.value,
3197
+ recoveryState,
3198
+ context?.selectedModel ?? autoSelection?.model,
3199
+ context?.providerId ?? autoSelection?.providerId,
3200
+ status,
3201
+ errorText,
3202
+ )
3203
+ : undefined,
3003
3204
  });
3004
3205
  return;
3005
3206
  }
@@ -3045,8 +3246,23 @@ export async function handleOpenAIChatCompletions(
3045
3246
  requesterIp: req.socket?.remoteAddress || null,
3046
3247
  rawRequest: validation.value,
3047
3248
  compressionStats: compRes.stats,
3249
+ autoRecoveryEnabled: autoRequested,
3048
3250
  },
3049
3251
  );
3252
+ if (autoRequested && await recoverAutoChatCandidate(
3253
+ req,
3254
+ res,
3255
+ rotator,
3256
+ dashboardAdmin,
3257
+ validation.value,
3258
+ recoveryState,
3259
+ result.context?.selectedModel ?? autoSelection?.model ?? bodyToForward.model,
3260
+ result.context?.providerId ?? autoSelection?.providerId,
3261
+ result.status,
3262
+ result.errorText,
3263
+ )) {
3264
+ return;
3265
+ }
3050
3266
  if (result.status !== 200) {
3051
3267
  compatLogger.warn(
3052
3268
  `OpenAI compat upstream failed status=${result.status} model=${validation.value.model}`,
@@ -3169,7 +3385,7 @@ export async function handleOpenAIResponsesCreate(
3169
3385
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
3170
3386
 
3171
3387
  const autoSelection = autoRequested
3172
- ? await resolveAutoModel(rotator, "openai-responses", validation.value)
3388
+ ? await resolveAutoModel(rotator, "openai-responses", validation.value, auth)
3173
3389
  : null;
3174
3390
  if (autoRequested && !autoSelection) {
3175
3391
  return writeJson(res, 503, {
@@ -3482,7 +3698,7 @@ export async function handleAnthropicMessages(
3482
3698
  const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
3483
3699
 
3484
3700
  const autoSelection = autoRequested
3485
- ? await resolveAutoModel(rotator, "anthropic", validation.value)
3701
+ ? await resolveAutoModel(rotator, "anthropic", validation.value, auth)
3486
3702
  : null;
3487
3703
  if (autoRequested && !autoSelection) {
3488
3704
  return writeJson(res, 503, {
@@ -57,12 +57,6 @@ export function applyPromptCompression(
57
57
  let currentMessages = messages;
58
58
  const techniques: string[] = [];
59
59
 
60
- if (mode === "lite" || mode === "rtk+lite") {
61
- const liteRes = compressLite(currentMessages, options);
62
- currentMessages = liteRes.messages;
63
- techniques.push(...liteRes.techniques);
64
- }
65
-
66
60
  if (mode === "rtk" || mode === "rtk+lite") {
67
61
  const rtkRes = compressRTK(currentMessages);
68
62
  currentMessages = rtkRes.messages;
@@ -71,6 +65,12 @@ export function applyPromptCompression(
71
65
  }
72
66
  }
73
67
 
68
+ if (mode === "lite" || mode === "rtk+lite") {
69
+ const liteRes = compressLite(currentMessages, options);
70
+ currentMessages = liteRes.messages;
71
+ techniques.push(...liteRes.techniques);
72
+ }
73
+
74
74
  const compressedChars = countChars(currentMessages);
75
75
  const savedChars = Math.max(0, originalChars - compressedChars);
76
76
  const savingsPercent =
@@ -9,7 +9,7 @@ export interface LiteCompressionOptions {
9
9
  maxToolResultChars?: number;
10
10
  /** Replace base64 image data URLs / image parts with text placeholders (default: false) */
11
11
  replaceImages?: boolean;
12
- /** Character length limit for system prompt deduplication hash comparison (default: 200) */
12
+ /** Deprecated compatibility option; instruction deduplication always compares complete messages. */
13
13
  maxSystemCharsHash?: number;
14
14
  /** Target model name for model-specific optimizations */
15
15
  model?: string;
@@ -37,7 +37,7 @@ export function collapseWhitespace(text: string): string {
37
37
  }
38
38
 
39
39
  /**
40
- * Applies all 5 lossless lite compression techniques to a list of messages.
40
+ * Applies lightweight compression. Tool-result truncation and optional image replacement are lossy.
41
41
  */
42
42
  export function compressLite(
43
43
  messages: ChatMessage[],
@@ -54,7 +54,6 @@ export function compressLite(
54
54
 
55
55
  const maxToolResultChars = options.maxToolResultChars ?? 2000;
56
56
  const replaceImages = options.replaceImages ?? false;
57
- const maxSystemCharsHash = options.maxSystemCharsHash ?? 200;
58
57
 
59
58
  const techniquesUsed = new Set<string>();
60
59
  let originalCharCount = 0;
@@ -71,12 +70,7 @@ export function compressLite(
71
70
 
72
71
  // 1. System Prompt Deduplication
73
72
  if (msg.role === "system" || msg.role === "developer") {
74
- const textContent = typeof msg.content === "string"
75
- ? msg.content
76
- : (Array.isArray(msg.content)
77
- ? msg.content.map((p) => (typeof p === "string" ? p : p.text || "")).join("\n")
78
- : "");
79
- const promptKey = textContent.slice(0, maxSystemCharsHash).trim();
73
+ const promptKey = JSON.stringify(msg);
80
74
  if (seenSystemPrompts.has(promptKey)) {
81
75
  techniquesUsed.add("dedup_system_prompt");
82
76
  continue; // Drop duplicate system prompt
@@ -15,9 +15,6 @@ export interface RtkCompressionResult {
15
15
  linesStripped: number;
16
16
  }
17
17
 
18
- const _SHELL_TOOL_NAME_RE =
19
- /\b(bash|shell|terminal|run_command|execute_command|exec|command)\b/i;
20
-
21
18
  function isToolOrTerminalMessage(msg: ChatMessage): boolean {
22
19
  if (msg.role === "tool") return true;
23
20
  if (typeof msg.content === "string") {
@@ -27,6 +27,7 @@ function safeStreamRecoveryMaxRetries(value: number | undefined): number {
27
27
  export function applyConfigDefaults(config: Config): Config {
28
28
  return {
29
29
  proxyPort: config.proxyPort || 51200,
30
+ modelAccessShadow: config.modelAccessShadow ?? false,
30
31
  bindHost: config.bindHost || rotatorEnv("BIND_HOST") || "0.0.0.0",
31
32
  routingPolicy: config.routingPolicy || "timer-first",
32
33
  requestsPerRotation: config.requestsPerRotation || 5,
@@ -70,6 +71,12 @@ export function applyConfigDefaults(config: Config): Config {
70
71
  maxCandidates: config.typesafeRouting.maxCandidates ?? 32,
71
72
  shortlistSize: config.typesafeRouting.shortlistSize ?? 12,
72
73
  maxExcerptChars: config.typesafeRouting.maxExcerptChars ?? 12_000,
74
+ selectionPolicy: config.typesafeRouting.selectionPolicy ?? "model-choice",
75
+ restrictToEffortPools: config.typesafeRouting.restrictToEffortPools ?? false,
76
+ effortPools: config.typesafeRouting.effortPools,
77
+ sessionAffinity: config.typesafeRouting.sessionAffinity ?? false,
78
+ stallEscalation: config.typesafeRouting.stallEscalation ?? false,
79
+ sessionAffinityTtlSeconds: config.typesafeRouting.sessionAffinityTtlSeconds ?? 1800,
73
80
  }
74
81
  : undefined,
75
82
  providerOrder: config.providerOrder,
@@ -48,6 +48,7 @@ export const DASHBOARD_CSP = [
48
48
  "script-src 'self'",
49
49
  "style-src 'self'",
50
50
  "img-src 'self' data:",
51
+ "media-src 'self' blob:",
51
52
  "font-src 'self'",
52
53
  "connect-src 'self'",
53
54
  "manifest-src 'self'",
package/src/dashboard.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { isUsageReadToken } from "./usage-limits-auth.js";
1
2
  // Admin API handlers behind the web dashboard. The dashboard UI itself is the
2
3
  // Preact app in src/web, served by dashboard-app.ts.
3
4
 
@@ -666,6 +667,10 @@ export async function serveCreateSessionApi(
666
667
  candidate = null;
667
668
  }
668
669
  const token = getConfiguredAdminToken();
670
+ if (typeof candidate === "string" && isUsageReadToken(candidate.trim())) {
671
+ sendDashboardJson(req, res, 401, { ok: false, error: "That admin token was not accepted." });
672
+ return;
673
+ }
669
674
  if (!token) {
670
675
  sendDashboardJson(req, res, 200, { ok: true, authRequired: false });
671
676
  return;
package/src/db-store.ts CHANGED
@@ -235,3 +235,13 @@ export async function setCachedResponsesStore(
235
235
  assertInitialized();
236
236
  await repository.set("responses_store", JSON.stringify(store));
237
237
  }
238
+
239
+ /** Private informational evidence; independent of routing state and credentials. */
240
+ export function getCachedAccessEvidence(): unknown {
241
+ assertInitialized();
242
+ try { return JSON.parse(repository.get("model_access_evidence") ?? "null"); } catch { return null; }
243
+ }
244
+ export async function setCachedAccessEvidence(value: unknown): Promise<void> {
245
+ assertInitialized();
246
+ await repository.set("model_access_evidence", JSON.stringify(value));
247
+ }
package/src/index.ts CHANGED
@@ -289,6 +289,8 @@ export async function main(): Promise<void> {
289
289
  stopPendingSessionReaper();
290
290
  await closeProxyDispatchers();
291
291
  const { closeDb } = await import("./db-store.js");
292
+ const { persistAccessEvidence } = await import("./access-evidence.js");
293
+ await persistAccessEvidence().catch(() => {});
292
294
  await closeDb();
293
295
  clearTimeout(forceExitTimer);
294
296
  process.exit(0);