tuxevil-rotator 4.2.2 → 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.
Files changed (84) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +11 -4
  3. package/package.json +2 -1
  4. package/plugins/opencode-discovery/capabilities.d.mts +7 -0
  5. package/plugins/opencode-discovery/capabilities.mjs +54 -0
  6. package/plugins/opencode-discovery/index.d.mts +2 -1
  7. package/plugins/opencode-discovery/index.mjs +6 -1
  8. package/plugins/opencode-discovery/package.json +3 -1
  9. package/src/access-evidence.ts +153 -0
  10. package/src/access-probe.ts +85 -0
  11. package/src/admin-auth.ts +4 -1
  12. package/src/audio-transcription.ts +32 -6
  13. package/src/auto-access-shadow.ts +11 -0
  14. package/src/auto-model-access.ts +185 -0
  15. package/src/auto-output-health.ts +12 -0
  16. package/src/auto-routing-evaluation.ts +80 -0
  17. package/src/auto-routing-quality.ts +308 -0
  18. package/src/auto-routing.ts +403 -26
  19. package/src/cli.ts +3 -3
  20. package/src/compat/model-specs.ts +4 -0
  21. package/src/compat.ts +253 -37
  22. package/src/compression/index.ts +6 -6
  23. package/src/compression/lite.ts +3 -9
  24. package/src/compression/rtk/index.ts +0 -3
  25. package/src/config-defaults.ts +7 -0
  26. package/src/dashboard-app.ts +1 -0
  27. package/src/dashboard.ts +5 -0
  28. package/src/db-store.ts +10 -0
  29. package/src/index.ts +2 -0
  30. package/src/install-agent.ts +211 -129
  31. package/src/install-opencode.ts +80 -18
  32. package/src/model-access-api.ts +74 -0
  33. package/src/model-access.ts +56 -0
  34. package/src/ollama-output-gate.ts +18 -0
  35. package/src/onboarding.ts +1 -1
  36. package/src/provider-catalog-evidence.ts +26 -0
  37. package/src/providers/google-antigravity/catalog.ts +14 -6
  38. package/src/providers/google-antigravity/dynamic-catalog.ts +87 -3
  39. package/src/providers/google-antigravity/forward.ts +4 -2
  40. package/src/providers/google-antigravity/quota.ts +7 -0
  41. package/src/providers/ollama/context-window.ts +13 -0
  42. package/src/providers/ollama/forward.ts +10 -0
  43. package/src/providers/ollama/quota.ts +4 -0
  44. package/src/providers/ollama/translators.ts +19 -2
  45. package/src/providers/openai-codex/catalog.ts +157 -18
  46. package/src/providers/openai-codex/compat.ts +5 -1
  47. package/src/providers/openai-codex/credentials.ts +22 -6
  48. package/src/providers/openai-codex/index.ts +9 -1
  49. package/src/providers/openai-codex/quota.ts +19 -6
  50. package/src/providers/opencode-zen/forward.ts +1 -1
  51. package/src/providers/opencode-zen/quota.ts +2 -0
  52. package/src/proxy.ts +113 -5
  53. package/src/quota-observation.ts +26 -0
  54. package/src/quota-pools.ts +322 -0
  55. package/src/rotator.ts +167 -40
  56. package/src/settings-repository.ts +1 -0
  57. package/src/types.ts +106 -29
  58. package/src/usage-limits-auth.ts +24 -0
  59. package/src/usage-limits.ts +148 -0
  60. package/src/validators.ts +26 -0
  61. package/src/web/app.tsx +4 -0
  62. package/src/web/components/icons.tsx +15 -0
  63. package/src/web/components/overlays.tsx +4 -0
  64. package/src/web/components/ui.tsx +9 -9
  65. package/src/web/lib/audio-recorder.ts +159 -0
  66. package/src/web/lib/colors.ts +4 -0
  67. package/src/web/lib/playground-storage.ts +261 -0
  68. package/src/web/lib/playground.ts +483 -0
  69. package/src/web/lib/pool-navigation.ts +4 -0
  70. package/src/web/lib/pools.ts +2 -243
  71. package/src/web/nav.ts +1 -0
  72. package/src/web/pages/AccountDetail.tsx +2 -1
  73. package/src/web/pages/ModelAccess.tsx +88 -0
  74. package/src/web/pages/Models.tsx +2 -0
  75. package/src/web/pages/Overview.tsx +26 -9
  76. package/src/web/pages/Playground.tsx +1692 -0
  77. package/src/web/pages/Transcription.tsx +562 -0
  78. package/src/web/state/api.ts +6 -0
  79. package/src/web/state/playground-client.ts +136 -0
  80. package/src/web/state/playground.ts +69 -0
  81. package/src/web/state/router.ts +2 -2
  82. package/src/web/state/transcription-client.ts +93 -0
  83. package/src/web/styles/app.css +501 -0
  84. package/tools/telemetry-receiver/receiver.js +59 -46
