tuxevil-rotator 4.3.0 → 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.
- package/CHANGELOG.md +21 -0
- package/README.md +4 -2
- package/package.json +2 -1
- package/src/access-evidence.ts +153 -0
- package/src/access-probe.ts +85 -0
- package/src/admin-auth.ts +4 -1
- package/src/auto-access-shadow.ts +11 -0
- package/src/auto-model-access.ts +185 -0
- package/src/auto-output-health.ts +12 -0
- package/src/auto-routing-evaluation.ts +80 -0
- package/src/auto-routing-quality.ts +308 -0
- package/src/auto-routing.ts +403 -26
- package/src/compat.ts +223 -36
- package/src/compression/index.ts +6 -6
- package/src/compression/lite.ts +3 -9
- package/src/compression/rtk/index.ts +0 -3
- package/src/config-defaults.ts +7 -0
- package/src/dashboard.ts +5 -0
- package/src/db-store.ts +10 -0
- package/src/index.ts +2 -0
- package/src/model-access-api.ts +74 -0
- package/src/model-access.ts +56 -0
- package/src/ollama-output-gate.ts +18 -0
- package/src/onboarding.ts +1 -1
- package/src/provider-catalog-evidence.ts +26 -0
- package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
- package/src/providers/google-antigravity/quota.ts +3 -0
- package/src/providers/ollama/context-window.ts +13 -0
- package/src/providers/ollama/quota.ts +4 -0
- package/src/providers/ollama/translators.ts +19 -2
- package/src/providers/openai-codex/compat.ts +5 -1
- package/src/providers/openai-codex/credentials.ts +22 -6
- package/src/providers/openai-codex/index.ts +9 -1
- package/src/providers/openai-codex/quota.ts +19 -6
- package/src/providers/opencode-zen/forward.ts +1 -1
- package/src/providers/opencode-zen/quota.ts +2 -0
- package/src/proxy.ts +78 -3
- package/src/quota-observation.ts +26 -0
- package/src/quota-pools.ts +322 -0
- package/src/rotator.ts +151 -38
- package/src/settings-repository.ts +1 -0
- package/src/types.ts +28 -0
- package/src/usage-limits-auth.ts +24 -0
- package/src/usage-limits.ts +148 -0
- package/src/validators.ts +26 -0
- package/src/web/components/icons.tsx +15 -0
- package/src/web/components/overlays.tsx +4 -0
- package/src/web/components/ui.tsx +9 -9
- package/src/web/lib/playground.ts +35 -0
- package/src/web/lib/pool-navigation.ts +4 -0
- package/src/web/lib/pools.ts +2 -243
- package/src/web/pages/AccountDetail.tsx +2 -1
- package/src/web/pages/ModelAccess.tsx +88 -0
- package/src/web/pages/Models.tsx +2 -0
- package/src/web/pages/Overview.tsx +26 -9
- package/src/web/pages/Playground.tsx +1132 -551
- package/src/web/pages/Transcription.tsx +304 -170
- package/src/web/state/api.ts +3 -0
- package/src/web/styles/app.css +501 -45
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 {
|
|
@@ -198,12 +202,18 @@ function authorizeResolvedAutoModel(
|
|
|
198
202
|
function buildAutoRoutingCatalog(
|
|
199
203
|
rotator: AccountRotator,
|
|
200
204
|
route: AutoRoutingRoute,
|
|
205
|
+
excludedCandidates: ReadonlySet<string> = new Set(),
|
|
201
206
|
): AutoRoutingCatalogEntry[] {
|
|
202
207
|
return buildAllAutoRoutingCandidates(rotator, route).filter((entry) =>
|
|
203
|
-
isModelServed(rotator, entry.providerId, entry.modelId)
|
|
208
|
+
isModelServed(rotator, entry.providerId, entry.modelId) &&
|
|
209
|
+
!excludedCandidates.has(autoCandidateKey(entry.providerId, entry.modelId)),
|
|
204
210
|
);
|
|
205
211
|
}
|
|
206
212
|
|
|
213
|
+
function autoCandidateKey(providerId: string, modelId: string): string {
|
|
214
|
+
return JSON.stringify([providerId, modelId]);
|
|
215
|
+
}
|
|
216
|
+
|
|
207
217
|
function buildAllAutoRoutingCandidates(
|
|
208
218
|
rotator: AccountRotator,
|
|
209
219
|
route: AutoRoutingRoute,
|
|
@@ -238,7 +248,7 @@ function buildAllAutoRoutingCandidates(
|
|
|
238
248
|
catalog.push({
|
|
239
249
|
providerId: "ollama",
|
|
240
250
|
modelId,
|
|
241
|
-
contextWindow:
|
|
251
|
+
contextWindow: getCachedOllamaContextWindow(modelId),
|
|
242
252
|
multimodal: false,
|
|
243
253
|
tools: true,
|
|
244
254
|
reasoning: false,
|
|
@@ -265,6 +275,8 @@ async function resolveAutoModel(
|
|
|
265
275
|
rotator: AccountRotator,
|
|
266
276
|
route: AutoRoutingRoute,
|
|
267
277
|
input: unknown,
|
|
278
|
+
auth: Awaited<ReturnType<typeof authenticateVirtualKey>>,
|
|
279
|
+
excludedCandidates: ReadonlySet<string> = new Set(),
|
|
268
280
|
): Promise<{
|
|
269
281
|
model: string;
|
|
270
282
|
providerId: string;
|
|
@@ -274,8 +286,8 @@ async function resolveAutoModel(
|
|
|
274
286
|
} | null> {
|
|
275
287
|
const selection = await selectAutoRoutingTarget(
|
|
276
288
|
rotator,
|
|
277
|
-
buildAutoRoutingCatalog(rotator, route),
|
|
278
|
-
{ 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) },
|
|
279
291
|
);
|
|
280
292
|
if (!selection) return null;
|
|
281
293
|
return {
|
|
@@ -877,10 +889,14 @@ export async function streamCompatSse(
|
|
|
877
889
|
openaiToolCallIndex: number;
|
|
878
890
|
}
|
|
879
891
|
const openAiStreamingTools = new Map<number, OpenAiStreamingToolState>();
|
|
892
|
+
let ollamaChunks = 0, ollamaThinkingChars = 0, ollamaContentChars = 0, ollamaRawToolCalls = 0;
|
|
893
|
+
let ollamaTerminal = false;
|
|
880
894
|
const emitOllamaLine = (line: string): void => {
|
|
881
895
|
try {
|
|
882
896
|
const parsed = JSON.parse(line) as Record<string, unknown>;
|
|
897
|
+
ollamaChunks++;
|
|
883
898
|
if (parsed.done === true) {
|
|
899
|
+
ollamaTerminal = true;
|
|
884
900
|
if (typeof parsed.prompt_eval_count === "number")
|
|
885
901
|
inputTokens = parsed.prompt_eval_count;
|
|
886
902
|
if (typeof parsed.eval_count === "number")
|
|
@@ -888,6 +904,9 @@ export async function streamCompatSse(
|
|
|
888
904
|
}
|
|
889
905
|
const message = isRecord(parsed.message) ? parsed.message : null;
|
|
890
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;
|
|
891
910
|
const deltaText =
|
|
892
911
|
typeof message.content === "string" ? message.content : "";
|
|
893
912
|
if (deltaText) {
|
|
@@ -1354,6 +1373,11 @@ export async function streamCompatSse(
|
|
|
1354
1373
|
responseEvents.off?.("close", closeUpstreamForClient);
|
|
1355
1374
|
}
|
|
1356
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
|
+
}
|
|
1357
1381
|
if (!reqClosed && !res.writableEnded) {
|
|
1358
1382
|
if (streamError) {
|
|
1359
1383
|
writeCompatStreamError(res, format, streamError);
|
|
@@ -2361,6 +2385,7 @@ async function completeViaRotator(
|
|
|
2361
2385
|
rawRequest?: unknown;
|
|
2362
2386
|
rawResponse?: unknown;
|
|
2363
2387
|
compressionStats?: CompressionStats | null;
|
|
2388
|
+
autoRecoveryEnabled?: boolean;
|
|
2364
2389
|
},
|
|
2365
2390
|
): Promise<{
|
|
2366
2391
|
completion: CompatCompletion;
|
|
@@ -2396,6 +2421,12 @@ async function completeViaRotator(
|
|
|
2396
2421
|
: format === "ollama"
|
|
2397
2422
|
? parseOllamaNdjson(raw)
|
|
2398
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
|
+
}
|
|
2399
2430
|
if (completion.inputTokens > 0 || completion.outputTokens > 0) {
|
|
2400
2431
|
rotator.recordTokenUsage(
|
|
2401
2432
|
context.displayModelKey,
|
|
@@ -2414,8 +2445,22 @@ async function completeViaRotator(
|
|
|
2414
2445
|
);
|
|
2415
2446
|
return completion;
|
|
2416
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
|
+
}
|
|
2417
2462
|
const completion = await streamCompatSse(
|
|
2418
|
-
|
|
2463
|
+
upstreamBody,
|
|
2419
2464
|
req,
|
|
2420
2465
|
res,
|
|
2421
2466
|
body.displayModel?.toLowerCase() === "auto"
|
|
@@ -2447,36 +2492,42 @@ async function completeViaRotator(
|
|
|
2447
2492
|
}
|
|
2448
2493
|
},
|
|
2449
2494
|
controller.signal,
|
|
2495
|
+
{ autoRecovery: options?.autoRecoveryEnabled === true && body.displayModel?.toLowerCase() === "auto" },
|
|
2450
2496
|
);
|
|
2451
2497
|
|
|
2452
2498
|
let outcome: RotationOutcome<CompatCompletion>;
|
|
2453
2499
|
let isDeduplicated = false;
|
|
2454
2500
|
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
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);
|
|
2480
2531
|
}
|
|
2481
2532
|
|
|
2482
2533
|
if (!outcome.ok) {
|
|
@@ -2498,6 +2549,7 @@ async function completeViaRotator(
|
|
|
2498
2549
|
compressionStats: options?.compressionStats,
|
|
2499
2550
|
};
|
|
2500
2551
|
}
|
|
2552
|
+
if (outcome.result.streamError && !res.headersSent) return { completion: outcome.result, status: 502, errorText: outcome.result.streamError, streamed: false, context: outcome.context };
|
|
2501
2553
|
return {
|
|
2502
2554
|
completion: outcome.result,
|
|
2503
2555
|
status: 200,
|
|
@@ -2715,7 +2767,14 @@ export function buildOpenAIModelCatalog(
|
|
|
2715
2767
|
});
|
|
2716
2768
|
}
|
|
2717
2769
|
}
|
|
2718
|
-
|
|
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;
|
|
2719
2778
|
}
|
|
2720
2779
|
|
|
2721
2780
|
/** Keep one entry per id: the one owned by the provider its requests go to. */
|
|
@@ -2840,7 +2899,7 @@ export async function handleGeminiGenerateContent(
|
|
|
2840
2899
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
2841
2900
|
|
|
2842
2901
|
const autoSelection = autoRequested
|
|
2843
|
-
? await resolveAutoModel(rotator, "gemini", parsed)
|
|
2902
|
+
? await resolveAutoModel(rotator, "gemini", parsed, auth)
|
|
2844
2903
|
: null;
|
|
2845
2904
|
if (autoRequested && !autoSelection) {
|
|
2846
2905
|
return writeJson(res, 503, {
|
|
@@ -2961,15 +3020,103 @@ export async function handleOpenAIChatCompletions(
|
|
|
2961
3020
|
await handleChatCompletions(req, res, rotator, false);
|
|
2962
3021
|
}
|
|
2963
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
|
+
|
|
2964
3109
|
async function handleChatCompletions(
|
|
2965
3110
|
req: IncomingMessage,
|
|
2966
3111
|
res: ServerResponse,
|
|
2967
3112
|
rotator: AccountRotator,
|
|
2968
3113
|
dashboardAdmin: boolean,
|
|
3114
|
+
retryInput?: unknown,
|
|
3115
|
+
recoveryState?: AutoChatRecoveryState,
|
|
2969
3116
|
): Promise<void> {
|
|
2970
3117
|
let parsed: unknown;
|
|
2971
3118
|
try {
|
|
2972
|
-
parsed = await readJsonBody(req);
|
|
3119
|
+
parsed = retryInput ?? await readJsonBody(req);
|
|
2973
3120
|
} catch (err) {
|
|
2974
3121
|
if (err instanceof PayloadTooLargeError)
|
|
2975
3122
|
return writeJson(res, 413, {
|
|
@@ -3002,9 +3149,20 @@ async function handleChatCompletions(
|
|
|
3002
3149
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
3003
3150
|
|
|
3004
3151
|
const autoSelection = autoRequested
|
|
3005
|
-
? await resolveAutoModel(
|
|
3152
|
+
? await resolveAutoModel(
|
|
3153
|
+
rotator,
|
|
3154
|
+
"openai-chat",
|
|
3155
|
+
validation.value,
|
|
3156
|
+
auth,
|
|
3157
|
+
new Set(recoveryState?.failedCandidates ?? []),
|
|
3158
|
+
)
|
|
3006
3159
|
: null;
|
|
3007
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
|
+
}
|
|
3008
3166
|
return writeJson(res, 503, {
|
|
3009
3167
|
error: { message: "No compatible model is currently available", type: "upstream_error" },
|
|
3010
3168
|
});
|
|
@@ -3029,6 +3187,20 @@ async function handleChatCompletions(
|
|
|
3029
3187
|
selectionMode: autoSelection?.mode,
|
|
3030
3188
|
selectionConfidence: autoSelection?.confidence,
|
|
3031
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,
|
|
3032
3204
|
});
|
|
3033
3205
|
return;
|
|
3034
3206
|
}
|
|
@@ -3074,8 +3246,23 @@ async function handleChatCompletions(
|
|
|
3074
3246
|
requesterIp: req.socket?.remoteAddress || null,
|
|
3075
3247
|
rawRequest: validation.value,
|
|
3076
3248
|
compressionStats: compRes.stats,
|
|
3249
|
+
autoRecoveryEnabled: autoRequested,
|
|
3077
3250
|
},
|
|
3078
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
|
+
}
|
|
3079
3266
|
if (result.status !== 200) {
|
|
3080
3267
|
compatLogger.warn(
|
|
3081
3268
|
`OpenAI compat upstream failed status=${result.status} model=${validation.value.model}`,
|
|
@@ -3198,7 +3385,7 @@ export async function handleOpenAIResponsesCreate(
|
|
|
3198
3385
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
3199
3386
|
|
|
3200
3387
|
const autoSelection = autoRequested
|
|
3201
|
-
? await resolveAutoModel(rotator, "openai-responses", validation.value)
|
|
3388
|
+
? await resolveAutoModel(rotator, "openai-responses", validation.value, auth)
|
|
3202
3389
|
: null;
|
|
3203
3390
|
if (autoRequested && !autoSelection) {
|
|
3204
3391
|
return writeJson(res, 503, {
|
|
@@ -3511,7 +3698,7 @@ export async function handleAnthropicMessages(
|
|
|
3511
3698
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
3512
3699
|
|
|
3513
3700
|
const autoSelection = autoRequested
|
|
3514
|
-
? await resolveAutoModel(rotator, "anthropic", validation.value)
|
|
3701
|
+
? await resolveAutoModel(rotator, "anthropic", validation.value, auth)
|
|
3515
3702
|
: null;
|
|
3516
3703
|
if (autoRequested && !autoSelection) {
|
|
3517
3704
|
return writeJson(res, 503, {
|
package/src/compression/index.ts
CHANGED
|
@@ -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 =
|
package/src/compression/lite.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
|
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
|
|
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") {
|
package/src/config-defaults.ts
CHANGED
|
@@ -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,
|
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);
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { antigravityCatalogEvidence, advertisedModelState, type ProviderCatalogEvidence } from "./provider-catalog-evidence.js";
|
|
2
|
+
import { readLimitedBody } from "./body-limit.js";
|
|
3
|
+
import { isSettingsRepositoryInitialized } from "./db-store.js";
|
|
4
|
+
import { accessEvidenceStore, persistAccessEvidence, ACCESS_PLANS, type ProviderPlanEvidence, type AccessObservation } from "./access-evidence.js";
|
|
5
|
+
import type { ServerResponse, IncomingMessage } from "node:http";
|
|
6
|
+
import type { Config } from "./types.js";
|
|
7
|
+
import { getAccountIdentity } from "./account-identity.js";
|
|
8
|
+
import { MODEL_ACCESS_RULES, evaluateModelAccess, type AccessDecision } from "./model-access.js";
|
|
9
|
+
|
|
10
|
+
export interface AccessAccount { id: string; label: string; providers: string[]; inferredPlan: string; providerPlans: Omit<ProviderPlanEvidence, "credential">[]; observations: Omit<AccessObservation, "credential">[]; providerCatalogs: ProviderCatalogEvidence[] }
|
|
11
|
+
export interface AccessReport { informational: true; rules: typeof MODEL_ACCESS_RULES; accounts: AccessAccount[]; decision?: AccessDecision; accountId?: string; catalogAvailability?: { state: "advertised" | "not-advertised" | "unknown"; source: string | null; observedAt: number | null; expiresAt: number | null }; planSource?: "query-assumption" | "single-provider-account" | "provider-declaration" | "unknown" }
|
|
12
|
+
export function buildModelAccessReport(config: Config, params: URLSearchParams): AccessReport {
|
|
13
|
+
const accounts = config.accounts.map(account => {
|
|
14
|
+
const providers = [...new Set(account.credentials?.map(c => c.provider) ?? [account.provider ?? "google-antigravity"])];
|
|
15
|
+
// A shared account tier cannot establish each linked provider's subscription.
|
|
16
|
+
const tier = account.tier ?? account.type ?? "unknown";
|
|
17
|
+
const inferredPlan = providers.length === 1 && ["free", "plus", "ultra"].includes(tier) ? tier : "unknown";
|
|
18
|
+
const evidence = accessEvidenceStore().forAccount(account);
|
|
19
|
+
return { id: getAccountIdentity(account), label: account.label ?? account.email, providers, inferredPlan,
|
|
20
|
+
providerPlans: evidence.plans.map(({ credential: _credential, ...plan }) => plan),
|
|
21
|
+
providerCatalogs: providers.includes("google-antigravity") ? [antigravityCatalogEvidence(account, config.quotaPollIntervalMs)] : [],
|
|
22
|
+
observations: evidence.observations.map(({ credential: _credential, ...observation }) => observation) };
|
|
23
|
+
});
|
|
24
|
+
const report: AccessReport = { informational: true, rules: MODEL_ACCESS_RULES, accounts };
|
|
25
|
+
if (!params.has("model") && !params.has("provider") && !params.has("accountId")) return report;
|
|
26
|
+
const provider = params.get("provider"), model = params.get("model");
|
|
27
|
+
if (!provider || !model || model.length > 256) throw new Error("provider and model are required (model up to 256 characters)");
|
|
28
|
+
const accountId = params.get("accountId");
|
|
29
|
+
const account = accountId ? accounts.find(a => a.id === accountId) : undefined;
|
|
30
|
+
if (accountId && !account) throw new Error("Unknown account ID");
|
|
31
|
+
if (account && !account.providers.includes(provider)) throw new Error("Selected account does not have this provider");
|
|
32
|
+
const declared = account?.providerPlans.find(p => p.provider === provider);
|
|
33
|
+
const plan = params.get("plan") || declared?.plan || account?.inferredPlan || "unknown";
|
|
34
|
+
report.planSource = params.get("plan") ? "query-assumption" : declared ? "provider-declaration" : account?.inferredPlan !== "unknown" && account ? "single-provider-account" : "unknown";
|
|
35
|
+
report.accountId = accountId ?? undefined;
|
|
36
|
+
const catalog = account?.providerCatalogs.find(c => c.provider === provider);
|
|
37
|
+
report.catalogAvailability = { state: catalog ? advertisedModelState(catalog, model) : "unknown", source: catalog?.source ?? null, observedAt: catalog?.observedAt ?? null, expiresAt: catalog?.expiresAt ?? null };
|
|
38
|
+
report.decision = evaluateModelAccess({ provider, model, plan, client: params.get("client") ?? undefined, at: params.get("at") ?? undefined });
|
|
39
|
+
return report;
|
|
40
|
+
}
|
|
41
|
+
export function serveModelAccessApi(res: ServerResponse, config: Config, params: URLSearchParams): void {
|
|
42
|
+
res.setHeader("Cache-Control", "no-store");
|
|
43
|
+
try {
|
|
44
|
+
const report = buildModelAccessReport(config, params);
|
|
45
|
+
res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(report));
|
|
46
|
+
} catch {
|
|
47
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
48
|
+
res.end(JSON.stringify({ error: "Invalid access query. Check account, provider, model and date." }));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function validateProviderPlanDeclaration(config: Config, value: unknown) {
|
|
53
|
+
const body = value as { accountId?: unknown; provider?: unknown; plan?: unknown } | null;
|
|
54
|
+
if (!body || typeof body.accountId !== "string" || typeof body.provider !== "string" || typeof body.plan !== "string" || !ACCESS_PLANS.includes(body.plan)) throw new Error("Invalid declaration");
|
|
55
|
+
const account = config.accounts.find(a => getAccountIdentity(a) === body.accountId);
|
|
56
|
+
const providers = account?.credentials?.map(c => c.provider) ?? [account?.provider ?? "google-antigravity"];
|
|
57
|
+
if (!account || !providers.includes(body.provider)) throw new Error("Account/provider mismatch");
|
|
58
|
+
return { account, provider: body.provider, plan: body.plan };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function serveProviderPlanApi(req: IncomingMessage, res: ServerResponse, config: Config): Promise<void> {
|
|
62
|
+
res.setHeader("Cache-Control", "no-store");
|
|
63
|
+
try {
|
|
64
|
+
if (!isSettingsRepositoryInitialized()) throw new Error("Store not ready");
|
|
65
|
+
const body = JSON.parse((await readLimitedBody(req, 4096)).toString("utf8"));
|
|
66
|
+
const declaration = validateProviderPlanDeclaration(config, body);
|
|
67
|
+
accessEvidenceStore().declarePlan(declaration.account, declaration.provider, declaration.plan);
|
|
68
|
+
await persistAccessEvidence();
|
|
69
|
+
serveModelAccessApi(res, config, new URLSearchParams());
|
|
70
|
+
} catch {
|
|
71
|
+
if (!res.headersSent) res.writeHead(400, { "Content-Type": "application/json" });
|
|
72
|
+
res.end(JSON.stringify({ error: "Invalid declaration or evidence persistence unavailable." }));
|
|
73
|
+
}
|
|
74
|
+
}
|