tuxevil-rotator 3.7.2 → 3.9.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
@@ -15,6 +15,20 @@ export interface KeyAuthResult {
15
15
  statusCode?: number;
16
16
  }
17
17
 
18
+ /** Checks a resolved model against the optional virtual-key model scope. */
19
+ export function isVirtualKeyModelAllowed(
20
+ key: VirtualKey | null,
21
+ targetModel: string,
22
+ ): boolean {
23
+ if (!key?.models || key.models.length === 0 || key.models.includes("*")) return true;
24
+ const normalizedTarget = targetModel.toLowerCase();
25
+ return key.models.some(
26
+ (model) =>
27
+ model.toLowerCase() === normalizedTarget ||
28
+ normalizedTarget.includes(model.toLowerCase()),
29
+ );
30
+ }
31
+
18
32
  /**
19
33
  * Extracts virtual key raw string from headers or query parameters.
20
34
  */
@@ -110,20 +124,7 @@ export async function authenticateVirtualKey(
110
124
  }
111
125
 
112
126
  // Model access restrictions
113
- if (
114
- targetModel &&
115
- key.models &&
116
- key.models.length > 0 &&
117
- !key.models.includes("*")
118
- ) {
119
- const normalizedTarget = targetModel.toLowerCase();
120
- const isAllowed = key.models.some(
121
- (m) =>
122
- m.toLowerCase() === normalizedTarget ||
123
- normalizedTarget.includes(m.toLowerCase()),
124
- );
125
-
126
- if (!isAllowed) {
127
+ if (targetModel && !isVirtualKeyModelAllowed(key, targetModel)) {
127
128
  return {
128
129
  authenticated: false,
129
130
  key,
@@ -131,7 +132,6 @@ export async function authenticateVirtualKey(
131
132
  error: `Model '${targetModel}' is not allowed for this Virtual Key`,
132
133
  statusCode: 403,
133
134
  };
134
- }
135
135
  }
136
136
 
137
137
  touchVirtualKeyLastActive(key.tokenHash);
package/src/onboarding.ts CHANGED
@@ -31,10 +31,17 @@ import {
31
31
  parseCodexIdentity,
32
32
  type CodexOAuthConfig,
33
33
  } from "./providers/openai-codex/oauth.js";
34
- import type { AccountConfig } from "./types.js";
34
+ import type { AccountConfig, Config } from "./types.js";
35
35
 
36
36
  interface AccountSink {
37
37
  addOrUpdateAccount(account: AccountConfig): Promise<void>;
38
+ getConfig?(): Config;
39
+ replaceConfig?(config: Config): Promise<void>;
40
+ }
41
+
42
+ interface TypeSafeConfigSink {
43
+ getConfig(): Config;
44
+ replaceConfig(config: Config): Promise<void>;
38
45
  }
39
46
 
40
47
  interface PendingSession {
@@ -303,8 +310,14 @@ function pruneCliSessions(): void {
303
310
  }
304
311
  }
305
312
 
306
- export function serveCliLogin(res: ServerResponse): void {
313
+ export function serveCliLogin(
314
+ res: ServerResponse,
315
+ configSource?: Pick<TypeSafeConfigSink, "getConfig">,
316
+ ): void {
307
317
  pruneCliSessions();
318
+ const currentTypeSafe = configSource?.getConfig().typesafeRouting;
319
+ const typeSafeConfigured = Boolean(currentTypeSafe?.apiKey);
320
+ const typeSafeModel = currentTypeSafe?.model || "jev-latest";
308
321
  const { verifier, challenge } = generatePkce();
309
322
  const oauthState = generateState();
310
323
  let authUrl: string | null = null;
@@ -358,6 +371,7 @@ export function serveCliLogin(res: ServerResponse): void {
358
371
  <button class="tab" data-panel="panel-codex">OpenAI Codex</button>
359
372
  <button class="tab" data-panel="panel-ollama">Ollama Cloud</button>
360
373
  <button class="tab" data-panel="panel-zen">OpenCode Zen</button>
374
+ <button class="tab" data-panel="panel-typesafe">TypeSafe Jev</button>
361
375
  </div>
362
376
 
363
377
  <div class="panel active" id="panel-google">
@@ -432,6 +446,28 @@ ${codexAuthUrl && codexSessionId ? `<h3 style="margin:24px 0 8px;font-size:18px;
432
446
  </form>
433
447
  </div>
434
448
 
449
+ <div class="panel" id="panel-typesafe">
450
+ <p>Configure TypeSafe Jev for optional <code>model: "auto"</code> routing. The key is stored encrypted with the rotator configuration in PostgreSQL when a database is configured.</p>
451
+ <p class="mono">${typeSafeConfigured ? "A Jev key is already configured. Leave the key field empty to keep it." : "No Jev key is configured yet."}</p>
452
+ <form id="typesafeForm" style="margin-top:12px;">
453
+ <label for="typesafeApiKey">TypeSafe API key</label>
454
+ <input id="typesafeApiKey" name="apiKey" class="field" type="password" placeholder="Paste a new TypeSafe API key" autocomplete="new-password" />
455
+ <label for="typesafeModel">Jev model</label>
456
+ <input id="typesafeModel" name="model" class="field" value="${escapeHtml(typeSafeModel)}" placeholder="jev-latest" autocomplete="off" />
457
+ <label style="display:flex;align-items:center;gap:8px;margin-top:16px;">
458
+ <input name="enabled" type="checkbox" ${currentTypeSafe?.enabled !== false ? "checked" : ""} />
459
+ Enable Jev when requests use <code>model: "auto"</code>
460
+ </label>
461
+ <label style="display:flex;align-items:flex-start;gap:8px;margin-top:12px;">
462
+ <input name="shadowMode" type="checkbox" ${currentTypeSafe?.shadowMode ? "checked" : ""} />
463
+ <span>Shadow mode: log Jev's recommendation, but keep serving the deterministic model. Logs contain model IDs and decision metadata only, not prompts.</span>
464
+ </label>
465
+ <button type="submit" class="cta" style="cursor:pointer;border:none;font-family:inherit;font-size:16px;margin-top:16px;">
466
+ Save Jev configuration
467
+ </button>
468
+ </form>
469
+ </div>
470
+
435
471
  <div id="result" style="margin-top:18px;"></div>
436
472
 
437
473
  <script>
@@ -617,6 +653,50 @@ if (zenForm) zenForm.addEventListener('submit', async (e) => {
617
653
  btn.textContent = 'Connect Account';
618
654
  }
619
655
  });
656
+
657
+ const typesafeForm = document.getElementById('typesafeForm');
658
+ if (typesafeForm) typesafeForm.addEventListener('submit', async (e) => {
659
+ e.preventDefault();
660
+ const form = e.target;
661
+ const btn = form.querySelector('button[type=submit]');
662
+ const apiKey = form.apiKey.value.trim();
663
+ const model = form.model.value.trim();
664
+ const enabled = form.enabled.checked;
665
+ const shadowMode = form.shadowMode.checked;
666
+ if (!model) { showResult('<div class="note error">Please enter a Jev model alias.</div>'); return; }
667
+ btn.disabled = true;
668
+ btn.textContent = 'Saving...';
669
+ showResult('<div class="note">Saving the encrypted Jev configuration...</div>');
670
+ try {
671
+ const params = new URLSearchParams(window.location.search);
672
+ const token = params.get('token') || '';
673
+ const payload = { provider: 'typesafe', ...(apiKey ? { apiKey } : {}), model, enabled, shadowMode };
674
+ const res = await fetch('/api/cli-login', {
675
+ method: 'POST',
676
+ headers: { 'Content-Type': 'application/json', ...(token ? { 'X-Rotator-Admin-Token': token } : {}) },
677
+ body: JSON.stringify(payload),
678
+ });
679
+ const data = await res.json();
680
+ if (data.ok) {
681
+ showResult('<div class="note" style="border-left-color:var(--accent);background:rgba(30,107,82,0.12);">TypeSafe Jev configuration saved. The API key is not returned by the server.</div>');
682
+ } else {
683
+ const errorDiv = document.createElement('div');
684
+ errorDiv.className = 'note error';
685
+ errorDiv.textContent = data.error || 'Unable to save TypeSafe configuration';
686
+ document.getElementById('result').innerHTML = '';
687
+ document.getElementById('result').appendChild(errorDiv);
688
+ }
689
+ } catch (err) {
690
+ const errorDiv = document.createElement('div');
691
+ errorDiv.className = 'note error';
692
+ errorDiv.textContent = 'Request failed: ' + err.message;
693
+ document.getElementById('result').innerHTML = '';
694
+ document.getElementById('result').appendChild(errorDiv);
695
+ } finally {
696
+ btn.disabled = false;
697
+ btn.textContent = 'Save Jev configuration';
698
+ }
699
+ });
620
700
  </script>
621
701
  `,
622
702
  ),
@@ -634,6 +714,9 @@ export async function handleCliLoginApi(
634
714
  redirectUrl?: string;
635
715
  email?: string;
636
716
  apiKey?: string;
717
+ model?: string;
718
+ enabled?: boolean;
719
+ shadowMode?: boolean;
637
720
  };
638
721
  try {
639
722
  const raw = await readLimitedBody(req, MAX_CLI_LOGIN_BODY_BYTES);
@@ -647,6 +730,9 @@ export async function handleCliLoginApi(
647
730
  redirectUrl?: string;
648
731
  email?: string;
649
732
  apiKey?: string;
733
+ model?: string;
734
+ enabled?: boolean;
735
+ shadowMode?: boolean;
650
736
  };
651
737
  } catch (err) {
652
738
  res.writeHead(err instanceof PayloadTooLargeError ? 413 : 400, {
@@ -673,6 +759,25 @@ export async function handleCliLoginApi(
673
759
  return;
674
760
  }
675
761
 
762
+ if (provider === "typesafe") {
763
+ if (
764
+ typeof rotator.getConfig !== "function" ||
765
+ typeof rotator.replaceConfig !== "function"
766
+ ) {
767
+ res.writeHead(500, { "Content-Type": "application/json" });
768
+ res.end(JSON.stringify({
769
+ ok: false,
770
+ error: "TypeSafe configuration is unavailable on this server",
771
+ }));
772
+ return;
773
+ }
774
+ await handleTypeSafeCliLogin(body, res, {
775
+ getConfig: () => rotator.getConfig!(),
776
+ replaceConfig: (config) => rotator.replaceConfig!(config),
777
+ });
778
+ return;
779
+ }
780
+
676
781
  if (provider !== "google-antigravity") {
677
782
  res.writeHead(400, { "Content-Type": "application/json" });
678
783
  res.end(JSON.stringify({ ok: false, error: `Unknown provider "${provider}"` }));
@@ -791,6 +896,88 @@ export async function handleCliLoginApi(
791
896
  }
792
897
  }
793
898
 
899
+ async function handleTypeSafeCliLogin(
900
+ body: { apiKey?: string; model?: string; enabled?: boolean; shadowMode?: boolean },
901
+ res: ServerResponse,
902
+ rotator: TypeSafeConfigSink,
903
+ ): Promise<void> {
904
+ if (body.apiKey !== undefined && typeof body.apiKey !== "string") {
905
+ res.writeHead(400, { "Content-Type": "application/json" });
906
+ res.end(JSON.stringify({ ok: false, error: "Invalid apiKey" }));
907
+ return;
908
+ }
909
+ if (body.model !== undefined && typeof body.model !== "string") {
910
+ res.writeHead(400, { "Content-Type": "application/json" });
911
+ res.end(JSON.stringify({ ok: false, error: "Invalid Jev model" }));
912
+ return;
913
+ }
914
+ if (body.enabled !== undefined && typeof body.enabled !== "boolean") {
915
+ res.writeHead(400, { "Content-Type": "application/json" });
916
+ res.end(JSON.stringify({ ok: false, error: "Invalid enabled flag" }));
917
+ return;
918
+ }
919
+ if (body.shadowMode !== undefined && typeof body.shadowMode !== "boolean") {
920
+ res.writeHead(400, { "Content-Type": "application/json" });
921
+ res.end(JSON.stringify({ ok: false, error: "Invalid shadow mode flag" }));
922
+ return;
923
+ }
924
+
925
+ const apiKey = body.apiKey?.trim() ?? "";
926
+ const model = body.model?.trim() ?? "";
927
+ const enabled = body.enabled ?? true;
928
+ if (apiKey.length > 4096) {
929
+ res.writeHead(400, { "Content-Type": "application/json" });
930
+ res.end(JSON.stringify({ ok: false, error: "API key too long" }));
931
+ return;
932
+ }
933
+ if (!model || model.length > 128) {
934
+ res.writeHead(400, { "Content-Type": "application/json" });
935
+ res.end(JSON.stringify({ ok: false, error: "Invalid Jev model" }));
936
+ return;
937
+ }
938
+
939
+ const current = rotator.getConfig();
940
+ const currentRouting = current.typesafeRouting ?? {};
941
+ const shadowMode = body.shadowMode ?? currentRouting.shadowMode ?? false;
942
+ if (!apiKey && !currentRouting.apiKey) {
943
+ res.writeHead(400, { "Content-Type": "application/json" });
944
+ res.end(JSON.stringify({ ok: false, error: "Missing TypeSafe API key" }));
945
+ return;
946
+ }
947
+
948
+ const nextConfig: Config = {
949
+ ...current,
950
+ typesafeRouting: {
951
+ ...currentRouting,
952
+ ...(apiKey ? { apiKey } : {}),
953
+ enabled,
954
+ model,
955
+ shadowMode,
956
+ },
957
+ };
958
+
959
+ try {
960
+ await rotator.replaceConfig(nextConfig);
961
+ } catch (error) {
962
+ const message = error instanceof Error ? error.message : "";
963
+ const userError = /ENCRYPTION_KEY/i.test(message)
964
+ ? "Configure TUXEVIL_ROTATOR_ENCRYPTION_KEY before saving the Jev key."
965
+ : "Unable to save TypeSafe configuration.";
966
+ res.writeHead(500, { "Content-Type": "application/json" });
967
+ res.end(JSON.stringify({ ok: false, error: userError }));
968
+ return;
969
+ }
970
+
971
+ res.writeHead(200, { "Content-Type": "application/json" });
972
+ res.end(JSON.stringify({
973
+ ok: true,
974
+ configured: true,
975
+ enabled,
976
+ shadowMode,
977
+ model,
978
+ }));
979
+ }
980
+
794
981
  async function handleCodexCliLogin(
795
982
  body: { session?: string; redirectUrl?: string },
796
983
  res: ServerResponse,
@@ -330,7 +330,14 @@ export async function forwardRequest(
330
330
  // of truth: src/types.ts:applyModelAlias)
331
331
  body.model = applyModelAlias(body.model);
332
332
 
333
- const { displayModel: _displayModel, ...bodyToForward } = body;
333
+ const {
334
+ displayModel: _displayModel,
335
+ providerId: _providerId,
336
+ selectionMode: _selectionMode,
337
+ selectionConfidence: _selectionConfidence,
338
+ selectionReason: _selectionReason,
339
+ ...bodyToForward
340
+ } = body;
334
341
  const requestBody = JSON.stringify(bodyToForward);
335
342
 
336
343
  // Build headers: keep originals but swap Authorization
@@ -13,20 +13,22 @@ export interface CodexModel {
13
13
  source: "allowlist" | "discovered";
14
14
  }
15
15
 
16
- // Only models validated by the initial unauthenticated/public spike are in the
17
- // safe base list. Authenticated discovery can add provider-owned GPT-5 IDs.
16
+ // The base list contains OpenAI models published in the Codex model catalog.
17
+ // Authenticated discovery can add provider-owned GPT-5 and GPT-6 IDs.
18
18
  // The Codex /models endpoint can expose models from other ChatGPT-backed
19
19
  // providers (for example Claude), so model IDs alone must be filtered before
20
20
  // they influence routing.
21
- // Official context window for the GPT-5.6 family per
22
- // https://platform.openai.com/docs/models (gpt-5.6-sol / gpt-5.6-terra / gpt-5.6-luna
23
- // each report 1.05M context / 128K max output).
21
+ // Official context window for GPT-5.6 and GPT-6 Astra, Sol, and Luna per their
22
+ // OpenAI model pages (1.05M context / 128K max output).
24
23
  const CODEX_CONTEXT_WINDOW = 1_050_000;
25
24
  // Hard cap to defend against `/models` upstream reporting absurd values for
26
25
  // discovered ids. 2M is comfortably above the published 1.05M baseline.
27
26
  const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
28
- const CODEX_DISCOVERED_ID_PATTERN = /^gpt-5(?:\.\d+)?(?:-[a-z0-9]+)+$/i;
27
+ const CODEX_DISCOVERED_ID_PATTERN = /^gpt-(?:5(?:\.\d+)?|6)(?:-[a-z0-9]+)+$/i;
29
28
  export const CODEX_BASE_MODELS: readonly CodexModel[] = [
29
+ { id: "gpt-6-astra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
30
+ { id: "gpt-6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
31
+ { id: "gpt-6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
30
32
  { id: "gpt-5.6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
31
33
  { id: "gpt-5.6-terra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
32
34
  { id: "gpt-5.6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
@@ -37,6 +37,11 @@ export interface CodexCompatOptions {
37
37
  apiKeyHash?: string | null;
38
38
  requesterIp?: string | null;
39
39
  rawRequest?: unknown;
40
+ providerId?: string;
41
+ requestedModel?: string;
42
+ selectionMode?: "typesafe" | "deterministic" | "shadow" | "disabled";
43
+ selectionConfidence?: number;
44
+ selectionReason?: string;
40
45
  }
41
46
 
42
47
  function recordCodexTokenUsage(
@@ -357,7 +362,7 @@ function codexResponseJson(
357
362
  };
358
363
  }
359
364
 
360
- function upstreamHeaders(response: Response, context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number }, model: string): Record<string, string> {
365
+ function upstreamHeaders(response: Response, context: RotationAttemptContext, model: string): Record<string, string> {
361
366
  const headers: Record<string, string> = {};
362
367
  response.headers.forEach((value, key) => {
363
368
  if (key !== "connection" && key !== "transfer-encoding" && key !== "content-length") headers[key] = value;
@@ -365,6 +370,11 @@ function upstreamHeaders(response: Response, context: { account?: { healthScore:
365
370
  Object.assign(headers, buildRotatorResponseHeaders({
366
371
  accountLabel: context.label,
367
372
  model,
373
+ requestedModel: context.requestedModel,
374
+ selectedProvider: context.providerId,
375
+ modelSelection: context.selectionMode,
376
+ selectionConfidence: context.selectionConfidence,
377
+ selectionReason: context.selectionReason,
368
378
  ttfbMs: Date.now() - context.requestStartMs,
369
379
  healthScore: context.account?.healthScore,
370
380
  retries: context.retries,
@@ -377,7 +387,7 @@ async function pipeNativeResponses(
377
387
  response: Response,
378
388
  req: IncomingMessage,
379
389
  res: ServerResponse,
380
- context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
390
+ context: RotationAttemptContext,
381
391
  model: string,
382
392
  ): Promise<CompatCompletion> {
383
393
  res.writeHead(response.status, upstreamHeaders(response, context, model));
@@ -435,7 +445,7 @@ async function pipeCodexAsChat(
435
445
  req: IncomingMessage,
436
446
  res: ServerResponse,
437
447
  model: string,
438
- context: { account?: { healthScore: number }; requestStartMs: number; label: string; retries: number },
448
+ context: RotationAttemptContext,
439
449
  ): Promise<CompatCompletion> {
440
450
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive", ...upstreamHeaders(response, context, model) });
441
451
  const id = `chatcmpl-${Date.now().toString(36)}`;
@@ -520,7 +530,16 @@ export async function serveCodexResponses(
520
530
  request: OpenAIResponsesRequest,
521
531
  options?: CodexCompatOptions,
522
532
  ): Promise<void> {
523
- const body: RequestBody = { project: "", model: request.model, request: buildCodexPayload({ project: "", model: request.model, request }) };
533
+ const body: RequestBody = {
534
+ project: "",
535
+ model: request.model,
536
+ request: buildCodexPayload({ project: "", model: request.model, request }),
537
+ ...(options?.providerId ? { providerId: options.providerId } : {}),
538
+ ...(options?.requestedModel ? { displayModel: options.requestedModel } : {}),
539
+ ...(options?.selectionMode ? { selectionMode: options.selectionMode } : {}),
540
+ ...(options?.selectionConfidence !== undefined ? { selectionConfidence: options.selectionConfidence } : {}),
541
+ ...(options?.selectionReason ? { selectionReason: options.selectionReason } : {}),
542
+ };
524
543
  const controller = new AbortController();
525
544
  const abort = (): void => controller.abort();
526
545
  req.once("aborted", abort);
@@ -567,7 +586,16 @@ export async function serveCodexChat(
567
586
  options?: CodexCompatOptions,
568
587
  ): Promise<void> {
569
588
  const codexRequest = chatToCodexResponsesRequest(request);
570
- const body: RequestBody = { project: "", model: request.model, request: codexRequest };
589
+ const body: RequestBody = {
590
+ project: "",
591
+ model: request.model,
592
+ request: codexRequest,
593
+ ...(options?.providerId ? { providerId: options.providerId } : {}),
594
+ ...(options?.requestedModel ? { displayModel: options.requestedModel } : {}),
595
+ ...(options?.selectionMode ? { selectionMode: options.selectionMode } : {}),
596
+ ...(options?.selectionConfidence !== undefined ? { selectionConfidence: options.selectionConfidence } : {}),
597
+ ...(options?.selectionReason ? { selectionReason: options.selectionReason } : {}),
598
+ };
571
599
  const controller = new AbortController();
572
600
  const abort = (): void => controller.abort();
573
601
  req.once("aborted", abort);
@@ -63,8 +63,19 @@ export function isKnownProvider(providerId: string): boolean {
63
63
 
64
64
  export function findProviderForModel(
65
65
  model: string,
66
- context?: { ollamaModels?: Set<string>; codexModels?: Set<string> },
66
+ context?: {
67
+ ollamaModels?: Set<string>;
68
+ codexModels?: Set<string>;
69
+ providerId?: string;
70
+ },
67
71
  ): ProviderAdapter | null {
72
+ if (context?.providerId) {
73
+ try {
74
+ return getProviderAdapter(context.providerId);
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
68
79
  // Check non-default explicit providers first to prevent Google fallback overlap
69
80
  for (const adapter of [opencodeZenAdapter, openaiCodexAdapter, ollamaAdapter, googleAntigravityAdapter]) {
70
81
  if (adapter.ownsModel?.(model, context)) {