tuxevil-rotator 3.9.0 → 3.11.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.
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);
@@ -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
  }
@@ -4,6 +4,8 @@ export const OPENCODE_ZEN_BASE_URL = "https://opencode.ai/zen/v1";
4
4
  export const OPENCODE_ZEN_MODELS_URL = "https://opencode.ai/zen/v1/models";
5
5
  export const OPENCODE_ZEN_CHAT_URL = "https://opencode.ai/zen/v1/chat/completions";
6
6
  export const OPENCODE_ZEN_RESPONSES_URL = "https://opencode.ai/zen/v1/responses";
7
+ export const OPENCODE_ZEN_USER_AGENT =
8
+ "opencode/1.18.31 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14";
7
9
 
8
10
  export const OPENCODE_ZEN_FREE_MODELS = [
9
11
  "big-pickle",
@@ -14,6 +14,7 @@ import {
14
14
  isOpenCodeZenResponsesModel,
15
15
  OPENCODE_ZEN_CHAT_URL,
16
16
  OPENCODE_ZEN_RESPONSES_URL,
17
+ OPENCODE_ZEN_USER_AGENT,
17
18
  } from "./catalog.js";
18
19
  import { isRecord } from "../../compat/schema-sanitizer.js";
19
20
  import type {
@@ -244,26 +245,28 @@ function buildOpenCodeZenHeaders(
244
245
  !HOP_BY_HOP.has(lower) &&
245
246
  lower !== "authorization" &&
246
247
  lower !== "content-type" &&
247
- lower !== "accept"
248
+ lower !== "accept" &&
249
+ lower !== "user-agent"
248
250
  ) {
249
251
  headers[key] = value;
250
252
  }
251
253
  }
252
254
 
253
- // OpenCode's free tier requires these context headers. Native OpenCode
254
- // emits them only for provider IDs beginning with `opencode`; the rotator
255
- // is commonly configured under a custom provider ID, so fill safe defaults.
256
- if (!headerValue(headers, "x-opencode-session")) {
257
- headers["x-opencode-session"] = `zen-session-${body.requestId || randomUUID()}`;
258
- }
259
- if (!headerValue(headers, "x-opencode-request")) {
260
- headers["x-opencode-request"] = `zen-request-${body.requestId || randomUUID()}`;
261
- }
262
- if (!headerValue(headers, "x-opencode-client")) {
263
- headers["x-opencode-client"] = "tuxevil-rotator";
264
- }
265
- if (!headerValue(headers, "user-agent")) {
266
- headers["User-Agent"] = "tuxevil-rotator/opencode-zen";
255
+ headers["User-Agent"] = OPENCODE_ZEN_USER_AGENT;
256
+
257
+ // OpenCode sends x-opencode-session directly for provider IDs beginning
258
+ // with `opencode`. For custom provider IDs it sends the same real session
259
+ // under x-session-affinity and X-Session-Id. Forward that value under the
260
+ // upstream's expected name only when the incoming User-Agent is OpenCode.
261
+ const userAgent = headerValue(originalHeaders, "user-agent");
262
+ if (
263
+ !headerValue(headers, "x-opencode-session") &&
264
+ userAgent?.toLowerCase().startsWith("opencode/")
265
+ ) {
266
+ const sessionId =
267
+ headerValue(headers, "x-session-affinity") ??
268
+ headerValue(headers, "x-session-id");
269
+ if (sessionId) headers["x-opencode-session"] = sessionId;
267
270
  }
268
271
 
269
272
  headers.Authorization = `Bearer ${getOpenCodeZenApiKey(account.config) ?? ""}`;
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { createInterface } from "node:readline";
4
4
  import type { AccountConfig } from "../../types.js";
5
- import { OPENCODE_ZEN_MODELS_URL } from "./catalog.js";
5
+ import { OPENCODE_ZEN_MODELS_URL, OPENCODE_ZEN_USER_AGENT } from "./catalog.js";
6
6
  import { defaultAccountEmail, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
7
7
 
8
8
  function askQuestion(prompt: string): Promise<string> {
@@ -24,6 +24,7 @@ export async function validateApiKey(
24
24
  headers: {
25
25
  Authorization: `Bearer ${apiKey}`,
26
26
  Accept: "application/json",
27
+ "User-Agent": OPENCODE_ZEN_USER_AGENT,
27
28
  },
28
29
  });
29
30
 
@@ -4,7 +4,7 @@ import { fetchWithRetry } from "../../fetch-with-retry.js";
4
4
  import type { AccountRuntime, ModelQuota } from "../../types.js";
5
5
  import type { QuotaFetchContext } from "../adapter.js";
6
6
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
7
- import { OPENCODE_ZEN_MODELS_URL } from "./catalog.js";
7
+ import { OPENCODE_ZEN_MODELS_URL, OPENCODE_ZEN_USER_AGENT } from "./catalog.js";
8
8
  import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
9
9
  import { sortQuotaPools } from "../registry.js";
10
10
 
@@ -21,6 +21,7 @@ export async function fetchOpenCodeZenQuota(
21
21
  headers: {
22
22
  Authorization: `Bearer ${apiKey}`,
23
23
  Accept: "application/json",
24
+ "User-Agent": OPENCODE_ZEN_USER_AGENT,
24
25
  },
25
26
  timeoutMs: 8000,
26
27
  dispatcher: getAccountProxyDispatcher(account, OPENCODE_ZEN_PROVIDER_ID),
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 {
@@ -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);
package/src/rotator.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
35
35
  import {
36
36
  reportFlagEvent,
37
+ extractFlagReason,
37
38
  FLAG_PATTERNS,
38
39
  type FlagEventData,
39
40
  } from "./telemetry.js";
@@ -205,6 +206,30 @@ const QUOTA_POOL_FOR_KICKSTART_MODEL: Record<string, string> = {
205
206
  "gpt-oss:20b": "session",
206
207
  };
207
208
 
209
+ function describeKickstartAuthFailure(status: number, upstreamModel: string, body: string): {
210
+ description: string;
211
+ accountEnforcement: boolean;
212
+ } {
213
+ let message = "";
214
+ let reason = "";
215
+ try {
216
+ const parsed = JSON.parse(body) as { error?: { message?: unknown; details?: Array<{ reason?: unknown }> } };
217
+ if (typeof parsed.error?.message === "string") message = parsed.error.message;
218
+ const detail = parsed.error?.details?.find((entry) => typeof entry.reason === "string");
219
+ if (typeof detail?.reason === "string") reason = detail.reason;
220
+ } catch {
221
+ message = body;
222
+ }
223
+ const detailText = [message.slice(0, 200), reason ? `(${reason.slice(0, 80)})` : ""]
224
+ .filter(Boolean).join(" ");
225
+ const accountEnforcement = status === 401 ||
226
+ /verif|infring|suspend|abus|terminat|violat|banned|account.*policy/i.test(`${message} ${reason}`);
227
+ return {
228
+ description: `kickstart ${status} on ${upstreamModel}${detailText ? `: ${detailText}` : ""}`,
229
+ accountEnforcement,
230
+ };
231
+ }
232
+
208
233
  export class AccountRotator {
209
234
  private accounts: AccountRuntime[] = [];
210
235
  // Per-model active account tracking
@@ -388,6 +413,7 @@ export class AccountRotator {
388
413
  private routingWarningLastLoggedAt = new Map<string, number>();
389
414
  private static readonly ROUTING_WARNING_DEDUP_MS = 60_000;
390
415
  private autoWarmupEnabled = false;
416
+ private readonly kickstartDeniedUntil = new Map<string, number>();
391
417
  // Debounced state writer: batches multiple saveState() calls within a 1s window
392
418
  // to a single disk write. Hot paths (markError, recordRequest, etc.) call
393
419
  // scheduleStateSave() instead of saveState() to avoid blocking the event loop.
@@ -614,6 +640,7 @@ export class AccountRotator {
614
640
  account.quotaExhaustedAt = saved.quotaExhaustedAt;
615
641
  account.disabled = saved.disabled;
616
642
  account.flagged = saved.flagged ?? false;
643
+ if (account.flagged && saved.flagReason) account.lastError = saved.flagReason;
617
644
  account.allowFreshWindowStartsOverride =
618
645
  saved.allowFreshWindowStartsOverride ?? false;
619
646
  }
@@ -778,6 +805,7 @@ export class AccountRotator {
778
805
  quotaExhaustedAt: account.quotaExhaustedAt,
779
806
  disabled: account.disabled,
780
807
  flagged: account.flagged,
808
+ flagReason: account.flagged ? account.lastError : null,
781
809
  allowFreshWindowStartsOverride: account.allowFreshWindowStartsOverride,
782
810
  };
783
811
  }
@@ -1066,15 +1094,17 @@ export class AccountRotator {
1066
1094
  account: AccountRuntime,
1067
1095
  statusCode: number,
1068
1096
  errorText: string,
1097
+ model = "quota-poll",
1069
1098
  ): void {
1070
- const modelKey = account.quota[0]?.modelKey ?? "quota-poll";
1099
+ const modelKey = model === "quota-poll" ? account.quota[0]?.modelKey ?? model : model;
1071
1100
  const ctx = this.getFlagContext(account, modelKey);
1072
1101
  const lower = errorText.toLowerCase();
1073
1102
  const matchedPatterns = FLAG_PATTERNS.filter((p) => lower.includes(p));
1074
1103
  reportFlagEvent({
1075
1104
  flagHttpStatus: statusCode,
1105
+ ...extractFlagReason(errorText),
1076
1106
  flagPatternsMatched: matchedPatterns.length > 0 ? matchedPatterns : [],
1077
- model: "quota-poll",
1107
+ model,
1078
1108
  timerType: ctx.timerType as FlagEventData["timerType"],
1079
1109
  accountQuotaPercent: ctx.accountQuotaPercent,
1080
1110
  wasProAccount: ctx.wasProAccount,
@@ -4660,6 +4690,16 @@ export class AccountRotator {
4660
4690
  };
4661
4691
  }
4662
4692
 
4693
+ const denialKey = `${email}\0${target.upstreamModel}`;
4694
+ if ((this.kickstartDeniedUntil.get(denialKey) ?? 0) > Date.now()) {
4695
+ return {
4696
+ ok: false,
4697
+ status: 403,
4698
+ upstreamModel: target.upstreamModel,
4699
+ error: "kickstart temporarily skipped after model-specific 403",
4700
+ };
4701
+ }
4702
+
4663
4703
  try {
4664
4704
  await this.ensureValidTokenForProvider(account, target.providerId);
4665
4705
  } catch (err) {
@@ -4775,7 +4815,7 @@ export class AccountRotator {
4775
4815
  }
4776
4816
 
4777
4817
  let errorText = "";
4778
- if (response.status === 429) {
4818
+ if (response.status === 429 || response.status === 401 || response.status === 403) {
4779
4819
  errorText = await response.text().catch(() => "");
4780
4820
  } else {
4781
4821
  // Consume and discard the response body to free the connection.
@@ -4823,13 +4863,18 @@ export class AccountRotator {
4823
4863
  }
4824
4864
 
4825
4865
  if (response.status === 401 || response.status === 403) {
4826
- const reason = `kickstart ${response.status} on ${upstreamModel}`;
4866
+ const failure = describeKickstartAuthFailure(response.status, upstreamModel, errorText);
4827
4867
  if (target.providerId === "openai-codex") {
4828
- this.markProviderInvalid(account, target.providerId, reason);
4868
+ this.markProviderInvalid(account, target.providerId, failure.description);
4869
+ } else if (failure.accountEnforcement) {
4870
+ this.reportQuotaPollFlag(account, response.status, errorText, upstreamModel);
4871
+ this.markFlagged(account, failure.description, { triggerProtectivePause: false });
4829
4872
  } else {
4830
- this.markFlagged(account, reason, { triggerProtectivePause: false });
4873
+ account.lastError = failure.description;
4874
+ this.kickstartDeniedUntil.set(denialKey, Date.now() + 30 * 60 * 1000);
4875
+ this.log(`${label}: ${failure.description}; retrying kickstart after 30 minutes`, "warn");
4831
4876
  }
4832
- return { ok: false, status: response.status, upstreamModel };
4877
+ return { ok: false, status: response.status, upstreamModel, error: failure.description };
4833
4878
  }
4834
4879
 
4835
4880
  if (response.status >= 500) {
package/src/telemetry.ts CHANGED
@@ -60,6 +60,34 @@ export const FLAG_PATTERNS = [
60
60
  ] as const;
61
61
  export type FlagPattern = typeof FLAG_PATTERNS[number];
62
62
 
63
+ /** Keep provider reasons useful for diagnosis without sending raw errors or links. */
64
+ export function extractFlagReason(errorText: string): {
65
+ flagReasonCode?: string;
66
+ flagReasonMessage?: string;
67
+ } {
68
+ let code: unknown;
69
+ let message: unknown;
70
+ try {
71
+ const parsed = JSON.parse(errorText) as {
72
+ error?: { status?: unknown; message?: unknown; details?: Array<{ reason?: unknown }> };
73
+ };
74
+ code = parsed.error?.details?.find((detail) => typeof detail?.reason === "string")?.reason
75
+ ?? parsed.error?.status;
76
+ message = parsed.error?.message;
77
+ } catch {
78
+ message = errorText;
79
+ }
80
+ const flagReasonCode = typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code)
81
+ ? code : undefined;
82
+ const rawMessage = typeof message === "string" ? message.trim().replace(/\s+/g, " ") : "";
83
+ // Provider errors can include verification URLs, account addresses, and tokens.
84
+ const flagReasonMessage = rawMessage &&
85
+ !/(?:https?:\/\/|@|bearer\s|access[_ -]?token|refresh[_ -]?token|api[_ -]?key)/i.test(rawMessage)
86
+ ? rawMessage.slice(0, 160) : undefined;
87
+ return { ...(flagReasonCode ? { flagReasonCode } : {}),
88
+ ...(flagReasonMessage ? { flagReasonMessage } : {}) };
89
+ }
90
+
63
91
  // ── Version ──────────────────────────────────────────────────────────
64
92
  let _version: string | null = null;
65
93
  function getVersion(): string {
@@ -206,12 +234,14 @@ export interface TelemetryPayload {
206
234
  // This is the most important telemetry signal — it drives anti-flag
207
235
  // algorithm improvements that benefit all users.
208
236
  //
209
- // NO PII in the payload: no email, no error text, no projectId, no request body.
210
- // Only structured, anonymous context about what happened.
237
+ // NO PII in the payload: no email, raw error body, projectId, or request body.
238
+ // Reason code and bounded message are filtered before transmission.
211
239
  export interface FlagEventData {
212
240
  // What triggered it
213
241
  flagHttpStatus: number; // 401 or 403
214
242
  flagPatternsMatched: FlagPattern[]; // which known patterns matched
243
+ flagReasonCode?: string; // upstream reason, e.g. VALIDATION_REQUIRED
244
+ flagReasonMessage?: string; // bounded message after privacy filtering
215
245
 
216
246
  // What was happening
217
247
  model: string; // model key being requested
package/src/types.ts CHANGED
@@ -196,9 +196,7 @@ export const MAX_QUOTA_POLL_INTERVAL_MS = 24 * 60 * 60 * 1000;
196
196
  const DEFAULT_MODEL_ALIASES: Record<string, string> = {
197
197
  "gemini-3.1-pro-high": "gemini-pro-agent",
198
198
  "gpt-oss-120b": "gpt-oss-120b-medium",
199
- "whisper-1": "models/proactive-observer-v10",
200
- "proactive-observer": "models/proactive-observer-v10",
201
- "proactive-observer-v10": "models/proactive-observer-v10",
199
+ "whisper-1": "gemini-3.8-flash-low",
202
200
  };
203
201
  let modelAliasesOverride: Record<string, string> | null = null;
204
202
  type StoredEffortRoutingRule = {
@@ -605,6 +603,7 @@ export interface PersistedState {
605
603
  quotaExhaustedAt: number;
606
604
  disabled: boolean;
607
605
  flagged: boolean;
606
+ flagReason?: string | null;
608
607
  allowFreshWindowStartsOverride?: boolean;
609
608
  }
610
609
  >;
@@ -137,9 +137,11 @@ Each JSONL line:
137
137
  curl -H "Authorization: Bearer YOUR_STATS_TOKEN" https://telemetry.yourdomain.com/v1/stats | jq .
138
138
  ```
139
139
 
140
+ Flag events are also written to daily `-flags.jsonl` files. The protected stats response includes `flags.byReasonCode` and `flags.recentIncidents` (up to 50, with anonymous install ID, HTTP status, provider code, filtered message, and model). The protected `/dashboard` displays both the reason counts and recent incidents. Older flag events without a provider reason remain valid and appear as `UNKNOWN`.
141
+
140
142
  ## Security
141
143
 
142
- - **No PII is stored in telemetry event files**: no emails, tokens, project IDs, request bodies, or error text
144
+ - **No PII is stored in telemetry event files**: no emails, tokens, project IDs, request bodies, or raw error responses. Flag events can include a bounded provider reason code and filtered short message; messages containing links, account addresses, or credential markers are rejected.
143
145
  - Source IPs are used transiently for in-memory rate limiting and may be visible to your network, host, or reverse-proxy logs. The receiver does not write IPs into telemetry JSONL event files.
144
146
  - Email-pattern detection in validation: payloads containing `@` email patterns are rejected
145
147
  - Payloads capped at 4KB