tuxevil-rotator 4.3.0 → 4.4.1

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 (60) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +5 -2
  3. package/package.json +5 -1
  4. package/src/access-evidence.ts +153 -0
  5. package/src/access-probe.ts +85 -0
  6. package/src/admin-auth.ts +4 -1
  7. package/src/auto-access-shadow.ts +11 -0
  8. package/src/auto-model-access.ts +185 -0
  9. package/src/auto-output-health.ts +12 -0
  10. package/src/auto-routing-evaluation.ts +80 -0
  11. package/src/auto-routing-quality.ts +308 -0
  12. package/src/auto-routing.ts +403 -26
  13. package/src/compat.ts +223 -36
  14. package/src/compression/index.ts +6 -6
  15. package/src/compression/lite.ts +3 -9
  16. package/src/compression/rtk/index.ts +0 -3
  17. package/src/config-defaults.ts +7 -0
  18. package/src/dashboard.ts +5 -0
  19. package/src/db-store.ts +10 -0
  20. package/src/index.ts +2 -0
  21. package/src/model-access-api.ts +74 -0
  22. package/src/model-access.ts +56 -0
  23. package/src/ollama-output-gate.ts +18 -0
  24. package/src/onboarding.ts +1 -1
  25. package/src/provider-catalog-evidence.ts +26 -0
  26. package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
  27. package/src/providers/google-antigravity/quota.ts +3 -0
  28. package/src/providers/ollama/context-window.ts +13 -0
  29. package/src/providers/ollama/quota.ts +4 -0
  30. package/src/providers/ollama/translators.ts +19 -2
  31. package/src/providers/openai-codex/compat.ts +5 -1
  32. package/src/providers/openai-codex/credentials.ts +22 -6
  33. package/src/providers/openai-codex/index.ts +9 -1
  34. package/src/providers/openai-codex/quota.ts +19 -6
  35. package/src/providers/opencode-zen/forward.ts +1 -1
  36. package/src/providers/opencode-zen/quota.ts +2 -0
  37. package/src/proxy.ts +78 -3
  38. package/src/quota-observation.ts +26 -0
  39. package/src/quota-pools.ts +322 -0
  40. package/src/rotator.ts +151 -38
  41. package/src/settings-repository.ts +1 -0
  42. package/src/telemetry.ts +3 -1
  43. package/src/types.ts +28 -0
  44. package/src/usage-limits-auth.ts +24 -0
  45. package/src/usage-limits.ts +148 -0
  46. package/src/validators.ts +26 -0
  47. package/src/web/components/icons.tsx +15 -0
  48. package/src/web/components/overlays.tsx +4 -0
  49. package/src/web/components/ui.tsx +9 -9
  50. package/src/web/lib/playground.ts +35 -0
  51. package/src/web/lib/pool-navigation.ts +4 -0
  52. package/src/web/lib/pools.ts +2 -243
  53. package/src/web/pages/AccountDetail.tsx +2 -1
  54. package/src/web/pages/ModelAccess.tsx +88 -0
  55. package/src/web/pages/Models.tsx +2 -0
  56. package/src/web/pages/Overview.tsx +26 -9
  57. package/src/web/pages/Playground.tsx +1132 -551
  58. package/src/web/pages/Transcription.tsx +304 -170
  59. package/src/web/state/api.ts +3 -0
  60. package/src/web/styles/app.css +501 -45
