tuxevil-rotator 3.8.0 → 3.10.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.
@@ -0,0 +1,201 @@
1
+ import { execSync } from "node:child_process";
2
+ import { readFileSync, existsSync } from "node:fs";
3
+ import { resolve, dirname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const __dirname = dirname(fileURLToPath(import.meta.url));
7
+ const PLUGIN_SOURCE_PATH = resolve(__dirname, "../plugins/opencode-discovery.js");
8
+
9
+ export interface InstallOptions {
10
+ host?: string;
11
+ user?: string;
12
+ port?: number;
13
+ sshKey?: string;
14
+ rotatorUrl?: string;
15
+ providerId?: string;
16
+ providerName?: string;
17
+ apiKey?: string;
18
+ targetDir?: string;
19
+ dryRun?: boolean;
20
+ }
21
+
22
+ /**
23
+ * Builds the remote installation script that will execute on the target machine.
24
+ */
25
+ export function buildRemoteInstallerScript(
26
+ pluginContent: string,
27
+ options: {
28
+ rotatorUrl: string;
29
+ providerId: string;
30
+ providerName: string;
31
+ apiKey?: string;
32
+ targetDir?: string;
33
+ }
34
+ ): string {
35
+ const pluginContentBase64 = Buffer.from(pluginContent, "utf8").toString("base64");
36
+ const targetDir = options.targetDir || "~/.config/opencode";
37
+ const providerId = options.providerId || "antigravity";
38
+ const providerName = options.providerName || "Antigravity (rotator)";
39
+ const rotatorUrl = options.rotatorUrl;
40
+ const apiKey = options.apiKey;
41
+
42
+ return `
43
+ set -e
44
+ TARGET_DIR="${targetDir}"
45
+ eval TARGET_DIR="$TARGET_DIR"
46
+
47
+ mkdir -p "$TARGET_DIR/plugins"
48
+ PLUGIN_FILE="$TARGET_DIR/plugins/opencode-discovery.js"
49
+ CONFIG_FILE="$TARGET_DIR/opencode.json"
50
+
51
+ echo "==> Writing plugin to $PLUGIN_FILE..."
52
+ echo "${pluginContentBase64}" | base64 -d > "$PLUGIN_FILE"
53
+
54
+ # Prepare node script to cleanly mutate or create opencode.json
55
+ node -e '
56
+ const fs = require("fs");
57
+ const path = require("path");
58
+
59
+ const configFile = process.argv[1];
60
+ const pluginPath = process.argv[2];
61
+ const providerID = process.argv[3];
62
+ const providerName = process.argv[4];
63
+ const baseURL = process.argv[5];
64
+ const apiKey = process.argv[6];
65
+
66
+ let config = {};
67
+ if (fs.existsSync(configFile)) {
68
+ try {
69
+ const raw = fs.readFileSync(configFile, "utf8");
70
+ config = JSON.parse(raw);
71
+ } catch (err) {
72
+ console.error("Warning: parsing existing " + configFile + " failed, backing up to .bak");
73
+ fs.copyFileSync(configFile, configFile + ".bak." + Date.now());
74
+ }
75
+ }
76
+
77
+ if (!config.$schema) {
78
+ config.$schema = "https://opencode.ai/config.json";
79
+ }
80
+
81
+ if (!Array.isArray(config.plugin)) {
82
+ config.plugin = [];
83
+ }
84
+
85
+ // Remove any prior entry of opencode-discovery
86
+ config.plugin = config.plugin.filter(p => {
87
+ if (typeof p === "string") return !p.includes("opencode-discovery.js");
88
+ if (Array.isArray(p)) return !p[0].includes("opencode-discovery.js");
89
+ return true;
90
+ });
91
+
92
+ // Add plugin tuple with options
93
+ config.plugin.push([
94
+ pluginPath,
95
+ {
96
+ baseURL: baseURL,
97
+ providerID: providerID,
98
+ providerName: providerName
99
+ }
100
+ ]);
101
+
102
+ if (!config.provider) {
103
+ config.provider = {};
104
+ }
105
+
106
+ if (!config.provider[providerID]) {
107
+ config.provider[providerID] = {
108
+ npm: "@ai-sdk/openai-compatible",
109
+ name: providerName,
110
+ options: {
111
+ baseURL: baseURL
112
+ }
113
+ };
114
+ } else {
115
+ config.provider[providerID].npm = "@ai-sdk/openai-compatible";
116
+ config.provider[providerID].name = providerName;
117
+ config.provider[providerID].options = config.provider[providerID].options || {};
118
+ config.provider[providerID].options.baseURL = baseURL;
119
+ }
120
+
121
+ if (apiKey && apiKey !== "no-key") {
122
+ config.provider[providerID].options.apiKey = apiKey;
123
+ }
124
+
125
+ if (!config.model) {
126
+ config.model = providerID + "/gemini-3.8-flash-high";
127
+ }
128
+
129
+ fs.writeFileSync(configFile, JSON.stringify(config, null, 2) + "\\n", "utf8");
130
+ console.log("==> Successfully updated " + configFile);
131
+ ' "$CONFIG_FILE" "$PLUGIN_FILE" "${providerId}" "${providerName}" "${rotatorUrl}" "${apiKey || ""}"
132
+
133
+ echo "==> Installation complete! OpenCode is now configured to discover models from ${rotatorUrl}"
134
+ `;
135
+ }
136
+
137
+ /**
138
+ * Installs the discovery plugin either locally or remotely via SSH.
139
+ */
140
+ export async function installOpenCodePlugin(options: InstallOptions): Promise<void> {
141
+ if (!existsSync(PLUGIN_SOURCE_PATH)) {
142
+ throw new Error(`Plugin file not found at ${PLUGIN_SOURCE_PATH}`);
143
+ }
144
+
145
+ const pluginContent = readFileSync(PLUGIN_SOURCE_PATH, "utf8");
146
+ const rotatorUrl = (options.rotatorUrl || process.env.TUXEVIL_ROTATOR_BASE_URL || "http://127.0.0.1:51200/v1").replace(/\/+$/, "");
147
+ const providerId = options.providerId || "antigravity";
148
+ const providerName = options.providerName || "Antigravity (rotator)";
149
+
150
+ const script = buildRemoteInstallerScript(pluginContent, {
151
+ rotatorUrl,
152
+ providerId,
153
+ providerName,
154
+ apiKey: options.apiKey,
155
+ targetDir: options.targetDir,
156
+ });
157
+
158
+ if (options.dryRun) {
159
+ console.log("=== Dry Run Mode: Script that would be executed ===");
160
+ console.log(script);
161
+ return;
162
+ }
163
+
164
+ // Local installation
165
+ if (!options.host || options.host === "localhost" || options.host === "127.0.0.1") {
166
+ console.log(`==> Installing OpenCode plugin locally for rotator: ${rotatorUrl}...`);
167
+ execSync("bash -s", {
168
+ input: script,
169
+ stdio: ["pipe", "inherit", "inherit"],
170
+ });
171
+ return;
172
+ }
173
+
174
+ // Remote installation via SSH
175
+ const sshTarget = options.user ? `${options.user}@${options.host}` : options.host;
176
+ const sshArgs: string[] = [
177
+ "-o", "BatchMode=yes",
178
+ "-o", "ConnectTimeout=10",
179
+ "-o", "StrictHostKeyChecking=accept-new",
180
+ ];
181
+
182
+ if (options.port) {
183
+ sshArgs.push("-p", String(options.port));
184
+ }
185
+ if (options.sshKey) {
186
+ sshArgs.push("-i", options.sshKey);
187
+ }
188
+
189
+ const sshCmd = `ssh ${sshArgs.join(" ")} ${sshTarget} "bash -s"`;
190
+
191
+ console.log(`==> Installing OpenCode plugin remotely on ${sshTarget} (Rotator: ${rotatorUrl})...`);
192
+ try {
193
+ execSync(sshCmd, {
194
+ input: script,
195
+ stdio: ["pipe", "inherit", "inherit"],
196
+ });
197
+ } catch (err: unknown) {
198
+ const errorMsg = err instanceof Error ? err.message : String(err);
199
+ throw new Error(`SSH installation failed on ${sshTarget}: ${errorMsg}`, { cause: err });
200
+ }
201
+ }
package/src/key-auth.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import type { VirtualKey } from "./types.js";
2
+ import { applyModelAlias, type VirtualKey } from "./types.js";
3
3
  import {
4
4
  hasAnyVirtualKeys,
5
5
  lookupVirtualKey,
@@ -68,6 +68,45 @@ export function extractVirtualKey(req: IncomingMessage): string | null {
68
68
  return null;
69
69
  }
70
70
 
71
+ export interface VirtualKeyScopeOptions {
72
+ /** Scope entries that authorize the equivalent model only, for backward compatibility. */
73
+ equivalentScopes?: readonly string[];
74
+ equivalentModel?: string;
75
+ normalizeModel?: (model: string) => string;
76
+ }
77
+
78
+ function isModelAllowedByScope(models: string[], targetModel: string): boolean {
79
+ const normalizedTarget = targetModel.toLowerCase();
80
+ const aliasedTarget = applyModelAlias(targetModel).toLowerCase();
81
+ const canonicalTarget =
82
+ normalizedTarget === "whisper-1" || normalizedTarget === "whisper"
83
+ ? "gemini-3.8-flash-low"
84
+ : aliasedTarget;
85
+
86
+ return models.some((m) => {
87
+ const normalizedM = m.toLowerCase();
88
+ const aliasedM = applyModelAlias(m).toLowerCase();
89
+ const canonicalM =
90
+ normalizedM === "whisper-1" || normalizedM === "whisper"
91
+ ? "gemini-3.8-flash-low"
92
+ : aliasedM;
93
+
94
+ return (
95
+ normalizedM === normalizedTarget ||
96
+ normalizedTarget.includes(normalizedM) ||
97
+ aliasedM === aliasedTarget ||
98
+ aliasedTarget.includes(aliasedM) ||
99
+ canonicalM === canonicalTarget ||
100
+ canonicalM === normalizedTarget ||
101
+ normalizedM === canonicalTarget ||
102
+ canonicalM === aliasedTarget ||
103
+ aliasedM === canonicalTarget ||
104
+ normalizedM === aliasedTarget ||
105
+ aliasedM === normalizedTarget
106
+ );
107
+ });
108
+ }
109
+
71
110
  /**
72
111
  * Validates request authentication against virtual keys.
73
112
  *
@@ -75,11 +114,13 @@ export function extractVirtualKey(req: IncomingMessage): string | null {
75
114
  * - If DB is not configured OR no virtual keys exist in DB, auth is not enforced.
76
115
  * - If keys exist, valid key is mandatory for proxy routes.
77
116
  * - Key must not be blocked.
78
- * - If targetModel is provided and key has model scope, targetModel must be allowed.
117
+ * - If target models are provided and key has model scope, every target must be allowed,
118
+ * unless the key is scoped to an equivalent id for `options.equivalentModel`.
79
119
  */
80
120
  export async function authenticateVirtualKey(
81
121
  req: IncomingMessage,
82
- targetModel?: string,
122
+ targetModel?: string | readonly string[],
123
+ options: VirtualKeyScopeOptions = {},
83
124
  ): Promise<KeyAuthResult> {
84
125
  const isEnforced = isDbConfigured() && (await hasAnyVirtualKeys());
85
126
 
@@ -124,14 +165,37 @@ export async function authenticateVirtualKey(
124
165
  }
125
166
 
126
167
  // Model access restrictions
127
- if (targetModel && !isVirtualKeyModelAllowed(key, targetModel)) {
168
+ const targets = (typeof targetModel === "string" ? [targetModel] : (targetModel ?? [])).filter(
169
+ (target) => target.length > 0,
170
+ );
171
+ const scopedModels = key.models ?? [];
172
+ if (targets.length > 0 && scopedModels.length > 0 && !scopedModels.includes("*")) {
173
+ const scopes = scopedModels.map((m) => m.toLowerCase());
174
+ const hasEquivalentScope = (options.equivalentScopes ?? []).some((scope) =>
175
+ scopes.includes(scope.toLowerCase()),
176
+ );
177
+ const normalizeModel = (model: string): string =>
178
+ (options.normalizeModel?.(model) ?? applyModelAlias(model)).toLowerCase().replace(/^models\//, "");
179
+ const equivalentModel = options.equivalentModel ? normalizeModel(options.equivalentModel) : undefined;
180
+ const deniedTarget =
181
+ hasEquivalentScope && equivalentModel === undefined
182
+ ? undefined
183
+ : targets.find((target) => {
184
+ if (isModelAllowedByScope(scopedModels, target)) return false;
185
+ const isEquivalentModel =
186
+ equivalentModel !== undefined && normalizeModel(target) === equivalentModel;
187
+ return !(hasEquivalentScope && isEquivalentModel);
188
+ });
189
+
190
+ if (deniedTarget !== undefined) {
128
191
  return {
129
192
  authenticated: false,
130
193
  key,
131
194
  rawKey,
132
- error: `Model '${targetModel}' is not allowed for this Virtual Key`,
195
+ error: `Model '${deniedTarget}' is not allowed for this Virtual Key`,
133
196
  statusCode: 403,
134
197
  };
198
+ }
135
199
  }
136
200
 
137
201
  touchVirtualKeyLastActive(key.tokenHash);
package/src/onboarding.ts CHANGED
@@ -458,6 +458,10 @@ ${codexAuthUrl && codexSessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;
458
458
  <input name="enabled" type="checkbox" ${currentTypeSafe?.enabled !== false ? "checked" : ""} />
459
459
  Enable Jev when requests use <code>model: "auto"</code>
460
460
  </label>
461
+ <label style="display:flex;align-items:flex-start;gap:8px;margin-top:12px;">
462
+ <input name="shadowMode" type="checkbox" ${currentTypeSafe?.shadowMode ? "checked" : ""} />
463
+ <span>Shadow mode: log Jev's recommendation, but keep serving the deterministic model. Logs contain model IDs and decision metadata only, not prompts.</span>
464
+ </label>
461
465
  <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:16px;">
462
466
  Save Jev configuration
463
467
  </button>
@@ -658,6 +662,7 @@ if (typesafeForm) typesafeForm.addEventListener('submit', async (e) => {
658
662
  const apiKey = form.apiKey.value.trim();
659
663
  const model = form.model.value.trim();
660
664
  const enabled = form.enabled.checked;
665
+ const shadowMode = form.shadowMode.checked;
661
666
  if (!model) { showResult('<div class="note error">Please enter a Jev model alias.</div>'); return; }
662
667
  btn.disabled = true;
663
668
  btn.textContent = 'Saving...';
@@ -665,7 +670,7 @@ if (typesafeForm) typesafeForm.addEventListener('submit', async (e) => {
665
670
  try {
666
671
  const params = new URLSearchParams(window.location.search);
667
672
  const token = params.get('token') || '';
668
- const payload = { provider: 'typesafe', ...(apiKey ? { apiKey } : {}), model, enabled };
673
+ const payload = { provider: 'typesafe', ...(apiKey ? { apiKey } : {}), model, enabled, shadowMode };
669
674
  const res = await fetch('/api/cli-login', {
670
675
  method: 'POST',
671
676
  headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
@@ -711,6 +716,7 @@ export async function handleCliLoginApi(
711
716
  apiKey?: string;
712
717
  model?: string;
713
718
  enabled?: boolean;
719
+ shadowMode?: boolean;
714
720
  };
715
721
  try {
716
722
  const raw = await readLimitedBody(req, MAX_CLI_LOGIN_BODY_BYTES);
@@ -726,6 +732,7 @@ export async function handleCliLoginApi(
726
732
  apiKey?: string;
727
733
  model?: string;
728
734
  enabled?: boolean;
735
+ shadowMode?: boolean;
729
736
  };
730
737
  } catch (err) {
731
738
  res.writeHead(err instanceof PayloadTooLargeError ? 413 : 400, {
@@ -890,7 +897,7 @@ export async function handleCliLoginApi(
890
897
  }
891
898
 
892
899
  async function handleTypeSafeCliLogin(
893
- body: { apiKey?: string; model?: string; enabled?: boolean },
900
+ body: { apiKey?: string; model?: string; enabled?: boolean; shadowMode?: boolean },
894
901
  res: ServerResponse,
895
902
  rotator: TypeSafeConfigSink,
896
903
  ): Promise<void> {
@@ -909,6 +916,11 @@ async function handleTypeSafeCliLogin(
909
916
  res.end(JSON.stringify({ ok: false, error: "Invalid enabled flag" }));
910
917
  return;
911
918
  }
919
+ if (body.shadowMode !== undefined && typeof body.shadowMode !== "boolean") {
920
+ res.writeHead(400, { "Content-Type": "application/json" });
921
+ res.end(JSON.stringify({ ok: false, error: "Invalid shadow mode flag" }));
922
+ return;
923
+ }
912
924
 
913
925
  const apiKey = body.apiKey?.trim() ?? "";
914
926
  const model = body.model?.trim() ?? "";
@@ -926,6 +938,7 @@ async function handleTypeSafeCliLogin(
926
938
 
927
939
  const current = rotator.getConfig();
928
940
  const currentRouting = current.typesafeRouting ?? {};
941
+ const shadowMode = body.shadowMode ?? currentRouting.shadowMode ?? false;
929
942
  if (!apiKey && !currentRouting.apiKey) {
930
943
  res.writeHead(400, { "Content-Type": "application/json" });
931
944
  res.end(JSON.stringify({ ok: false, error: "Missing TypeSafe API key" }));
@@ -939,6 +952,7 @@ async function handleTypeSafeCliLogin(
939
952
  ...(apiKey ? { apiKey } : {}),
940
953
  enabled,
941
954
  model,
955
+ shadowMode,
942
956
  },
943
957
  };
944
958
 
@@ -959,6 +973,7 @@ async function handleTypeSafeCliLogin(
959
973
  ok: true,
960
974
  configured: true,
961
975
  enabled,
976
+ shadowMode,
962
977
  model,
963
978
  }));
964
979
  }
@@ -61,7 +61,7 @@ function isDiscoverableModelId(value: string): boolean {
61
61
  !RESERVED_QUOTA_MODEL_IDS.has(lower) &&
62
62
  !lower.startsWith("chat_") &&
63
63
  !lower.startsWith("tab_") &&
64
- !lower.startsWith("gemini-3.5-");
64
+ (!lower.startsWith("gemini-3.5-") || lower === "gemini-3.5-flash-lite");
65
65
  }
66
66
 
67
67
  /** Validate and sanitize the untrusted runtime catalog response. */
@@ -216,6 +216,19 @@ export function isNonEmptyString(value: unknown): value is string {
216
216
  return typeof value === "string" && value.trim().length > 0;
217
217
  }
218
218
 
219
+ function containsUnresolvedFunctionResponseRef(value: unknown): boolean {
220
+ if (Array.isArray(value)) {
221
+ return value.some(containsUnresolvedFunctionResponseRef);
222
+ }
223
+ if (!isRecord(value)) return false;
224
+
225
+ // Gemini reserves { "$ref": "..." } inside function responses for a
226
+ // FunctionResponsePart display_name. This converter does not attach named
227
+ // response parts, so JSON Schema/OpenAPI refs cannot be resolved here.
228
+ if (typeof value.$ref === "string") return true;
229
+ return Object.values(value).some(containsUnresolvedFunctionResponseRef);
230
+ }
231
+
219
232
  /**
220
233
  * Normalize a tool-call `arguments` field into the JSON-encoded string
221
234
  * shape that OpenAI-compat responses expect. The Ollama adapter feeds us
@@ -1129,6 +1142,9 @@ export function openAIToAntigravityBody(
1129
1142
  !Array.isArray(parsed)
1130
1143
  ? parsed
1131
1144
  : { output: parsed };
1145
+ if (containsUnresolvedFunctionResponseRef(responseData)) {
1146
+ responseData = { output: responseText };
1147
+ }
1132
1148
  } catch {
1133
1149
  responseData = { output: responseText };
1134
1150
  }
@@ -13,20 +13,22 @@ export interface CodexModel {
13
13
  source: "allowlist" | "discovered";
14
14
  }
15
15
 
16
- // Only models validated by the initial unauthenticated/public spike are in the
17
- // safe base list. Authenticated discovery can add provider-owned GPT-5 IDs.
16
+ // The base list contains OpenAI models published in the Codex model catalog.
17
+ // Authenticated discovery can add provider-owned GPT-5 and GPT-6 IDs.
18
18
  // The Codex /models endpoint can expose models from other ChatGPT-backed
19
19
  // providers (for example Claude), so model IDs alone must be filtered before
20
20
  // they influence routing.
21
- // Official context window for the GPT-5.6 family per
22
- // https://platform.openai.com/docs/models (gpt-5.6-sol / gpt-5.6-terra / gpt-5.6-luna
23
- // each report 1.05M context / 128K max output).
21
+ // Official context window for GPT-5.6 and GPT-6 Astra, Sol, and Luna per their
22
+ // OpenAI model pages (1.05M context / 128K max output).
24
23
  const CODEX_CONTEXT_WINDOW = 1_050_000;
25
24
  // Hard cap to defend against `/models` upstream reporting absurd values for
26
25
  // discovered ids. 2M is comfortably above the published 1.05M baseline.
27
26
  const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
28
- const CODEX_DISCOVERED_ID_PATTERN = /^gpt-5(?:\.\d+)?(?:-[a-z0-9]+)+$/i;
27
+ const CODEX_DISCOVERED_ID_PATTERN = /^gpt-(?:5(?:\.\d+)?|6)(?:-[a-z0-9]+)+$/i;
29
28
  export const CODEX_BASE_MODELS: readonly CodexModel[] = [
29
+ { id: "gpt-6-astra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
30
+ { id: "gpt-6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
31
+ { id: "gpt-6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
30
32
  { id: "gpt-5.6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
31
33
  { id: "gpt-5.6-terra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
32
34
  { id: "gpt-5.6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
@@ -39,7 +39,7 @@ export interface CodexCompatOptions {
39
39
  rawRequest?: unknown;
40
40
  providerId?: string;
41
41
  requestedModel?: string;
42
- selectionMode?: "typesafe" | "deterministic" | "disabled";
42
+ selectionMode?: "typesafe" | "deterministic" | "shadow" | "disabled";
43
43
  selectionConfidence?: number;
44
44
  selectionReason?: string;
45
45
  }
package/src/proxy.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  type Server,
11
11
  type ServerResponse,
12
12
  } from "node:http";
13
- import { Readable } from "node:stream";
13
+ import { Readable, type Duplex } from "node:stream";
14
14
  import {
15
15
  classifyEffortRoutingModel,
16
16
  getEffortRoutingRule,
@@ -83,6 +83,7 @@ import { logger } from "./logger.js";
83
83
  import {
84
84
  trackFeature,
85
85
  reportFlagEvent,
86
+ extractFlagReason,
86
87
  FLAG_PATTERNS,
87
88
  type FlagPattern,
88
89
  } from "./telemetry.js";
@@ -178,6 +179,8 @@ import {
178
179
  import {
179
180
  handleOpenAIAudioTranscriptions,
180
181
  handleAudioWebSocket,
182
+ closeAllAudioWebSockets,
183
+ WS_SHUTDOWN_CLOSE_GRACE_MS,
181
184
  } from "./audio-transcription.js";
182
185
  import { applyConfigDefaults } from "./account-store.js";
183
186
  import {
@@ -241,7 +244,7 @@ export interface RequestBody {
241
244
  requestId?: string;
242
245
  displayModel?: string;
243
246
  providerId?: string;
244
- selectionMode?: "typesafe" | "deterministic" | "disabled";
247
+ selectionMode?: "typesafe" | "deterministic" | "shadow" | "disabled";
245
248
  selectionConfidence?: number;
246
249
  selectionReason?: string;
247
250
  [key: string]: unknown;
@@ -287,7 +290,7 @@ export interface RotationAttemptContext {
287
290
  providerId?: string;
288
291
  requestedModel?: string;
289
292
  selectedModel?: string;
290
- selectionMode?: "typesafe" | "deterministic" | "disabled";
293
+ selectionMode?: "typesafe" | "deterministic" | "shadow" | "disabled";
291
294
  selectionConfidence?: number;
292
295
  selectionReason?: string;
293
296
  }
@@ -606,6 +609,7 @@ async function handleUpstreamAccountAction(
606
609
  const ctx401 = rotator.getFlagContext(account, modelKey);
607
610
  reportFlagEvent({
608
611
  flagHttpStatus: 401,
612
+ ...extractFlagReason(action.errorText),
609
613
  flagPatternsMatched:
610
614
  matched401.length > 0 ? matched401 : ["blocked_401" as FlagPattern],
611
615
  model: modelKey,
@@ -648,6 +652,7 @@ async function handleUpstreamAccountAction(
648
652
  const ctx403 = rotator.getFlagContext(account, modelKey);
649
653
  reportFlagEvent({
650
654
  flagHttpStatus: 403,
655
+ ...extractFlagReason(action.errorText),
651
656
  flagPatternsMatched: matchedPatterns,
652
657
  model: modelKey,
653
658
  timerType: ctx403.timerType as FlagEventData["timerType"],
@@ -2611,7 +2616,7 @@ export function startProxy(
2611
2616
  }
2612
2617
 
2613
2618
  if (method === "POST" && pathname === "/v1/audio/transcriptions") {
2614
- handleOpenAIAudioTranscriptions(req, res).catch((err) => {
2619
+ handleOpenAIAudioTranscriptions(req, res, rotator).catch((err) => {
2615
2620
  log(`Audio transcription error: ${err}`, rotator, "error");
2616
2621
  if (!res.headersSent)
2617
2622
  res.writeHead(500, { "Content-Type": "application/json" });
@@ -2749,6 +2754,11 @@ export function startProxy(
2749
2754
  res.end(JSON.stringify({ error: "Not found" }));
2750
2755
  });
2751
2756
 
2757
+ // Upgraded sockets leave the HTTP server's connection tracking, so neither closeAllConnections() nor
2758
+ // closeAllAudioWebSockets() alone can end sockets still authenticating or half-closed earlier.
2759
+ const audioUpgradeSockets = new Set<Duplex>();
2760
+ const serverClosing = new AbortController();
2761
+
2752
2762
  server.on("upgrade", (req, socket) => {
2753
2763
  const url = req.url || "";
2754
2764
  const pathname = url.split("?")[0];
@@ -2759,12 +2769,35 @@ export function startProxy(
2759
2769
  pathname === "/v1/listen" ||
2760
2770
  pathname.startsWith("/ws/")
2761
2771
  ) {
2762
- handleAudioWebSocket(req, socket).catch(() => socket.destroy());
2772
+ if (serverClosing.signal.aborted) {
2773
+ socket.destroy();
2774
+ return;
2775
+ }
2776
+ audioUpgradeSockets.add(socket);
2777
+ socket.once("close", () => audioUpgradeSockets.delete(socket));
2778
+ handleAudioWebSocket(req, socket, rotator, { signal: serverClosing.signal }).catch(() =>
2779
+ socket.destroy(),
2780
+ );
2763
2781
  return;
2764
2782
  }
2765
2783
  socket.destroy();
2766
2784
  });
2767
2785
 
2786
+ const originalClose = server.close.bind(server);
2787
+ server.close = ((callback?: (err?: Error) => void) => {
2788
+ serverClosing.abort();
2789
+ closeAllAudioWebSockets(serverClosing.signal);
2790
+ const forceCloseTimer = setTimeout(() => {
2791
+ for (const socket of audioUpgradeSockets) socket.destroy();
2792
+ }, WS_SHUTDOWN_CLOSE_GRACE_MS);
2793
+ forceCloseTimer.unref?.();
2794
+ return originalClose(callback);
2795
+ }) as typeof server.close;
2796
+
2797
+ server.on("close", () => {
2798
+ closeAllAudioWebSockets(serverClosing.signal);
2799
+ });
2800
+
2768
2801
  server.listen(port, bindHost, () => {
2769
2802
  log(`Listening on ${bindHost}:${port}`, rotator);
2770
2803
  log(`Dashboard: http://localhost:${port}/dashboard`, rotator);
@@ -30,7 +30,7 @@ export interface RotatorResponseHeaderOptions {
30
30
  model?: string;
31
31
  requestedModel?: string;
32
32
  selectedProvider?: string;
33
- modelSelection?: "typesafe" | "deterministic" | "disabled";
33
+ modelSelection?: "typesafe" | "deterministic" | "shadow" | "disabled";
34
34
  selectionConfidence?: number;
35
35
  selectionReason?: string;
36
36
  latencyMs?: number;