tuxevil-rotator 3.9.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.
- package/CHANGELOG.md +35 -7
- package/README.md +3 -1
- package/package.json +3 -2
- package/plugins/opencode-discovery.d.ts +65 -0
- package/plugins/opencode-discovery.js +174 -0
- package/src/audio-transcription.ts +1265 -117
- package/src/cli.ts +130 -0
- package/src/compat/model-specs.ts +59 -58
- package/src/compat/schema-sanitizer.ts +11 -3
- package/src/compat.ts +4 -4
- package/src/index.ts +39 -1
- package/src/install-agent.ts +453 -0
- package/src/install-opencode.ts +201 -0
- package/src/key-auth.ts +69 -5
- package/src/providers/google-antigravity/dynamic-catalog.ts +1 -1
- package/src/providers/google-antigravity/translators.ts +16 -0
- package/src/proxy.ts +36 -3
- package/src/rotator.ts +52 -7
- package/src/telemetry.ts +32 -2
- package/src/types.ts +2 -3
- package/tools/telemetry-receiver/README.md +3 -1
- package/tools/telemetry-receiver/receiver.js +36 -0
package/src/key-auth.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import type
|
|
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
|
|
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
|
-
|
|
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 '${
|
|
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
|
}
|
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
|
-
|
|
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 ??
|
|
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
|
|
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
|
|
4866
|
+
const failure = describeKickstartAuthFailure(response.status, upstreamModel, errorText);
|
|
4827
4867
|
if (target.providerId === "openai-codex") {
|
|
4828
|
-
this.markProviderInvalid(account, target.providerId,
|
|
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
|
-
|
|
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,
|
|
210
|
-
//
|
|
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": "
|
|
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
|
|
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
|
|
@@ -213,6 +213,9 @@ function isFlagPayload(data) {
|
|
|
213
213
|
if (typeof flag.protectivePauseTriggered !== "boolean") return false;
|
|
214
214
|
if (typeof flag.uptimeSeconds !== "number") return false;
|
|
215
215
|
if (typeof flag.timeSinceLastFlagSeconds !== "number") return false;
|
|
216
|
+
if (flag.flagReasonCode !== undefined &&
|
|
217
|
+
(typeof flag.flagReasonCode !== "string" || !/^[A-Z][A-Z0-9_]{0,63}$/.test(flag.flagReasonCode))) return false;
|
|
218
|
+
if (flag.flagReasonMessage !== undefined && !isSafeFlagReasonMessage(flag.flagReasonMessage)) return false;
|
|
216
219
|
|
|
217
220
|
const serialized = JSON.stringify(data);
|
|
218
221
|
if (serialized.includes("@") && /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]/.test(serialized)) {
|
|
@@ -222,6 +225,11 @@ function isFlagPayload(data) {
|
|
|
222
225
|
return true;
|
|
223
226
|
}
|
|
224
227
|
|
|
228
|
+
function isSafeFlagReasonMessage(message) {
|
|
229
|
+
return typeof message === "string" && message.length > 0 && message.length <= 160 &&
|
|
230
|
+
!/(?:https?:\/\/|@|bearer\s|access[_ -]?token|refresh[_ -]?token|api[_ -]?key)/i.test(message);
|
|
231
|
+
}
|
|
232
|
+
|
|
225
233
|
function isValidPayload(data) {
|
|
226
234
|
if (typeof data !== "object" || data === null) return false;
|
|
227
235
|
if (!ALLOWED_EVENTS.has(data.event)) return false;
|
|
@@ -283,6 +291,10 @@ function sanitizeFlagData(flag) {
|
|
|
283
291
|
]);
|
|
284
292
|
return {
|
|
285
293
|
flagHttpStatus: typeof flag.flagHttpStatus === "number" ? flag.flagHttpStatus : 0,
|
|
294
|
+
...(typeof flag.flagReasonCode === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(flag.flagReasonCode)
|
|
295
|
+
? { flagReasonCode: flag.flagReasonCode } : {}),
|
|
296
|
+
...(isSafeFlagReasonMessage(flag.flagReasonMessage)
|
|
297
|
+
? { flagReasonMessage: flag.flagReasonMessage } : {}),
|
|
286
298
|
flagPatternsMatched: Array.isArray(flag.flagPatternsMatched)
|
|
287
299
|
? flag.flagPatternsMatched.filter((p) => ALLOWED_PATTERNS.has(p))
|
|
288
300
|
: [],
|
|
@@ -636,6 +648,7 @@ function computeStats(filters = {}) {
|
|
|
636
648
|
|
|
637
649
|
// Flag aggregates
|
|
638
650
|
const flagsByStatus = Object.create(null);
|
|
651
|
+
const flagsByReasonCode = Object.create(null);
|
|
639
652
|
const flagsByPattern = Object.create(null);
|
|
640
653
|
const flagsByModel = Object.create(null);
|
|
641
654
|
const flagsByTimerType = Object.create(null);
|
|
@@ -648,6 +661,8 @@ function computeStats(filters = {}) {
|
|
|
648
661
|
for (const { fl } of flagEvents) {
|
|
649
662
|
flagCount++;
|
|
650
663
|
flagsByStatus[fl.flagHttpStatus] = (flagsByStatus[fl.flagHttpStatus] || 0) + 1;
|
|
664
|
+
const reasonCode = fl.flagReasonCode || "UNKNOWN";
|
|
665
|
+
flagsByReasonCode[reasonCode] = (flagsByReasonCode[reasonCode] || 0) + 1;
|
|
651
666
|
for (const p of fl.flagPatternsMatched || []) flagsByPattern[p] = (flagsByPattern[p] || 0) + 1;
|
|
652
667
|
if (fl.model) flagsByModel[fl.model] = (flagsByModel[fl.model] || 0) + 1;
|
|
653
668
|
if (fl.timerType) flagsByTimerType[fl.timerType] = (flagsByTimerType[fl.timerType] || 0) + 1;
|
|
@@ -656,6 +671,7 @@ function computeStats(filters = {}) {
|
|
|
656
671
|
flagRequestsTotal += fl.accountTotalRequests || 0;
|
|
657
672
|
const signature = JSON.stringify({
|
|
658
673
|
status: fl.flagHttpStatus,
|
|
674
|
+
reasonCode: fl.flagReasonCode || "",
|
|
659
675
|
patterns: [...(fl.flagPatternsMatched || [])].sort(),
|
|
660
676
|
model: fl.model || "",
|
|
661
677
|
timerType: fl.timerType || "",
|
|
@@ -668,6 +684,19 @@ function computeStats(filters = {}) {
|
|
|
668
684
|
|
|
669
685
|
const avgRequestsBeforeFlag = flagCount > 0 ? Math.round(flagRequestsTotal / flagCount) : 0;
|
|
670
686
|
const uniqueFlagIncidents = uniqueFlagSignatures.size;
|
|
687
|
+
const recentIncidents = flagEvents
|
|
688
|
+
.map(({ fl }) => ({
|
|
689
|
+
installId: fl.installId,
|
|
690
|
+
ts: fl.ts,
|
|
691
|
+
receivedAt: fl.receivedAt,
|
|
692
|
+
flagHttpStatus: fl.flagHttpStatus,
|
|
693
|
+
flagReasonCode: fl.flagReasonCode || "UNKNOWN",
|
|
694
|
+
flagReasonMessage: fl.flagReasonMessage || "",
|
|
695
|
+
flagPatternsMatched: fl.flagPatternsMatched || [],
|
|
696
|
+
model: fl.model || "unknown",
|
|
697
|
+
}))
|
|
698
|
+
.sort((a, b) => String(b.receivedAt || b.ts).localeCompare(String(a.receivedAt || a.ts)))
|
|
699
|
+
.slice(0, 50);
|
|
671
700
|
|
|
672
701
|
// Build filter options from ALL events (unfiltered) for dropdown population
|
|
673
702
|
const filterOptions = buildFilterOptions(allEvents, allFlagEvents);
|
|
@@ -696,6 +725,8 @@ function computeStats(filters = {}) {
|
|
|
696
725
|
totalFlags: totalFlags + flagCount,
|
|
697
726
|
uniqueIncidents: uniqueFlagIncidents,
|
|
698
727
|
byHttpStatus: flagsByStatus,
|
|
728
|
+
byReasonCode: flagsByReasonCode,
|
|
729
|
+
recentIncidents,
|
|
699
730
|
byPattern: flagsByPattern,
|
|
700
731
|
byModel: flagsByModel,
|
|
701
732
|
byTimerType: flagsByTimerType,
|
|
@@ -1070,6 +1101,8 @@ table{width:100%;border-collapse:collapse;font-size:12px}th{text-align:left;padd
|
|
|
1070
1101
|
<div class="section-title"><div><div class="section-kicker">Safety signals</div><h2>Flag analysis</h2><p>Patterns that need operator attention.</p></div></div>
|
|
1071
1102
|
<div class="flag-kpis" id="flagKpis"></div>
|
|
1072
1103
|
<div class="charts"><div class="chart-box"><h2>By pattern</h2><canvas id="cPatterns"></canvas></div><div class="chart-box"><h2>By model</h2><canvas id="cFlagModels"></canvas></div><div class="chart-box"><h2>By timer type</h2><canvas id="cTimerType"></canvas></div></div>
|
|
1104
|
+
<div class="charts"><div class="chart-box"><h2>By provider reason</h2><canvas id="cFlagReasons"></canvas></div></div>
|
|
1105
|
+
<h3>Recent flag incidents</h3><div id="flagIncidents"></div>
|
|
1073
1106
|
</section>
|
|
1074
1107
|
<section class="section">
|
|
1075
1108
|
<div class="section-title"><div><div class="section-kicker">Consumption</div><h2>Token usage by model</h2><p>Input, output and request volume for the selected cohort.</p></div></div>
|
|
@@ -1255,8 +1288,11 @@ function render(d, filters={}){
|
|
|
1255
1288
|
{l:'Avg Requests Before Flag',v:fmt(fl.avgRequestsBeforeFlag||0)},
|
|
1256
1289
|
].map(k=>'<div class="flag-kpi"><div class="label">'+esc(k.l)+'</div><div class="value">'+esc(k.v)+'</div></div>').join('');
|
|
1257
1290
|
mkChart('cPatterns','bar',Object.keys(fl.byPattern||{}),[{label:'Count',data:Object.values(fl.byPattern||{}),backgroundColor:R}]);
|
|
1291
|
+
mkChart('cFlagReasons','bar',Object.keys(fl.byReasonCode||{}),[{label:'Count',data:Object.values(fl.byReasonCode||{}),backgroundColor:R}]);
|
|
1258
1292
|
mkChart('cFlagModels','doughnut',Object.keys(fl.byModel||{}),[{data:Object.values(fl.byModel||{}),backgroundColor:C}]);
|
|
1259
1293
|
mkChart('cTimerType','doughnut',Object.keys(fl.byTimerType||{}),[{data:Object.values(fl.byTimerType||{}),backgroundColor:['#63b3ed','#f6e05e','#68d391']}]);
|
|
1294
|
+
const incidentRows=(fl.recentIncidents||[]).map(i=>'<tr><td>'+esc(i.receivedAt||i.ts||'—')+'</td><td class="mono">'+esc(i.installId||'—')+'</td><td>'+esc(i.flagHttpStatus||'—')+'</td><td class="mono">'+esc(i.flagReasonCode||'UNKNOWN')+'</td><td>'+esc(i.flagReasonMessage||'—')+'</td><td class="mono">'+esc(i.model||'—')+'</td></tr>').join('');
|
|
1295
|
+
$('flagIncidents').innerHTML=incidentRows?'<div style="overflow-x:auto"><table><thead><tr><th>Received</th><th>Install</th><th>HTTP</th><th>Provider reason</th><th>Provider message</th><th>Model</th></tr></thead><tbody>'+incidentRows+'</tbody></table></div>':'<div class="empty">No flag incidents yet</div>';
|
|
1260
1296
|
|
|
1261
1297
|
const tk=d.tokensByModel||{};
|
|
1262
1298
|
$('tokTable').innerHTML=Object.keys(tk).length?'<table><thead><tr><th>Model</th><th>Input Tokens</th><th>Output Tokens</th><th>Requests</th></tr></thead><tbody>'+Object.entries(tk).map(([m,v])=>'<tr><td class="mono">'+esc(m)+'</td><td>'+fmt(v.input)+'</td><td>'+fmt(v.output)+'</td><td>'+fmt(v.requests)+'</td></tr>').join('')+'</tbody></table>':'<div class="empty">No token data yet</div>';
|