package/src/rotator.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { summarizeAutoAccess } from "./auto-access-shadow.js";
2
+ import { evaluateAutoModelAccess, type AutoAccountScope } from "./auto-model-access.js";
3
+ import { primeOllamaContextWindows } from "./providers/ollama/context-window.js";
1
4
  import {
2
5
  type AccountConfig,
3
6
  type AccountRuntime,
@@ -207,6 +210,7 @@ interface AccountRequestWaiter {
207
210
  queueKey: string;
208
211
  model?: string;
209
212
  providerId?: string;
213
+ autoScope?: AutoAccountScope;
210
214
  signal?: AbortSignal;
211
215
  timer: ReturnType<typeof setTimeout>;
212
216
  onAbort?: () => void;
@@ -321,6 +325,41 @@ export class AccountRotator {
321
325
  * Exposes only aggregate routing health to the optional Jev selector.
322
326
  * Account identities and credentials stay inside the rotator.
323
327
  */
328
+ getAutoRoutingEvidenceStatus(model: string, providerId: string) {
329
+ const key=this.resolvePoolKeyForModel(model,providerId);
330
+ const now=Date.now(),policy=this.config.routingPolicy||"timer-first";
331
+ const accounts=key?this.accounts.filter(a=>!this.getRoutingRejectionForModel(a,key,now,policy)).map(a=>a.config):[];
332
+ return summarizeAutoAccess(accounts,providerId,model);
333
+ }
334
+
335
+ /**
336
+ * Applies account/model access policy only to operationally routable accounts.
337
+ * Keep this separate from candidate health so dashboards continue to report
338
+ * provider availability independently of plan eligibility.
339
+ */
340
+ getAutoRoutingAccessStatus(model: string, providerId: string): {
341
+ eligible: boolean;
342
+ reason?: string;
343
+ } {
344
+ const poolKey = this.resolvePoolKeyForModel(model, providerId);
345
+ if (!poolKey) return { eligible: true };
346
+ const now = Date.now();
347
+ const policy = this.config.routingPolicy || "timer-first";
348
+ let operationalAccounts = 0;
349
+ let firstReason: string | undefined;
350
+ for (const account of this.accounts) {
351
+ if (this.getRoutingRejectionForModel(account, poolKey, now, policy)) continue;
352
+ operationalAccounts++;
353
+ const access = evaluateAutoModelAccess(account.config, providerId, model);
354
+ if (access.eligible) return { eligible: true };
355
+ firstReason ??= access.reason;
356
+ }
357
+ // Availability is reported by getAutoRoutingCandidateStatus. If no
358
+ // account is operational, this method has no access denial to add.
359
+ if (operationalAccounts === 0) return { eligible: true };
360
+ return { eligible: false, ...(firstReason ? { reason: firstReason } : {}) };
361
+ }
362
+
324
363
  getAutoRoutingCandidateStatus(
325
364
  model: string,
326
365
  providerId: string,
@@ -340,7 +379,12 @@ export class AccountRotator {
340
379
  let available = false;
341
380
  let firstReason: string | undefined;
342
381
  for (const account of this.accounts) {
343
- const rejection = this.getRoutingRejectionForModel(account, poolKey, now, policy);
382
+ const rejection = this.getRoutingRejectionForModel(
383
+ account,
384
+ poolKey,
385
+ now,
386
+ policy,
387
+ );
344
388
  if (rejection) {
345
389
  firstReason ??= rejection.detail;
346
390
  continue;
@@ -453,7 +497,10 @@ export class AccountRotator {
453
497
  const names = (data.models ?? [])
454
498
  .map((m) => m.name ?? m.model ?? "")
455
499
  .filter(Boolean);
456
- if (names.length > 0) this.setOllamaModels(names);
500
+ if (names.length > 0) {
501
+ this.setOllamaModels(names);
502
+ void primeOllamaContextWindows(names, ollamaAccount).catch(() => {});
503
+ }
457
504
  } catch {
458
505
  // Catalog refresh is non-fatal
459
506
  }
@@ -1348,6 +1395,7 @@ export class AccountRotator {
1348
1395
  modelKey: string,
1349
1396
  now: number,
1350
1397
  excludeIdx: number = -1,
1398
+ autoScope?: AutoAccountScope,
1351
1399
  ): AccountRuntime | null {
1352
1400
  let best: AccountRuntime | null = null;
1353
1401
  let bestMetrics: {
@@ -1374,7 +1422,7 @@ export class AccountRotator {
1374
1422
  if (i === excludeIdx) continue;
1375
1423
  const account = this.accounts[i];
1376
1424
  if (!this.isProviderEligibleForKey(account, modelKey)) continue;
1377
- if (!this.isAvailableForModel(account, modelKey, now)) continue;
1425
+ if (!this.isAvailableForModel(account, modelKey, now, autoScope)) continue;
1378
1426
 
1379
1427
  const quota = this.getModelQuota(account, modelKey);
1380
1428
  if (quota === 0) continue;
@@ -1430,6 +1478,7 @@ export class AccountRotator {
1430
1478
  private pickLeastLoadedModelAccount(
1431
1479
  modelKey: string,
1432
1480
  now: number,
1481
+ autoScope?: AutoAccountScope,
1433
1482
  ): AccountRuntime | null {
1434
1483
  let best: AccountRuntime | null = null;
1435
1484
  let bestLoad = Infinity;
@@ -1439,7 +1488,7 @@ export class AccountRotator {
1439
1488
 
1440
1489
  for (let i = 0; i < this.accounts.length; i++) {
1441
1490
  const account = this.accounts[i];
1442
- if (!this.isRoutableForModel(account, modelKey, now)) continue;
1491
+ if (!this.isRoutableForModel(account, modelKey, now, autoScope)) continue;
1443
1492
  const load = account.inFlightRequests;
1444
1493
  const tier = this.getTierRank(account);
1445
1494
  const distance = this.requestCursorIndex < 0
@@ -1489,8 +1538,9 @@ export class AccountRotator {
1489
1538
  modelKey: string,
1490
1539
  now: number = Date.now(),
1491
1540
  excludeIdx?: number,
1541
+ autoScope?: AutoAccountScope,
1492
1542
  ): Promise<AccountRuntime | null> {
1493
- return this.rotateModel(modelKey, now, excludeIdx, true);
1543
+ return this.rotateModel(modelKey, now, excludeIdx, true, autoScope);
1494
1544
  }
1495
1545
 
1496
1546
  private rollDailySafetyIfNeeded(now: number): void {
@@ -1675,11 +1725,25 @@ export class AccountRotator {
1675
1725
  now: number,
1676
1726
  policy: Config["routingPolicy"],
1677
1727
  ignoreConcurrency = false,
1728
+ autoScope?: AutoAccountScope,
1678
1729
  ): { reason: RoutingRejectionReason; detail: string } | null {
1679
1730
  if (account.disabled)
1680
1731
  return { reason: "disabled", detail: "account disabled" };
1681
1732
  if (account.flagged)
1682
1733
  return { reason: "flagged", detail: "account quarantined or flagged" };
1734
+ if (autoScope) {
1735
+ const access = evaluateAutoModelAccess(
1736
+ account.config,
1737
+ autoScope.providerId,
1738
+ autoScope.modelId,
1739
+ );
1740
+ if (!access.eligible) {
1741
+ return {
1742
+ reason: "provider-ineligible",
1743
+ detail: `auto access policy: ${access.reason}`,
1744
+ };
1745
+ }
1746
+ }
1683
1747
  const providerRejection = this.getProviderEligibilityRejection(
1684
1748
  account,
1685
1749
  modelKey,
@@ -2050,19 +2114,20 @@ export class AccountRotator {
2050
2114
  model?: string,
2051
2115
  signal?: AbortSignal,
2052
2116
  providerId?: string,
2117
+ autoScope?: AutoAccountScope,
2053
2118
  ): Promise<AccountRuntime | null> {
2054
2119
  if (signal?.aborted) return null;
2055
2120
  const queueKey = this.getRequestQueueKey(model, providerId);
2056
2121
  if (
2057
2122
  this.hasQueuedRequest(queueKey) ||
2058
- this.isConcurrencySaturated(model, providerId)
2123
+ this.isConcurrencySaturated(model, providerId, autoScope)
2059
2124
  ) {
2060
- return this.enqueueAccountRequest(model, signal, queueKey, providerId);
2125
+ return this.enqueueAccountRequest(model, signal, queueKey, providerId, autoScope);
2061
2126
  }
2062
2127
 
2063
- const account = await this.tryGetActiveAccount(model, providerId);
2064
- if (account || !this.isConcurrencySaturated(model, providerId)) return account;
2065
- return this.enqueueAccountRequest(model, signal, queueKey, providerId);
2128
+ const account = await this.tryGetActiveAccount(model, providerId, autoScope);
2129
+ if (account || !this.isConcurrencySaturated(model, providerId, autoScope)) return account;
2130
+ return this.enqueueAccountRequest(model, signal, queueKey, providerId, autoScope);
2066
2131
  }
2067
2132
 
2068
2133
  /** Keep fairness within a provider pool without making unrelated providers wait. */
@@ -2080,6 +2145,7 @@ export class AccountRotator {
2080
2145
  signal?: AbortSignal,
2081
2146
  queueKey = this.getRequestQueueKey(model),
2082
2147
  providerId?: string,
2148
+ autoScope?: AutoAccountScope,
2083
2149
  ): Promise<AccountRuntime | null> {
2084
2150
  if (signal?.aborted) return Promise.resolve(null);
2085
2151
 
@@ -2088,6 +2154,7 @@ export class AccountRotator {
2088
2154
  waiter.queueKey = queueKey;
2089
2155
  waiter.model = model;
2090
2156
  waiter.providerId = providerId;
2157
+ waiter.autoScope = autoScope;
2091
2158
  waiter.signal = signal;
2092
2159
  waiter.resolve = resolve;
2093
2160
  waiter.reject = reject;
@@ -2201,7 +2268,7 @@ export class AccountRotator {
2201
2268
 
2202
2269
  let account: AccountRuntime | null;
2203
2270
  try {
2204
- account = await this.tryGetActiveAccount(waiter.model, waiter.providerId);
2271
+ account = await this.tryGetActiveAccount(waiter.model, waiter.providerId, waiter.autoScope);
2205
2272
  } catch (error) {
2206
2273
  this.rejectAccountRequestWaiter(waiter, error);
2207
2274
  progressed = true;
@@ -2230,9 +2297,9 @@ export class AccountRotator {
2230
2297
  progressed = true;
2231
2298
  continue;
2232
2299
  }
2233
- const wakeAt = this.getNextRequestAvailabilityAt(waiter.model, waiter.providerId);
2300
+ const wakeAt = this.getNextRequestAvailabilityAt(waiter.model, waiter.providerId, waiter.autoScope);
2234
2301
  if (wakeAt !== null) this.scheduleRequestWaiterWake(wakeAt);
2235
- if (!this.isConcurrencySaturated(waiter.model, waiter.providerId) && wakeAt === null) {
2302
+ if (!this.isConcurrencySaturated(waiter.model, waiter.providerId, waiter.autoScope) && wakeAt === null) {
2236
2303
  this.settleAccountRequestWaiter(waiter, null);
2237
2304
  progressed = true;
2238
2305
  }
@@ -2244,7 +2311,11 @@ export class AccountRotator {
2244
2311
  }
2245
2312
  }
2246
2313
 
2247
- private isConcurrencySaturated(model?: string, providerId?: string): boolean {
2314
+ private isConcurrencySaturated(
2315
+ model?: string,
2316
+ providerId?: string,
2317
+ autoScope?: AutoAccountScope,
2318
+ ): boolean {
2248
2319
  const now = Date.now();
2249
2320
  if (this.isProtectivePauseActive(now)) return false;
2250
2321
  const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
@@ -2260,6 +2331,7 @@ export class AccountRotator {
2260
2331
  now,
2261
2332
  policy,
2262
2333
  true,
2334
+ autoScope,
2263
2335
  )
2264
2336
  ) {
2265
2337
  continue;
@@ -2269,6 +2341,8 @@ export class AccountRotator {
2269
2341
  modelKey,
2270
2342
  now,
2271
2343
  policy,
2344
+ false,
2345
+ autoScope,
2272
2346
  );
2273
2347
  if (!rejection) return false;
2274
2348
  if (
@@ -2283,7 +2357,11 @@ export class AccountRotator {
2283
2357
 
2284
2358
  // Try to reserve an account immediately. The public method queues only
2285
2359
  // when every otherwise-eligible account is blocked by concurrency.
2286
- private async tryGetActiveAccount(model?: string, providerId?: string): Promise<AccountRuntime | null> {
2360
+ private async tryGetActiveAccount(
2361
+ model?: string,
2362
+ providerId?: string,
2363
+ autoScope?: AutoAccountScope,
2364
+ ): Promise<AccountRuntime | null> {
2287
2365
  const now = Date.now();
2288
2366
  if (this.accounts.length === 0) return null;
2289
2367
  if (this.isProtectivePauseActive(now)) return null;
@@ -2298,7 +2376,7 @@ export class AccountRotator {
2298
2376
  !state &&
2299
2377
  current &&
2300
2378
  this.isQuotaAwarePolicy() &&
2301
- this.isRoutableForModel(current, modelKey, now)
2379
+ this.isRoutableForModel(current, modelKey, now, autoScope)
2302
2380
  ) {
2303
2381
  // Seed the preference on the first request as well. Without this, a
2304
2382
  // default account that later enters cooldown would be indistinguishable
@@ -2317,18 +2395,18 @@ export class AccountRotator {
2317
2395
  );
2318
2396
  const policy = this.config.routingPolicy || "timer-first";
2319
2397
  if (modelKey && policy === "tier-first" && !hasActiveRequests) {
2320
- const preferred = this.pickBestModelAccount(modelKey, now);
2398
+ const preferred = this.pickBestModelAccount(modelKey, now, -1, autoScope);
2321
2399
  if (preferred && preferred !== current) {
2322
2400
  // A persisted assignment may have been selected under a previous
2323
2401
  // policy or before account tiers were corrected. Re-evaluate it while
2324
2402
  // idle so tier-first does not keep serving a lower-tier account.
2325
- return this.rotateModelForRequest(modelKey, now, idx);
2403
+ return this.rotateModelForRequest(modelKey, now, idx, autoScope);
2326
2404
  }
2327
2405
  }
2328
2406
  if (modelKey && hasActiveRequests) {
2329
- const leastLoaded = this.pickLeastLoadedModelAccount(modelKey, now);
2407
+ const leastLoaded = this.pickLeastLoadedModelAccount(modelKey, now, autoScope);
2330
2408
  if (leastLoaded && leastLoaded !== current) {
2331
- return this.rotateModelForRequest(modelKey, now, idx);
2409
+ return this.rotateModelForRequest(modelKey, now, idx, autoScope);
2332
2410
  }
2333
2411
  }
2334
2412
 
@@ -2339,19 +2417,23 @@ export class AccountRotator {
2339
2417
  now,
2340
2418
  state,
2341
2419
  idx,
2420
+ autoScope,
2342
2421
  );
2343
2422
  if (restored) return restored;
2344
2423
  } catch (error) {
2345
2424
  if (!this.isCodexPoolKey(modelKey)) throw error;
2346
- return this.rotateModelForRequest(modelKey, now, idx);
2425
+ return this.rotateModelForRequest(modelKey, now, idx, autoScope);
2347
2426
  }
2348
2427
  }
2349
2428
 
2350
2429
  if (current && modelKey) {
2351
- const providerRejection = this.getProviderEligibilityRejection(
2430
+ const providerRejection = this.getRoutingRejectionForModel(
2352
2431
  current,
2353
2432
  modelKey,
2354
2433
  now,
2434
+ this.config.routingPolicy || "timer-first",
2435
+ false,
2436
+ autoScope,
2355
2437
  );
2356
2438
  if (providerRejection) {
2357
2439
  // A cooldown is expected after a provider 429 and can be hit by many
@@ -2371,14 +2453,14 @@ export class AccountRotator {
2371
2453
  );
2372
2454
  }
2373
2455
  }
2374
- return this.rotateModelForRequest(modelKey, now, idx);
2456
+ return this.rotateModelForRequest(modelKey, now, idx, autoScope);
2375
2457
  }
2376
2458
  }
2377
2459
  if (
2378
2460
  current &&
2379
2461
  (!modelKey
2380
2462
  ? this.isAvailable(current, now)
2381
- : this.isAvailableForModel(current, modelKey, now))
2463
+ : this.isAvailableForModel(current, modelKey, now, autoScope))
2382
2464
  ) {
2383
2465
  // Check if this account has quota for the requested model
2384
2466
  if (modelKey) {
@@ -2386,7 +2468,7 @@ export class AccountRotator {
2386
2468
  this.log(
2387
2469
  `${current.config.label || current.config.email} [${modelKey}]: hit rotation threshold (${this.config.requestsPerRotation})`,
2388
2470
  );
2389
- const rotated = await this.rotateModelForRequest(modelKey, now, idx);
2471
+ const rotated = await this.rotateModelForRequest(modelKey, now, idx, autoScope);
2390
2472
  if (rotated) {
2391
2473
  current.requestsSinceRotation = 0;
2392
2474
  return rotated;
@@ -2401,7 +2483,7 @@ export class AccountRotator {
2401
2483
  this.log(
2402
2484
  `${current.config.label || current.config.email} [${modelKey}]: 0% quota, skipping`,
2403
2485
  );
2404
- return this.rotateModelForRequest(modelKey);
2486
+ return this.rotateModelForRequest(modelKey, now, undefined, autoScope);
2405
2487
  }
2406
2488
  if (!this.isFreshWindowAllowed(current, modelKey)) {
2407
2489
  const label = current.config.label || current.config.email;
@@ -2411,7 +2493,7 @@ export class AccountRotator {
2411
2493
  : `${label} [${modelKey}]: fresh window blocked by operator toggle`,
2412
2494
  "warn",
2413
2495
  );
2414
- return this.rotateModelForRequest(modelKey);
2496
+ return this.rotateModelForRequest(modelKey, now, undefined, autoScope);
2415
2497
  }
2416
2498
  if ((this.config.routingPolicy || "timer-first") === "hybrid") {
2417
2499
  const tokenSnapshot = this.getTokenBucketSnapshot(current, now);
@@ -2420,7 +2502,7 @@ export class AccountRotator {
2420
2502
  `${current.config.label || current.config.email} [${modelKey}]: local token bucket is empty, rotating to another candidate`,
2421
2503
  "warn",
2422
2504
  );
2423
- return this.rotateModelForRequest(modelKey, now, idx);
2505
+ return this.rotateModelForRequest(modelKey, now, idx, autoScope);
2424
2506
  }
2425
2507
  }
2426
2508
  }
@@ -2440,7 +2522,7 @@ export class AccountRotator {
2440
2522
  this.refundTokenBucket(current, Date.now());
2441
2523
  this.finishRequest(current, modelKey ?? undefined, providerId);
2442
2524
  if (modelKey && this.isCodexPoolKey(modelKey)) {
2443
- return this.rotateModelForRequest(modelKey, now, idx);
2525
+ return this.rotateModelForRequest(modelKey, now, idx, autoScope);
2444
2526
  }
2445
2527
  throw err;
2446
2528
  }
@@ -2448,7 +2530,7 @@ export class AccountRotator {
2448
2530
 
2449
2531
  // Current unavailable, or no per-model assignment yet
2450
2532
  if (modelKey) {
2451
- return this.rotateModelForRequest(modelKey, now, state ? idx : -1);
2533
+ return this.rotateModelForRequest(modelKey, now, state ? idx : -1, autoScope);
2452
2534
  }
2453
2535
  const defaultAcc = await this.rotateDefault(now, true);
2454
2536
  return defaultAcc;
@@ -2459,6 +2541,7 @@ export class AccountRotator {
2459
2541
  now: number,
2460
2542
  state: ModelRotationState,
2461
2543
  activeIndex: number,
2544
+ autoScope?: AutoAccountScope,
2462
2545
  ): Promise<AccountRuntime | null> {
2463
2546
  if (!this.isQuotaAwarePolicy()) return null;
2464
2547
  const preferredIndex = state.stickyAccountIndex;
@@ -2479,7 +2562,7 @@ export class AccountRotator {
2479
2562
  this.scheduleStateSave();
2480
2563
  return null;
2481
2564
  }
2482
- if (!this.isRoutableForModel(preferred, modelKey, now)) return null;
2565
+ if (!this.isRoutableForModel(preferred, modelKey, now, autoScope)) return null;
2483
2566
 
2484
2567
  this.log(
2485
2568
  `[${modelKey}] Restoring preferred account ${preferred.config.label || preferred.config.email} after temporary fallback`,
@@ -2500,10 +2583,11 @@ export class AccountRotator {
2500
2583
  excludeIdx: number = this.modelState.get(modelKey)?.activeAccountIndex ??
2501
2584
  -1,
2502
2585
  forRequest = false,
2586
+ autoScope?: AutoAccountScope,
2503
2587
  ): Promise<AccountRuntime | null> {
2504
2588
  const best = forRequest
2505
- ? this.pickLeastLoadedModelAccount(modelKey, now)
2506
- : this.pickBestModelAccount(modelKey, now, excludeIdx);
2589
+ ? this.pickLeastLoadedModelAccount(modelKey, now, autoScope)
2590
+ : this.pickBestModelAccount(modelKey, now, excludeIdx, autoScope);
2507
2591
 
2508
2592
  if (best) {
2509
2593
  const previous = this.modelState.get(modelKey);
@@ -2519,7 +2603,7 @@ export class AccountRotator {
2519
2603
  preferred &&
2520
2604
  this.getModelQuota(preferred, modelKey) !== 0 &&
2521
2605
  (preferredIndex !== previous.activeAccountIndex ||
2522
- !this.isAvailableForModel(preferred, modelKey, now))
2606
+ !this.isAvailableForModel(preferred, modelKey, now, autoScope))
2523
2607
  ) {
2524
2608
  // Keep the original account as the preference while a cooldown,
2525
2609
  // breaker, or concurrency limit forces a temporary fallback.
@@ -2548,6 +2632,7 @@ export class AccountRotator {
2548
2632
  now,
2549
2633
  this.accounts.indexOf(best),
2550
2634
  forRequest,
2635
+ autoScope,
2551
2636
  );
2552
2637
  }
2553
2638
  }
@@ -2705,6 +2790,7 @@ export class AccountRotator {
2705
2790
  model?: string,
2706
2791
  failedAccount?: AccountRuntime | number | string,
2707
2792
  providerId?: string,
2793
+ autoScope?: AutoAccountScope,
2708
2794
  ): Promise<AccountRuntime | null> {
2709
2795
  if (this.isProtectivePauseActive(Date.now())) return null;
2710
2796
  const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
@@ -2725,7 +2811,7 @@ export class AccountRotator {
2725
2811
  : this.defaultIndex;
2726
2812
  }
2727
2813
  return modelKey
2728
- ? this.rotateModel(modelKey, Date.now(), excludeIdx)
2814
+ ? this.rotateModel(modelKey, Date.now(), excludeIdx, false, autoScope)
2729
2815
  : this.rotateDefault(Date.now(), false, excludeIdx);
2730
2816
  }
2731
2817
 
@@ -3903,9 +3989,20 @@ export class AccountRotator {
3903
3989
  account: AccountRuntime,
3904
3990
  modelKey: string,
3905
3991
  now: number,
3992
+ autoScope?: AutoAccountScope,
3906
3993
  ): boolean {
3907
3994
  if (!this.isAvailable(account, now)) return false;
3908
3995
  const providerId = getProviderIdForPoolKey(modelKey);
3996
+ if (
3997
+ autoScope &&
3998
+ !evaluateAutoModelAccess(
3999
+ account.config,
4000
+ autoScope.providerId,
4001
+ autoScope.modelId,
4002
+ ).eligible
4003
+ ) {
4004
+ return false;
4005
+ }
3909
4006
  if (account.invalidProviders?.[providerId]) return false;
3910
4007
  if (this.isProviderOffForAccount(account, providerId)) return false;
3911
4008
  if ((account.providerCooldowns?.[providerId] ?? 0) > now) return false;
@@ -4147,10 +4244,11 @@ export class AccountRotator {
4147
4244
  account: AccountRuntime,
4148
4245
  modelKey: string,
4149
4246
  now: number,
4247
+ autoScope?: AutoAccountScope,
4150
4248
  ): boolean {
4151
4249
  modelKey = this.resolvePoolKey(account, modelKey);
4152
4250
  if (!this.isProviderEligibleForKey(account, modelKey)) return false;
4153
- if (!this.isAvailableForModel(account, modelKey, now)) return false;
4251
+ if (!this.isAvailableForModel(account, modelKey, now, autoScope)) return false;
4154
4252
  if (this.getModelQuota(account, modelKey) === 0) return false;
4155
4253
  if (!this.isFreshWindowAllowed(account, modelKey)) return false;
4156
4254
  if ((this.config.routingPolicy || "timer-first") === "hybrid") {
@@ -4164,6 +4262,7 @@ export class AccountRotator {
4164
4262
  model: string | undefined,
4165
4263
  now: number,
4166
4264
  providerId?: string,
4265
+ autoScope?: AutoAccountScope,
4167
4266
  ): number[] {
4168
4267
  const retryTimes: number[] = [];
4169
4268
  if (this.protectivePauseUntil > now)
@@ -4178,6 +4277,16 @@ export class AccountRotator {
4178
4277
  for (const account of this.accounts) {
4179
4278
  if (account.disabled || account.flagged) continue;
4180
4279
  const candidateProviderId = providerId ?? getProviderIdForPoolKey(modelKey);
4280
+ if (
4281
+ autoScope &&
4282
+ !evaluateAutoModelAccess(
4283
+ account.config,
4284
+ autoScope.providerId,
4285
+ autoScope.modelId,
4286
+ ).eligible
4287
+ ) {
4288
+ continue;
4289
+ }
4181
4290
  if (
4182
4291
  !hasCredential(account.config, candidateProviderId) ||
4183
4292
  account.invalidProviders?.[candidateProviderId] ||
@@ -4214,9 +4323,13 @@ export class AccountRotator {
4214
4323
  return retryTimes;
4215
4324
  }
4216
4325
 
4217
- private getNextRequestAvailabilityAt(model?: string, providerId?: string): number | null {
4326
+ private getNextRequestAvailabilityAt(
4327
+ model?: string,
4328
+ providerId?: string,
4329
+ autoScope?: AutoAccountScope,
4330
+ ): number | null {
4218
4331
  const now = Date.now();
4219
- const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId);
4332
+ const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId, autoScope);
4220
4333
  return retryTimes.length > 0 ? Math.min(...retryTimes) : null;
4221
4334
  }
4222
4335
 
@@ -85,6 +85,7 @@ const DISK_FILES: Record<string, DiskFileSpec> = {
85
85
  trim: false,
86
86
  mode: 0o600,
87
87
  },
88
+ model_access_evidence: { filename: "model-access-evidence.json", backup: false, trim: false, mode: 0o600 },
88
89
  rotator_state: { filename: "state.json", backup: true, trim: false },
89
90
  token_usage: { filename: "token-usage.json", backup: false, trim: false },
90
91
  responses_store: { filename: "responses.json", backup: false, trim: false },
package/src/telemetry.ts CHANGED
@@ -351,7 +351,9 @@ export class TelemetryReporter {
351
351
  };
352
352
 
353
353
  // Fire-and-forget
354
- void this.sendPayload(payload);
354
+ void this.sendPayload(payload).catch(() => {
355
+ // Telemetry failures must never terminate the proxy.
356
+ });
355
357
 
356
358
  telemetryLogger.log("info",
357
359
  `Flag event reported: ${data.flagHttpStatus} [${data.flagPatternsMatched.join(",")}] model=${data.model}`,
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. */
@@ -1082,7 +1106,9 @@ export function getModelPricing(model: string): ModelPricing | undefined {
1082
1106
  // "free" = served on the free tier; "subscription" = requires a paid plan.
1083
1107
  export type ModelTierAccess = "free" | "subscription";
1084
1108
  export const MODEL_TIER_ACCESS: Record<string, ModelTierAccess> = {
1109
+ // Free-credit list refreshed from operator-provided Ollama list, 2026-10-30.
1085
1110
  // ── Free tier (HTTP 200 on free accounts) ───────────────────────────────
1111
+ "beam": "free",
1086
1112
  "gpt-oss:20b": "free",
1087
1113
  "gpt-oss:120b": "free",
1088
1114
  "gemma4:31b": "free",
@@ -1090,6 +1116,8 @@ export const MODEL_TIER_ACCESS: Record<string, ModelTierAccess> = {
1090
1116
  "nemotron-3-super": "free",
1091
1117
  "nemotron-3-ultra": "free",
1092
1118
  // ── Subscription tier (HTTP 402 on free accounts) ───────────────────────
1119
+ "deepseek-v4.1-flash:1017": "subscription",
1120
+ "minimax-m3.1-flash": "subscription",
1093
1121
  "deepseek-v4-flash:0731": "subscription",
1094
1122
  "deepseek-v4-pro:0813": "subscription",
1095
1123
  "glm-5.1": "subscription",
@@ -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
+ }