package/src/types.ts CHANGED
@@ -97,6 +97,8 @@ export interface AccountConfig {
97
97
  }
98
98
 
99
99
  export interface Config {
100
+ /** Log informational account/model policy comparisons without enforcing them. */
101
+ modelAccessShadow?: boolean;
100
102
  accounts: AccountConfig[];
101
103
  requestsPerRotation: number;
102
104
  proxyPort: number;
@@ -168,6 +170,17 @@ export interface Config {
168
170
  }
169
171
 
170
172
  export interface TypeSafeRoutingConfig {
173
+ /** Classify effort then select operationally from explicit pools; default model-choice. */
174
+ selectionPolicy?: "model-choice" | "effort-pools";
175
+ /** Restrict all selections, including fallback and affinity, to the union of configured pools. */
176
+ restrictToEffortPools?: boolean;
177
+ effortPools?: Partial<Record<"low" | "medium" | "high" | "max", string[]>>;
178
+ /** Reuse a valid model for tool continuations with metadata.session_id. */
179
+ sessionAffinity?: boolean;
180
+ /** Once per pinned task, seek a reasoning model after three consecutive tool errors. */
181
+ stallEscalation?: boolean;
182
+ /** Absolute pin lifetime, seconds; default 1800, maximum 86400. */
183
+ sessionAffinityTtlSeconds?: number;
171
184
  /** Explicit opt-in. When omitted, a configured apiKey enables the feature. */
172
185
  enabled?: boolean;
173
186
  /** TypeSafe API key. Persisted encrypted by the settings layer. */
@@ -344,7 +357,18 @@ export interface ModelSpecConfig {
344
357
  }
345
358
 
346
359
  // Per-model quota info for an account
360
+ /** Observability only: never an input to routing policy. Missing means unknown. */
361
+ export interface QuotaObservation {
362
+ observedAt: number;
363
+ percentageSource: "reported" | "derived" | "estimated" | "unknown";
364
+ remainingPercent: number | null;
365
+ resetSource: "reported" | "estimated" | "unknown";
366
+ resetAt: string | null;
367
+ catalogAccessible?: boolean;
368
+ }
369
+
347
370
  export interface ModelQuota {
371
+ observation?: QuotaObservation;
348
372
  modelKey: string;
349
373
  displayName: string;
350
374
  /** Owner of this quota pool when the account has several providers. */
@@ -432,6 +456,17 @@ export function resolveDisplayModelKey(
432
456
  if (lower.includes("-high")) return "gemini-3.1-pro-high";
433
457
  return "gemini-3.1-pro"; // unspecified variant
434
458
  }
459
+ // Gemini 4 Argon
460
+ if (
461
+ lower.includes("gemini") &&
462
+ lower.includes("4") &&
463
+ lower.includes("argon")
464
+ ) {
465
+ if (lower.includes("-low")) return "gemini-4-argon-low";
466
+ if (lower.includes("-medium")) return "gemini-4-argon-medium";
467
+ if (lower.includes("-high")) return "gemini-4-argon-high";
468
+ return "gemini-4-argon";
469
+ }
435
470
  // Gemini 3.8 Flash — Antigravity exposes separate reasoning-level ids.
436
471
  if (
437
472
  lower.includes("gemini") &&
@@ -555,7 +590,18 @@ export interface PersistedDynamicModelOwnership {
555
590
  >;
556
591
  }
557
592
 
593
+ export interface PersistedDynamicModelSnapshots {
594
+ version: 1;
595
+ accounts: Record<string, {
596
+ credentialGenerationFingerprint: string;
597
+ capturedAt: number;
598
+ models: import("./providers/google-antigravity/dynamic-catalog.js").DynamicModelEntry[];
599
+ defaultAgentModelId?: string;
600
+ }>;
601
+ }
602
+
558
603
  export interface PersistedState {
604
+ dynamicModelSnapshots?: PersistedDynamicModelSnapshots;
559
605
  // Historical dynamic model IDs mapped to their shared quota pools.
560
606
  dynamicModelQuotaPools?: Record<string, string>;
561
607
  // Exact account ownership for dynamically discovered model IDs.
@@ -837,7 +883,8 @@ export interface ModelPricing {
837
883
  cachingStoragePer1MPerHour?: number;
838
884
  }
839
885
 
840
- // Pricing per 1M tokens (USD) — what these would cost on paid APIs
886
+ // Pricing per 1M tokens (USD) — what these would cost on paid APIs.
887
+ // Source audit and estimation limits: docs/model-pricing.md (2026-10-25).
841
888
  export const MODEL_PRICING: Record<string, ModelPricing> = {
842
889
  "claude-opus-4-6-thinking": { inputPer1M: 5.0, outputPer1M: 25.0 },
843
890
  "claude-sonnet-4-6": { inputPer1M: 3.0, outputPer1M: 15.0 },
@@ -845,35 +892,37 @@ export const MODEL_PRICING: Record<string, ModelPricing> = {
845
892
  "gemini-3.1-pro-low": { inputPer1M: 2.0, outputPer1M: 12.0 },
846
893
  "gemini-3.1-pro-high": { inputPer1M: 2.0, outputPer1M: 12.0 },
847
894
  "gemini-3-flash": { inputPer1M: 0.5, outputPer1M: 3.0 },
895
+ // Standard introductory rates verified 2026-10-25; double on 2027-01-01.
896
+ // https://ai.google.dev/gemini-api/docs/pricing
848
897
  "gemini-3.6-flash": {
849
- inputPer1M: 1.5,
850
- outputPer1M: 7.5,
851
- cachingPer1M: 0.15,
852
- cachingStoragePer1MPerHour: 1.0,
898
+ inputPer1M: 0.75,
899
+ outputPer1M: 3.75,
900
+ cachingPer1M: 0.075,
901
+ cachingStoragePer1MPerHour: 0.5,
853
902
  },
854
903
  "gemini-3.6-flash-high": {
855
- inputPer1M: 1.5,
856
- outputPer1M: 7.5,
857
- cachingPer1M: 0.15,
858
- cachingStoragePer1MPerHour: 1.0,
904
+ inputPer1M: 0.75,
905
+ outputPer1M: 3.75,
906
+ cachingPer1M: 0.075,
907
+ cachingStoragePer1MPerHour: 0.5,
859
908
  },
860
909
  "gemini-3.6-flash-medium": {
861
- inputPer1M: 1.5,
862
- outputPer1M: 7.5,
863
- cachingPer1M: 0.15,
864
- cachingStoragePer1MPerHour: 1.0,
910
+ inputPer1M: 0.75,
911
+ outputPer1M: 3.75,
912
+ cachingPer1M: 0.075,
913
+ cachingStoragePer1MPerHour: 0.5,
865
914
  },
866
915
  "gemini-3.6-flash-low": {
867
- inputPer1M: 1.5,
868
- outputPer1M: 7.5,
869
- cachingPer1M: 0.15,
870
- cachingStoragePer1MPerHour: 1.0,
916
+ inputPer1M: 0.75,
917
+ outputPer1M: 3.75,
918
+ cachingPer1M: 0.075,
919
+ cachingStoragePer1MPerHour: 0.5,
871
920
  },
872
921
  "gemini-3.6-flash-tiered": {
873
- inputPer1M: 1.5,
874
- outputPer1M: 7.5,
875
- cachingPer1M: 0.15,
876
- cachingStoragePer1MPerHour: 1.0,
922
+ inputPer1M: 0.75,
923
+ outputPer1M: 3.75,
924
+ cachingPer1M: 0.075,
925
+ cachingStoragePer1MPerHour: 0.5,
877
926
  },
878
927
  // Gemini 3.7 Flash tiered — public Gemini API equivalent-value pricing,
879
928
  // verified on the official Gemini API / Google Cloud pricing pages
@@ -888,7 +937,7 @@ export const MODEL_PRICING: Record<string, ModelPricing> = {
888
937
  cachingStoragePer1MPerHour: 0.5,
889
938
  },
890
939
  // Gemini 3.8 Flash — introductory public Gemini API pricing verified
891
- // 2026-09-02. These rates double on 2027-01-01. Antigravity exposes
940
+ // 2026-10-25. These rates double on 2027-01-01. Antigravity exposes
892
941
  // separate low/medium/high model ids.
893
942
  "gemini-3.8-flash-low": {
894
943
  inputPer1M: 0.75,
@@ -908,10 +957,32 @@ export const MODEL_PRICING: Record<string, ModelPricing> = {
908
957
  cachingPer1M: 0.075,
909
958
  cachingStoragePer1MPerHour: 0.5,
910
959
  },
960
+ // Standard rates through 2026-11-30; then 4/20/0.2. Implicit cache only.
961
+ // https://ai.google.dev/gemini-api/docs/pricing (verified 2026-10-25).
962
+ "gemini-4-argon": {
963
+ inputPer1M: 2.0,
964
+ outputPer1M: 10.0,
965
+ cachingPer1M: 0.1,
966
+ },
967
+ "gemini-4-argon-low": {
968
+ inputPer1M: 2.0,
969
+ outputPer1M: 10.0,
970
+ cachingPer1M: 0.1,
971
+ },
972
+ "gemini-4-argon-medium": {
973
+ inputPer1M: 2.0,
974
+ outputPer1M: 10.0,
975
+ cachingPer1M: 0.1,
976
+ },
977
+ "gemini-4-argon-high": {
978
+ inputPer1M: 2.0,
979
+ outputPer1M: 10.0,
980
+ cachingPer1M: 0.1,
981
+ },
911
982
  "gpt-oss-120b-medium": { inputPer1M: 2.0, outputPer1M: 10.0 },
912
983
 
913
984
  // OpenAI Codex API-equivalent standard rates, checked against
914
- // https://developers.openai.com/api/docs/pricing on 2026-09-22.
985
+ // https://developers.openai.com/api/docs/pricing on 2026-10-25.
915
986
  // Spend logs use aggregate input/output tokens;
916
987
  // cache rates are metadata and are not applied separately.
917
988
  "gpt-6-astra": {
@@ -929,10 +1000,11 @@ export const MODEL_PRICING: Record<string, ModelPricing> = {
929
1000
  outputPer1M: 0.5,
930
1001
  cachingPer1M: 0.01,
931
1002
  },
1003
+ // Promotional pricing available at least through 2026-11-21.
932
1004
  "gpt-5.6-sol": {
933
- inputPer1M: 5.0,
934
- outputPer1M: 30.0,
935
- cachingPer1M: 0.50,
1005
+ inputPer1M: 4.0,
1006
+ outputPer1M: 20.0,
1007
+ cachingPer1M: 0.40,
936
1008
  },
937
1009
  "gpt-5.6-terra": {
938
1010
  inputPer1M: 2.0,
@@ -945,7 +1017,7 @@ export const MODEL_PRICING: Record<string, ModelPricing> = {
945
1017
  cachingPer1M: 0.02,
946
1018
  },
947
1019
 
948
- // Ollama Cloud standard USD/1M rates, verified 2026-10-11:
1020
+ // Ollama Cloud standard USD/1M rates, verified 2026-10-25:
949
1021
  // https://ollama.com/pricing. Aggregates do not track cache hits or off-peak
950
1022
  // billing, so savings represent standard list-price value, not a net saving.
951
1023
  "gpt-oss:20b": { inputPer1M: 0.07, outputPer1M: 0.30, cachingPer1M: 0.035 },
@@ -1034,7 +1106,9 @@ export function getModelPricing(model: string): ModelPricing | undefined {
1034
1106
  // "free" = served on the free tier; "subscription" = requires a paid plan.
1035
1107
  export type ModelTierAccess = "free" | "subscription";
1036
1108
  export const MODEL_TIER_ACCESS: Record<string, ModelTierAccess> = {
1109
+ // Free-credit list refreshed from operator-provided Ollama list, 2026-10-30.
1037
1110
  // ── Free tier (HTTP 200 on free accounts) ───────────────────────────────
1111
+ "beam": "free",
1038
1112
  "gpt-oss:20b": "free",
1039
1113
  "gpt-oss:120b": "free",
1040
1114
  "gemma4:31b": "free",
@@ -1042,6 +1116,8 @@ export const MODEL_TIER_ACCESS: Record<string, ModelTierAccess> = {
1042
1116
  "nemotron-3-super": "free",
1043
1117
  "nemotron-3-ultra": "free",
1044
1118
  // ── Subscription tier (HTTP 402 on free accounts) ───────────────────────
1119
+ "deepseek-v4.1-flash:1017": "subscription",
1120
+ "minimax-m3.1-flash": "subscription",
1045
1121
  "deepseek-v4-flash:0731": "subscription",
1046
1122
  "deepseek-v4-pro:0813": "subscription",
1047
1123
  "glm-5.1": "subscription",
@@ -1111,9 +1187,10 @@ export const TAGS_CACHE_TTL_MS = 5 * 60 * 1000;
1111
1187
  export const ANTIGRAVITY_VERSION =
1112
1188
  rotatorEnv("ANTIGRAVITY_VERSION") ||
1113
1189
  process.env.PI_AI_ANTIGRAVITY_VERSION ||
1114
- "2.11.0";
1190
+ "2.26.0";
1115
1191
  export const DEFAULT_ANTIGRAVITY_USER_AGENT =
1116
- `antigravity/ide/${ANTIGRAVITY_VERSION} (aidev_client; os_type=darwin; arch=arm64)`;
1192
+ rotatorEnv("ANTIGRAVITY_USER_AGENT") ||
1193
+ `antigravity/hub/${ANTIGRAVITY_VERSION} (aidev_client; os_type=darwin; arch=arm64)`;
1117
1194
  export const QUOTA_USER_AGENT =
1118
1195
  rotatorEnv("QUOTA_USER_AGENT") ||
1119
1196
  DEFAULT_ANTIGRAVITY_USER_AGENT;
@@ -0,0 +1,24 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import type { IncomingMessage } from "node:http";
3
+
4
+ export function usageReadToken(): string | null {
5
+ return process.env.TUXEVIL_ROTATOR_USAGE_READ_TOKEN?.trim() || null;
6
+ }
7
+ export function isUsageReadToken(value: unknown): boolean {
8
+ const token = usageReadToken();
9
+ if (!token || typeof value !== "string") return false;
10
+ const expected = Buffer.from(token, "utf8");
11
+ const candidate = Buffer.from(value, "utf8");
12
+ return expected.length === candidate.length && timingSafeEqual(expected, candidate);
13
+ }
14
+ /** Reserve the read credential across conventional HTTP credential carriers. */
15
+ export function carriesUsageReadToken(req: Pick<IncomingMessage, "url" | "headers">): boolean {
16
+ for (const value of Object.values(req.headers)) {
17
+ for (const item of Array.isArray(value) ? value : [value]) {
18
+ if (typeof item === "string" && (isUsageReadToken(item.trim()) || isUsageReadToken(item.trim().replace(/^Bearer\s+/i, "").trim()))) return true;
19
+ }
20
+ }
21
+ try {
22
+ return [...new URL(req.url || "/", "http://localhost").searchParams.values()].some(value => isUsageReadToken(value.trim()));
23
+ } catch { return false; }
24
+ }
@@ -0,0 +1,148 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, writeFile, link, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import type { IncomingMessage, ServerResponse } from "node:http";
5
+ import type { DashboardOverview } from "./dashboard-types.js";
6
+ import { buildProviderGroups } from "./quota-pools.js";
7
+ import { isUsageReadToken, usageReadToken } from "./usage-limits-auth.js";
8
+ import { getConfiguredAdminToken } from "./admin-auth.js";
9
+ import { getConfigDir } from "./paths.js";
10
+
11
+ export const USAGE_LIMITS_PATH = "/api/usage-limits/v1";
12
+
13
+ /** Atomic publication avoids partial identities across simultaneous processes. */
14
+ export async function loadUsageInstanceId(directory: string): Promise<string> {
15
+ await mkdir(directory, { recursive: true });
16
+ const path = join(directory, "usage-limits-instance-id");
17
+ try { return validateIdentity(await readFile(path, "utf8")); }
18
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
19
+ const id = randomUUID();
20
+ const temporary = `${path}.${randomUUID()}.tmp`;
21
+ await writeFile(temporary, id + "\n", { mode: 0o600, flag: "wx" });
22
+ try {
23
+ try { await link(temporary, path); }
24
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
25
+ } finally { await unlink(temporary); }
26
+ return validateIdentity(await readFile(path, "utf8"));
27
+ }
28
+ function validateIdentity(text: string): string {
29
+ const id = text.trim();
30
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id)) throw new Error("Invalid installation identity");
31
+ return id;
32
+ }
33
+
34
+ export interface UsageLimitsPoolV1 {
35
+ id: string;
36
+ scope: "pool" | "provider";
37
+ name: string;
38
+ providerId: string;
39
+ knowledge: "known" | "unknown" | "not-applicable";
40
+ remainingPercent: number | null;
41
+ quotaCoverage: { knownAccounts: number; totalAccounts: number };
42
+ partialObservation: {
43
+ remainingPercent: number;
44
+ accountsWithQuota: number;
45
+ percentageBasis: "tier-estimate" | "included-credits";
46
+ observedAt: number | null;
47
+ freshness: "fresh" | "stale" | "unknown";
48
+ } | null;
49
+ percentageBasis: "tier-estimate" | "included-credits" | "unknown";
50
+ accountsWithQuota: number | null;
51
+ accountsEligible: number | null;
52
+ accountsConsidered: number;
53
+ availability: "available" | "unavailable" | "unknown";
54
+ nextResetAt: number | null;
55
+ resetBasis: "reported" | "estimated" | "unknown";
56
+ observedAt: number | null;
57
+ freshness: "fresh" | "stale" | "unknown";
58
+ quotaUnit: "usd" | "percent" | "unknown";
59
+ credits: { balanceUsd: number; allowanceUsd: number; purchasedUsd: number } | null;
60
+ catalogAccessible: boolean | null;
61
+ }
62
+
63
+ /** Explicit aggregate allowlist. Never serialize a ModelPool or ModelQuota. */
64
+ export function buildUsageLimitsSnapshot(overview: DashboardOverview, instanceId: string, now: number) {
65
+ return {
66
+ schemaVersion: 1 as const,
67
+ instanceId,
68
+ generatedAt: now,
69
+ pools: buildProviderGroups(overview, now).flatMap<UsageLimitsPoolV1>(group => group.pools.length ? group.pools.map(pool => ({
70
+ id: pool.id,
71
+ scope: "pool" as const,
72
+ name: pool.name,
73
+ providerId: pool.provider,
74
+ knowledge: pool.observedCapacity === null ? "unknown" as const : "known" as const,
75
+ remainingPercent: pool.observedCapacity,
76
+ quotaCoverage: { knownAccounts: pool.quotaCoverage.knownAccounts, totalAccounts: pool.quotaCoverage.totalAccounts },
77
+ partialObservation: pool.partialObservation ? {
78
+ remainingPercent: pool.partialObservation.remainingPercent,
79
+ accountsWithQuota: pool.partialObservation.accountsWithQuota,
80
+ percentageBasis: pool.partialObservation.percentageBasis,
81
+ observedAt: pool.partialObservation.observedAt,
82
+ freshness: pool.partialObservation.freshness,
83
+ } : null,
84
+ percentageBasis: pool.capacityBasis,
85
+ accountsWithQuota: pool.observedWithQuota,
86
+ accountsEligible: pool.eligibleNow,
87
+ accountsConsidered: pool.members.length,
88
+ availability: pool.eligibleNow === null ? "unknown" as const : pool.eligibleNow > 0 ? "available" as const : "unavailable" as const,
89
+ nextResetAt: pool.observedNextResetAt,
90
+ resetBasis: pool.resetBasis,
91
+ observedAt: pool.observedAt,
92
+ freshness: pool.freshness,
93
+ quotaUnit: pool.credits ? "usd" as const : pool.observedCapacity === null ? "unknown" as const : "percent" as const,
94
+ credits: pool.observedCapacity !== null && pool.credits ? {
95
+ balanceUsd: pool.credits.balanceUsd,
96
+ allowanceUsd: pool.credits.allowanceUsd,
97
+ purchasedUsd: pool.credits.purchasedUsd,
98
+ } : null,
99
+ catalogAccessible: pool.catalogAccessible,
100
+ })) : [{
101
+ scope: "provider" as const,
102
+ id: JSON.stringify([group.provider, null]), name: group.provider, providerId: group.provider,
103
+ quotaCoverage: { knownAccounts: 0, totalAccounts: group.accounts.length }, partialObservation: null,
104
+ knowledge: "unknown" as const, remainingPercent: null, percentageBasis: "unknown" as const,
105
+ accountsWithQuota: null, accountsEligible: null, accountsConsidered: group.accounts.length,
106
+ availability: "unknown" as const, nextResetAt: null, resetBasis: "unknown" as const,
107
+ observedAt: null, freshness: "unknown" as const, quotaUnit: "unknown" as const,
108
+ credits: null, catalogAccessible: null,
109
+ }]),
110
+ };
111
+ }
112
+ export type UsageLimitsSnapshotV1 = ReturnType<typeof buildUsageLimitsSnapshot>;
113
+
114
+ /** Per-server short cache coalesces readers. Reads local state only; never polls. */
115
+ export function createUsageLimitsHandler(readOverview: () => DashboardOverview, directory = () => getConfigDir()) {
116
+ let pending: Promise<string> | null = null;
117
+ let cached: { expires: number; body: string } | null = null;
118
+ return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
119
+ const send = (status: number, body: string) => {
120
+ if (res.destroyed) return;
121
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
122
+ res.end(body);
123
+ };
124
+ const auth = req.headers.authorization;
125
+ if (!usageReadToken() || usageReadToken() === getConfiguredAdminToken() || typeof auth !== "string" ||
126
+ !/^Bearer /i.test(auth) || !isUsageReadToken(auth.slice(7)) || (req.url || "").includes("?")) {
127
+ send(401, '{"error":"unauthorized"}'); return;
128
+ }
129
+ if (req.method !== "GET") { res.setHeader("Allow", "GET"); send(405, '{"error":"method_not_allowed"}'); return; }
130
+ try {
131
+ pending ??= loadUsageInstanceId(directory()).catch(error => { pending = null; throw error; });
132
+ let timer: ReturnType<typeof setTimeout> | undefined;
133
+ let id: string;
134
+ try {
135
+ id = await Promise.race([pending, new Promise<never>((_, reject) => {
136
+ timer = setTimeout(() => reject(new Error("Identity timeout")), 5000);
137
+ })]);
138
+ } finally { clearTimeout(timer); }
139
+ const now = Date.now();
140
+ if (!cached || now >= cached.expires) {
141
+ const body = JSON.stringify(buildUsageLimitsSnapshot(readOverview(), id, now));
142
+ if (Buffer.byteLength(body) > 1024 * 1024) throw new Error("Snapshot too large");
143
+ cached = { expires: now + 1000, body };
144
+ }
145
+ send(200, cached.body);
146
+ } catch { send(503, '{"error":"snapshot_unavailable"}'); }
147
+ };
148
+ }
package/src/validators.ts CHANGED
@@ -315,11 +315,37 @@ export function validateConfig(value: unknown): ValidationResult<Config> {
315
315
  }
316
316
  }
317
317
  }
318
+ if (value.modelAccessShadow !== undefined && typeof value.modelAccessShadow !== "boolean") errors.push("config.modelAccessShadow must be a boolean");
318
319
  if (value.typesafeRouting !== undefined) {
319
320
  if (!isRecord(value.typesafeRouting)) {
320
321
  errors.push("config.typesafeRouting must be an object when provided");
321
322
  } else {
322
323
  const routing = value.typesafeRouting;
324
+ if (routing.restrictToEffortPools !== undefined && typeof routing.restrictToEffortPools !== "boolean") errors.push("config.typesafeRouting.restrictToEffortPools must be a boolean");
325
+ if (routing.restrictToEffortPools === true && routing.selectionPolicy !== "effort-pools") errors.push("restrictToEffortPools requires effort-pools selectionPolicy");
326
+ if (routing.selectionPolicy !== undefined && !["model-choice", "effort-pools"].includes(String(routing.selectionPolicy))) {
327
+ errors.push("config.typesafeRouting.selectionPolicy must be model-choice or effort-pools");
328
+ }
329
+ if (routing.effortPools !== undefined || routing.selectionPolicy === "effort-pools") {
330
+ if (!isRecord(routing.effortPools)) {
331
+ errors.push("config.typesafeRouting.effortPools must be an object");
332
+ } else {
333
+ for (const [effort, pool] of Object.entries(routing.effortPools)) {
334
+ if (!["low", "medium", "high", "max"].includes(effort) || !Array.isArray(pool) || pool.length === 0 || pool.length > 128 || pool.some(id => typeof id !== "string" || !/^[^/\s]+\/.+/.test(id))) {
335
+ errors.push("config.typesafeRouting.effortPools must contain nonempty pools of provider/model IDs for low, medium, high or max");
336
+ }
337
+ }
338
+ }
339
+ }
340
+ if (routing.stallEscalation !== undefined && typeof routing.stallEscalation !== "boolean") {
341
+ errors.push("config.typesafeRouting.stallEscalation must be a boolean");
342
+ }
343
+ if (routing.sessionAffinity !== undefined && typeof routing.sessionAffinity !== "boolean") {
344
+ errors.push("config.typesafeRouting.sessionAffinity must be a boolean");
345
+ }
346
+ if (routing.sessionAffinityTtlSeconds !== undefined && (!isNonNegativeInteger(routing.sessionAffinityTtlSeconds) || routing.sessionAffinityTtlSeconds < 1 || routing.sessionAffinityTtlSeconds > 86400)) {
347
+ errors.push("config.typesafeRouting.sessionAffinityTtlSeconds must be an integer between 1 and 86400");
348
+ }
323
349
  if (routing.enabled !== undefined && typeof routing.enabled !== "boolean") {
324
350
  errors.push("config.typesafeRouting.enabled must be a boolean");
325
351
  }
package/src/web/app.tsx CHANGED
@@ -34,6 +34,7 @@ import { ModelsPage } from "./pages/Models.js";
34
34
  import { RequestsPage } from "./pages/Requests.js";
35
35
  import { UsagePage } from "./pages/Usage.js";
36
36
  import { KeysPage } from "./pages/Keys.js";
37
+ import { PlaygroundPage } from "./pages/Playground.js";
37
38
  import { SettingsPage } from "./pages/Settings.js";
38
39
  import { openAddAccount } from "./pages/shared.js";
39
40
 
@@ -137,6 +138,9 @@ function Shell(): JSX.Element {
137
138
  case "keys":
138
139
  page = <KeysPage />;
139
140
  break;
141
+ case "playground":
142
+ page = <PlaygroundPage />;
143
+ break;
140
144
  case "settings":
141
145
  page = <SettingsPage />;
142
146
  break;
@@ -177,6 +177,21 @@ const PATHS = {
177
177
  </>
178
178
  ),
179
179
  play: <path d="M7 4.5v15l12-7.5z" />,
180
+ stop: <rect x="6" y="6" width="12" height="12" rx="2" />,
181
+ mic: (
182
+ <>
183
+ <rect x="9" y="2" width="6" height="13" rx="3" />
184
+ <path d="M19 10v2a7 7 0 0 1-14 0v-2" />
185
+ <path d="M12 19v3" />
186
+ </>
187
+ ),
188
+ image: (
189
+ <>
190
+ <rect x="3" y="3" width="18" height="18" rx="2" />
191
+ <circle cx="9" cy="9" r="2" />
192
+ <path d="m21 15-3.09-3.09a2 2 0 0 0-2.82 0L6 21" />
193
+ </>
194
+ ),
180
195
  pause: (
181
196
  <>
182
197
  <path d="M7 4h3v16H7z" />
@@ -215,6 +215,7 @@ export function Menu({
215
215
  trigger,
216
216
  triggerClass,
217
217
  header,
218
+ disabled,
218
219
  }: {
219
220
  label: string;
220
221
  icon?: IconName;
@@ -226,6 +227,8 @@ export function Menu({
226
227
  trigger?: ComponentChildren;
227
228
  triggerClass?: string;
228
229
  header?: ComponentChildren;
230
+ /** Disables the trigger, e.g. when none of the items can be used. */
231
+ disabled?: boolean;
229
232
  }): JSX.Element {
230
233
  const layer = useAnchoredLayer(placement, "button:not([disabled])");
231
234
 
@@ -248,6 +251,7 @@ export function Menu({
248
251
  aria-expanded={layer.open}
249
252
  aria-label={text ? undefined : label}
250
253
  title={trigger ? undefined : label}
254
+ disabled={disabled}
251
255
  onClick={layer.toggle}
252
256
  >
253
257
  {trigger ?? (
@@ -318,23 +318,23 @@ export function Meter({
318
318
  tone,
319
319
  size = "md",
320
320
  }: {
321
- value: number;
321
+ value: number | null;
322
322
  label: string;
323
323
  tone?: Tone;
324
324
  size?: "sm" | "md";
325
325
  }): JSX.Element {
326
- const clamped = Math.max(0, Math.min(100, Math.round(value)));
327
- const resolved = tone ?? quotaTone(clamped);
326
+ const clamped = value === null ? null : Math.max(0, Math.min(100, Math.round(value)));
327
+ const resolved = clamped === null ? "neutral" : tone ?? quotaTone(clamped);
328
328
  return (
329
329
  <span
330
- class={`meter meter-${size} tone-${resolved}`}
331
- role="meter"
332
- aria-valuemin={0}
333
- aria-valuemax={100}
334
- aria-valuenow={clamped}
330
+ class={`meter meter-${size} tone-${resolved}${clamped === null ? " meter-unknown" : ""}`}
331
+ role={clamped === null ? "img" : "meter"}
332
+ aria-valuemin={clamped === null ? undefined : 0}
333
+ aria-valuemax={clamped === null ? undefined : 100}
334
+ aria-valuenow={clamped ?? undefined}
335
335
  aria-label={label}
336
336
  >
337
- <span class="meter-fill" style={{ width: `${clamped}%` }} />
337
+ {clamped !== null && <span class="meter-fill" style={{ width: `${clamped}%` }} />}
338
338
  </span>
339
339
  );
340
340
  }