tuxevil-rotator 4.4.9 → 4.5.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 (57) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +2 -1
  3. package/package.json +1 -1
  4. package/src/access-probe.ts +1 -1
  5. package/src/account-store.ts +14 -2
  6. package/src/audio-transcription.ts +1 -0
  7. package/src/auto-model-access.ts +22 -0
  8. package/src/compat/model-specs.ts +7 -0
  9. package/src/compat/schema-sanitizer.ts +420 -287
  10. package/src/compat.ts +110 -66
  11. package/src/config-defaults.ts +7 -0
  12. package/src/fetch-with-retry.ts +294 -16
  13. package/src/idempotency.ts +3 -1
  14. package/src/model-access-api.ts +9 -1
  15. package/src/model-access.ts +2 -2
  16. package/src/notification-poller.ts +9 -1
  17. package/src/provider-catalog-evidence.ts +18 -1
  18. package/src/providers/adapter.ts +5 -0
  19. package/src/providers/credential-helpers.ts +34 -0
  20. package/src/providers/google-antigravity/aicode-eligibility.ts +256 -0
  21. package/src/providers/google-antigravity/aicode-forward.ts +381 -0
  22. package/src/providers/google-antigravity/aicode.ts +478 -0
  23. package/src/providers/google-antigravity/catalog.ts +6 -0
  24. package/src/providers/google-antigravity/code-assist.ts +53 -41
  25. package/src/providers/google-antigravity/dynamic-catalog.ts +72 -7
  26. package/src/providers/google-antigravity/forward.ts +309 -86
  27. package/src/providers/google-antigravity/index.ts +67 -6
  28. package/src/providers/google-antigravity/oauth.ts +22 -12
  29. package/src/providers/google-antigravity/quota.ts +781 -34
  30. package/src/providers/google-antigravity/translators.ts +55 -46
  31. package/src/providers/google-antigravity/twin-payload.ts +231 -0
  32. package/src/providers/ollama/quota.ts +6 -4
  33. package/src/providers/openai-codex/compat.ts +11 -2
  34. package/src/providers/openai-codex/quota.ts +2 -1
  35. package/src/providers/opencode-zen/catalog.ts +159 -13
  36. package/src/providers/opencode-zen/discovery.ts +50 -0
  37. package/src/providers/opencode-zen/index.ts +7 -2
  38. package/src/providers/opencode-zen/quota.ts +14 -1
  39. package/src/proxy.ts +570 -87
  40. package/src/quota-pools.ts +76 -1
  41. package/src/rate-limit-parser.ts +239 -19
  42. package/src/rotator.ts +602 -138
  43. package/src/stream-guards.ts +87 -1
  44. package/src/telemetry.ts +17 -3
  45. package/src/types.ts +168 -9
  46. package/src/validators.ts +3 -0
  47. package/src/web/lib/accounts.ts +2 -0
  48. package/src/web/lib/attention.ts +19 -0
  49. package/src/web/lib/models.ts +6 -1
  50. package/src/web/lib/status.ts +22 -4
  51. package/src/web/pages/AccountDetail.tsx +49 -2
  52. package/src/web/pages/Accounts.tsx +38 -3
  53. package/src/web/pages/ModelAccess.tsx +4 -0
  54. package/src/web/pages/Models.tsx +2 -1
  55. package/src/web/pages/Overview.tsx +15 -1
  56. package/src/web/styles/app.css +73 -3
  57. package/tools/telemetry-receiver/receiver.js +444 -243
@@ -1,21 +1,70 @@
1
1
  import type { Dispatcher } from "undici";
2
+ import {
3
+ extractRetryDelayMs,
4
+ isAntigravityRetryableError,
5
+ MAX_ANTIGRAVITY_RETRY_DELAY_MS,
6
+ } from "./rate-limit-parser.js";
2
7
 
3
8
  export interface FetchWithRetryOptions extends RequestInit {
4
9
  retries?: number;
5
10
  timeoutMs?: number;
6
11
  baseDelayMs?: number;
7
12
  maxDelayMs?: number;
13
+ exponentialMultiplier?: number;
14
+ jitterRange?: number;
15
+ maxServerRetryDelayMs?: number;
8
16
  retryStatuses?: number[];
17
+ /**
18
+ * `generic` (default): retry transport errors and 408/429/500/502/503/504
19
+ * with short backoff. `antigravity`: Antigravity twin classification for
20
+ * Google CCPA calls (no HTTP 500 retry, hard 429 / long retryDelay fail fast).
21
+ */
22
+ retryPolicy?: FetchRetryPolicy;
9
23
  fetchImpl?: typeof fetch;
10
- sleepImpl?: (ms: number) => Promise<void>;
24
+ sleepImpl?: (ms: number, signal?: AbortSignal) => Promise<void>;
11
25
  /** Node/Undici dispatcher selected from the account's provider config. */
12
26
  dispatcher?: Dispatcher;
13
27
  }
14
28
 
15
29
  export type RequestInitWithDispatcher = RequestInit & { dispatcher?: Dispatcher };
16
30
 
31
+ export type FetchRetryPolicy = "generic" | "antigravity";
32
+
33
+ // Generic retry statuses shared by every provider/catalog/quota caller.
17
34
  export const DEFAULT_RETRY_STATUSES = [408, 429, 500, 502, 503, 504] as const;
18
- export const DEFAULT_HEADERS_TIMEOUT_MS = 30_000;
35
+ // Twin to Antigravity utils.RetryableFromErrorDetails & classifyGenAIAPIErrorWithMode:
36
+ // 408, 429, 502, 503, 504 (HTTP 500 is NOT retried). Only for retryPolicy "antigravity".
37
+ export const ANTIGRAVITY_RETRY_STATUSES = [408, 429, 502, 503, 504] as const;
38
+ /** Generic fetchWithRetry backoff: 250ms doubling, capped at 5s. */
39
+ export const GENERIC_RETRY_BACKOFF = {
40
+ baseDelayMs: 250,
41
+ maxDelayMs: 5_000,
42
+ exponentialMultiplier: 2,
43
+ jitterRange: 0.2,
44
+ } as const;
45
+ // Default for non-Google providers (Ollama, OpenAI Codex, OpenCode Zen): an
46
+ // upstream that never sends headers must not hold a slot for minutes.
47
+ export const DEFAULT_HEADERS_TIMEOUT_MS = 120_000;
48
+ // Google Antigravity only: matches ccpahttp.New default stream idle timeout (600s).
49
+ export const ANTIGRAVITY_HEADERS_TIMEOUT_MS = 600_000;
50
+
51
+ /** Matches Antigravity defaultConversationalCascadeConfig ModelAPIRetryConfig + ModelAPIBackoff. */
52
+ export const ANTIGRAVITY_RETRY_CONFIG = {
53
+ maxRetries: 8,
54
+ initialSleepDurationMs: 4_000,
55
+ maxSleepDurationMs: MAX_ANTIGRAVITY_RETRY_DELAY_MS,
56
+ exponentialMultiplier: 2,
57
+ jitterRange: 0.4,
58
+ } as const;
59
+
60
+ /** Matches Antigravity model_api/common/continuation.NewStream defaults. */
61
+ export const ANTIGRAVITY_CONTINUATION_RETRY_CONFIG = {
62
+ baseDelayMs: 100,
63
+ maxDelayMs: 5_000,
64
+ maxRetries: 3,
65
+ maxContinuations: 32,
66
+ maxResumeDelayMs: 60_000,
67
+ } as const;
19
68
 
20
69
  /** Raised when an upstream accepts a request but never sends response headers. */
21
70
  export class UpstreamHeadersTimeoutError extends Error {
@@ -38,24 +87,93 @@ export function isRetryableStatus(status: number, retryStatuses: readonly number
38
87
  }
39
88
 
40
89
  export function isRetryableFetchError(error: unknown): boolean {
41
- if (error instanceof DOMException && error.name === "AbortError") return true;
90
+ if (
91
+ (error instanceof DOMException || error instanceof Error) &&
92
+ (error.name === "AbortError" || error.name === "TimeoutError")
93
+ ) {
94
+ return true;
95
+ }
42
96
  if (error instanceof UpstreamHeadersTimeoutError) return true;
43
- return error instanceof TypeError;
97
+ const cause =
98
+ typeof error === "object" && error !== null && "cause" in error
99
+ ? (error as { cause?: unknown }).cause
100
+ : undefined;
101
+ const msg = [
102
+ error instanceof Error ? error.message : String(error ?? ""),
103
+ cause instanceof Error ? cause.message : String(cause ?? ""),
104
+ typeof cause === "object" && cause !== null && "code" in cause
105
+ ? String((cause as { code?: unknown }).code ?? "")
106
+ : "",
107
+ ]
108
+ .join(" ")
109
+ .toLowerCase();
110
+ if (msg.includes("x509") || msg.includes("certificate") || msg.includes("tls")) return false;
111
+ if (error instanceof TypeError) return true;
112
+ return false;
44
113
  }
45
114
 
115
+ /**
116
+ * Matches Antigravity timeutil.backoff + core.backoff / generator.retrySleepDuration:
117
+ * exponential growth capped at maxDelayMs with downward jitter `[clamped * (1 - jitterRange), clamped]`
118
+ * floored at baseDelayMs, and when serverRetryDelayMs > 0, `max(backoff, serverRetryDelayMs + rand * backoff * jitterRange)`.
119
+ */
46
120
  export function calculateBackoffMs(
47
121
  attempt: number,
48
- baseDelayMs = 250,
49
- maxDelayMs = 5_000,
122
+ baseDelayMs: number = ANTIGRAVITY_RETRY_CONFIG.initialSleepDurationMs,
123
+ maxDelayMs: number = ANTIGRAVITY_RETRY_CONFIG.maxSleepDurationMs,
124
+ random: () => number = Math.random,
125
+ exponentialMultiplier: number = ANTIGRAVITY_RETRY_CONFIG.exponentialMultiplier,
126
+ jitterRange: number = ANTIGRAVITY_RETRY_CONFIG.jitterRange,
127
+ serverRetryDelayMs = 0,
128
+ ): number {
129
+ const raw = baseDelayMs * exponentialMultiplier ** Math.max(0, attempt);
130
+ const clamped = Number.isFinite(raw) ? Math.min(maxDelayMs, raw) : maxDelayMs;
131
+ const backoff = Math.max(
132
+ baseDelayMs,
133
+ Math.round(clamped - random() * clamped * jitterRange),
134
+ );
135
+ if (serverRetryDelayMs > 0) {
136
+ const serverWithJitter =
137
+ serverRetryDelayMs + Math.round(random() * backoff * jitterRange);
138
+ return Math.max(backoff, serverWithJitter);
139
+ }
140
+ return backoff;
141
+ }
142
+
143
+ /**
144
+ * Matches Antigravity continuation.sleepForMidStreamRetry:
145
+ * `min(baseDelay << min(max(retry - 1, 0), 6), maxDelay)` with half-jitter `[0.5, 1.0)`.
146
+ */
147
+ export function calculateContinuationBackoffMs(
148
+ attempt: number,
50
149
  random = Math.random,
150
+ serverRetryDelayMs = 0,
151
+ baseDelayMs = ANTIGRAVITY_CONTINUATION_RETRY_CONFIG.baseDelayMs,
152
+ maxDelayMs = ANTIGRAVITY_CONTINUATION_RETRY_CONFIG.maxDelayMs,
51
153
  ): number {
52
- const exponential = baseDelayMs * 2 ** Math.max(0, attempt);
53
- const jitter = exponential * 0.2 * random();
54
- return Math.min(maxDelayMs, Math.round(exponential + jitter));
154
+ const shift = Math.min(Math.max(attempt - 1, 0), 6);
155
+ const exp = Math.min(baseDelayMs * 2 ** shift, maxDelayMs);
156
+ const jittered = Math.round(exp * (0.5 + random() * 0.5));
157
+ return serverRetryDelayMs > 0 ? Math.max(serverRetryDelayMs, jittered) : jittered;
55
158
  }
56
159
 
57
- function sleep(ms: number): Promise<void> {
58
- return new Promise((resolve) => setTimeout(resolve, ms));
160
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
161
+ if (signal?.aborted) {
162
+ return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
163
+ }
164
+ return new Promise((resolve, reject) => {
165
+ const timer = setTimeout(() => {
166
+ if (signal) signal.removeEventListener("abort", onAbort);
167
+ resolve();
168
+ }, ms);
169
+ const onAbort = () => {
170
+ clearTimeout(timer);
171
+ reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
172
+ };
173
+ if (signal) {
174
+ signal.addEventListener("abort", onAbort, { once: true });
175
+ }
176
+ });
59
177
  }
60
178
 
61
179
  function createTimeoutSignal(timeoutMs: number | undefined, inputSignal: AbortSignal | null | undefined): AbortSignal | undefined {
@@ -121,22 +239,42 @@ export async function fetchWithHeadersTimeout(
121
239
  /**
122
240
  * Fetch wrapper for non-streaming calls. Retries only transport failures and explicit retryable statuses.
123
241
  * Do not use for streaming responses: retrying streams can duplicate upstream work.
242
+ * The default `generic` policy applies to every provider; Antigravity twin
243
+ * classification is opt-in through `retryPolicy: "antigravity"`.
124
244
  */
125
245
  export async function fetchWithRetry(input: RequestInfo | URL, options: FetchWithRetryOptions = {}): Promise<Response> {
246
+ const antigravity = options.retryPolicy === "antigravity";
126
247
  const {
127
248
  retries = 2,
128
249
  timeoutMs = 10_000,
129
- baseDelayMs = 250,
130
- maxDelayMs = 5_000,
131
- retryStatuses = [...DEFAULT_RETRY_STATUSES],
250
+ baseDelayMs = antigravity
251
+ ? ANTIGRAVITY_RETRY_CONFIG.initialSleepDurationMs
252
+ : GENERIC_RETRY_BACKOFF.baseDelayMs,
253
+ maxDelayMs = antigravity
254
+ ? ANTIGRAVITY_RETRY_CONFIG.maxSleepDurationMs
255
+ : GENERIC_RETRY_BACKOFF.maxDelayMs,
256
+ exponentialMultiplier = antigravity
257
+ ? ANTIGRAVITY_RETRY_CONFIG.exponentialMultiplier
258
+ : GENERIC_RETRY_BACKOFF.exponentialMultiplier,
259
+ jitterRange = antigravity
260
+ ? ANTIGRAVITY_RETRY_CONFIG.jitterRange
261
+ : GENERIC_RETRY_BACKOFF.jitterRange,
262
+ maxServerRetryDelayMs = MAX_ANTIGRAVITY_RETRY_DELAY_MS,
263
+ retryStatuses = antigravity ? [...ANTIGRAVITY_RETRY_STATUSES] : [...DEFAULT_RETRY_STATUSES],
264
+ retryPolicy: _retryPolicy,
132
265
  fetchImpl = fetch,
133
266
  sleepImpl = sleep,
134
267
  dispatcher,
135
268
  ...init
136
269
  } = options;
270
+ void _retryPolicy;
137
271
 
138
272
  let lastError: unknown;
139
273
  for (let attempt = 0; attempt <= retries; attempt++) {
274
+ if (init.signal?.aborted) {
275
+ throw init.signal.reason ?? new DOMException("Aborted", "AbortError");
276
+ }
277
+ let serverRetryDelayMs = 0;
140
278
  try {
141
279
  const requestInit: RequestInitWithDispatcher = {
142
280
  ...init,
@@ -149,16 +287,156 @@ export async function fetchWithRetry(input: RequestInfo | URL, options: FetchWit
149
287
  return response;
150
288
  }
151
289
 
290
+ if (antigravity) {
291
+ let errorText = "";
292
+ if (response.status === 429 || response.status === 402 || response.status >= 500) {
293
+ errorText = await response.clone().text().catch(() => "");
294
+ }
295
+ if (init.signal?.aborted) {
296
+ throw init.signal.reason ?? new DOMException("Aborted", "AbortError");
297
+ }
298
+ const serverDelay = extractRetryDelayMs(errorText, response.headers);
299
+ if (serverDelay !== null) {
300
+ if (serverDelay > maxServerRetryDelayMs) {
301
+ return response;
302
+ }
303
+ serverRetryDelayMs = serverDelay;
304
+ }
305
+ if (
306
+ response.status >= 400 &&
307
+ !isAntigravityRetryableError({
308
+ status: response.status,
309
+ errorText,
310
+ headers: response.headers,
311
+ })
312
+ ) {
313
+ return response;
314
+ }
315
+ }
316
+
152
317
  await response.body?.cancel().catch(() => undefined);
153
318
  } catch (err) {
154
319
  lastError = err;
155
- if (!isRetryableFetchError(err) || attempt === retries) {
320
+ if (init.signal?.aborted || !isRetryableFetchError(err) || attempt === retries) {
156
321
  throw err;
157
322
  }
158
323
  }
159
324
 
160
- await sleepImpl(calculateBackoffMs(attempt, baseDelayMs, maxDelayMs));
325
+ await sleepImpl(
326
+ calculateBackoffMs(
327
+ attempt,
328
+ baseDelayMs,
329
+ maxDelayMs,
330
+ Math.random,
331
+ exponentialMultiplier,
332
+ jitterRange,
333
+ serverRetryDelayMs,
334
+ ),
335
+ init.signal ?? undefined,
336
+ );
161
337
  }
162
338
 
163
339
  throw lastError instanceof Error ? lastError : new Error(String(lastError ?? "fetch failed"));
164
340
  }
341
+
342
+ export interface AntigravityApiRetryOptions<T> {
343
+ maxRetries?: number;
344
+ initialSleepDurationMs?: number;
345
+ maxSleepDurationMs?: number;
346
+ exponentialMultiplier?: number;
347
+ jitterRange?: number;
348
+ maxServerRetryDelayMs?: number;
349
+ random?: () => number;
350
+ sleepImpl?: (ms: number, signal?: AbortSignal) => Promise<void>;
351
+ onRetry?: (info: {
352
+ attempt: number;
353
+ delayMs: number;
354
+ error: unknown;
355
+ serverRetryDelayMs: number;
356
+ }) => void;
357
+ signal?: AbortSignal;
358
+ classifyError?: (error: unknown) => {
359
+ retryable: boolean;
360
+ serverRetryDelayMs?: number;
361
+ };
362
+ fn: (attempt: number) => Promise<T>;
363
+ }
364
+
365
+ /**
366
+ * Twin retry loop to Antigravity core.CallWithRetry / oneharness RunWithAPIRetry:
367
+ * MaxAttempts = maxRetries + 1 (default 8 + 1 = 9), backoff via ModelAPIBackoff
368
+ * (4000ms -> 240s, 2.0x, downward jitter 0.4, + server delay additive jitter),
369
+ * failing fast when server delay > 240s or non-retryable.
370
+ */
371
+ export async function runWithAntigravityApiRetry<T>(
372
+ options: AntigravityApiRetryOptions<T>,
373
+ ): Promise<T> {
374
+ const {
375
+ maxRetries = ANTIGRAVITY_RETRY_CONFIG.maxRetries,
376
+ initialSleepDurationMs = ANTIGRAVITY_RETRY_CONFIG.initialSleepDurationMs,
377
+ maxSleepDurationMs = ANTIGRAVITY_RETRY_CONFIG.maxSleepDurationMs,
378
+ exponentialMultiplier = ANTIGRAVITY_RETRY_CONFIG.exponentialMultiplier,
379
+ jitterRange = ANTIGRAVITY_RETRY_CONFIG.jitterRange,
380
+ maxServerRetryDelayMs = MAX_ANTIGRAVITY_RETRY_DELAY_MS,
381
+ random = Math.random,
382
+ sleepImpl = sleep,
383
+ onRetry,
384
+ signal,
385
+ classifyError = (error: unknown) => {
386
+ if (isRetryableFetchError(error)) return { retryable: true };
387
+ const status =
388
+ typeof error === "object" && error !== null && "status" in error && typeof (error as { status: unknown }).status === "number"
389
+ ? (error as { status: number }).status
390
+ : undefined;
391
+ const errorText = error instanceof Error ? error.message : String(error ?? "");
392
+ const serverRetryDelayMs = extractRetryDelayMs(errorText) ?? undefined;
393
+ return {
394
+ retryable: isAntigravityRetryableError({ status, errorText }),
395
+ serverRetryDelayMs,
396
+ };
397
+ },
398
+ fn,
399
+ } = options;
400
+
401
+ const maxAttempts = Math.max(1, maxRetries + 1);
402
+ let lastError: unknown;
403
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
404
+ if (signal?.aborted) {
405
+ throw signal.reason ?? new DOMException("Aborted", "AbortError");
406
+ }
407
+ try {
408
+ return await fn(attempt);
409
+ } catch (error) {
410
+ lastError = error;
411
+ if (signal?.aborted) {
412
+ throw error;
413
+ }
414
+ const verdict = classifyError(error);
415
+ const serverDelayMs = verdict.serverRetryDelayMs ?? 0;
416
+ if (
417
+ !verdict.retryable ||
418
+ serverDelayMs > maxServerRetryDelayMs ||
419
+ attempt + 1 >= maxAttempts
420
+ ) {
421
+ throw error;
422
+ }
423
+ const delayMs = calculateBackoffMs(
424
+ attempt,
425
+ initialSleepDurationMs,
426
+ maxSleepDurationMs,
427
+ random,
428
+ exponentialMultiplier,
429
+ jitterRange,
430
+ serverDelayMs,
431
+ );
432
+ onRetry?.({
433
+ attempt,
434
+ delayMs,
435
+ error,
436
+ serverRetryDelayMs: serverDelayMs,
437
+ });
438
+ await sleepImpl(delayMs, signal);
439
+ }
440
+ }
441
+ throw lastError instanceof Error ? lastError : new Error(String(lastError ?? "retry exhausted"));
442
+ }
@@ -23,10 +23,12 @@ export class IdempotencyManager {
23
23
  .update(`idkey:${clientKey.trim()}`)
24
24
  .digest("hex");
25
25
  }
26
+ // SHA-256 is intentional: this is a deterministic HTTP request payload fingerprint
27
+ // for in-flight deduplication / idempotency caching, not a password hash.
26
28
  const raw = typeof body === "string" ? body : JSON.stringify(body);
27
29
  return createHash("sha256")
28
30
  .update(`body:${model}:${raw}`)
29
- .digest("hex");
31
+ .digest("hex"); // codeql[js/insufficient-password-hash]
30
32
  }
31
33
 
32
34
  /**
@@ -6,9 +6,10 @@ import type { ServerResponse, IncomingMessage } from "node:http";
6
6
  import type { Config } from "./types.js";
7
7
  import { getAccountIdentity } from "./account-identity.js";
8
8
  import { MODEL_ACCESS_RULES, evaluateModelAccess, type AccessDecision } from "./model-access.js";
9
+ import { evaluateAutoModelAccess, type AutoModelAccessDecision } from "./auto-model-access.js";
9
10
 
10
11
  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 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"; routing?: Pick<AutoModelAccessDecision, "eligible" | "reason" | "catalog"> }
12
13
  export function buildModelAccessReport(config: Config, params: URLSearchParams): AccessReport {
13
14
  const accounts = config.accounts.map(account => {
14
15
  const providers = [...new Set(account.credentials?.map(c => c.provider) ?? [account.provider ?? "google-antigravity"])];
@@ -36,6 +37,13 @@ export function buildModelAccessReport(config: Config, params: URLSearchParams):
36
37
  const catalog = account?.providerCatalogs.find(c => c.provider === provider);
37
38
  report.catalogAvailability = { state: catalog ? advertisedModelState(catalog, model) : "unknown", source: catalog?.source ?? null, observedAt: catalog?.observedAt ?? null, expiresAt: catalog?.expiresAt ?? null };
38
39
  report.decision = evaluateModelAccess({ provider, model, plan, client: params.get("client") ?? undefined, at: params.get("at") ?? undefined });
40
+ // Routing decides from the account's live catalog first; report that verdict
41
+ // so the plan-table explanation cannot be mistaken for the routing outcome.
42
+ const accountConfig = accountId ? config.accounts.find(a => getAccountIdentity(a) === accountId) : undefined;
43
+ if (accountConfig && !params.get("plan") && !params.get("at")) {
44
+ const { eligible, reason, catalog: source } = evaluateAutoModelAccess(accountConfig, provider, model, undefined, undefined, config.quotaPollIntervalMs);
45
+ report.routing = { eligible, reason, ...(source ? { catalog: source } : {}) };
46
+ }
39
47
  return report;
40
48
  }
41
49
  export function serveModelAccessApi(res: ServerResponse, config: Config, params: URLSearchParams): void {
@@ -29,8 +29,8 @@ export const MODEL_ACCESS_RULES: readonly AccessRule[] = [
29
29
  ...["gemini-4", "claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-paid-${model}`, "google-antigravity", ["free", "plus"], model, "blocked", "documented", google, "Not included in Free/Plus.")),
30
30
  ...["claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-trial-${model}`, "google-antigravity", ["pro-trial"], model, "blocked", "documented", google, "Claude 5.5 requires a non-trial Pro subscription or higher eligible plan.")),
31
31
  ...["gemini-4-argon", "gemini-4-neon", "gemini-4-hydrogen", "claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-entitled-${model}`, "google-antigravity", ["pro-paid", "ultra", "enterprise"], model, "allowed", "documented", google, "Listed for paid Pro/Ultra; account entitlement and quota still apply.")),
32
- rule("ag-carbon-paid", "google-antigravity", ["pro-paid", "pro-trial"], "gemini-4-carbon", "blocked", "documented", google, "Gemini 4 Carbon requires Ultra or Enterprise."),
33
- rule("ag-carbon-ultra", "google-antigravity", ["ultra", "enterprise"], "gemini-4-carbon", "allowed", "documented", google, "Gemini 4 Carbon is listed for Ultra and Enterprise."),
32
+ rule("ag-carbon-trial", "google-antigravity", ["pro-trial"], "gemini-4-carbon", "blocked", "operator-confirmed", "Account catalogs observed 2026-11-25", "Gemini 4 Carbon is not offered to trial Pro accounts."),
33
+ rule("ag-carbon-paid", "google-antigravity", ["pro-paid", "ultra", "enterprise"], "gemini-4-carbon", "allowed", "operator-confirmed", "Account catalogs observed 2026-11-25", "Paid Pro account catalogs advertise Gemini 4 Carbon; the account catalog still decides per account."),
34
34
  rule("ag-hydrogen-trial", "google-antigravity", ["pro-trial"], "gemini-4-hydrogen", "blocked", "documented", google, "Gemini 4 Hydrogen requires a non-trial Pro plan or higher."),
35
35
  rule("ag-neon-trial", "google-antigravity", ["pro-trial"], "gemini-4-neon", "conditional", "documented", google, "Only eligible premium-device trials."),
36
36
  rule("ag-argon-trial", "google-antigravity", ["pro-trial"], "gemini-4-argon", "conditional", "documented", google, "Only eligible premium-device trials; generic trial status is insufficient."),
@@ -22,7 +22,15 @@ export function resolveTelemetryBase(raw: string | undefined): string {
22
22
  try {
23
23
  const url = new URL(candidate);
24
24
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("unsupported protocol");
25
- return url.origin;
25
+ let pathname = url.pathname.replace(/\/+$/, "");
26
+ if (pathname.endsWith("/v1/events")) {
27
+ pathname = pathname.slice(0, -"/v1/events".length);
28
+ } else if (pathname.endsWith("/v1/notifications")) {
29
+ pathname = pathname.slice(0, -"/v1/notifications".length);
30
+ } else if (pathname.endsWith("/events")) {
31
+ pathname = pathname.slice(0, -"/events".length);
32
+ }
33
+ return `${url.origin}${pathname}`;
26
34
  } catch {
27
35
  notifLogger.log(
28
36
  "warn",
@@ -19,8 +19,25 @@ export function antigravityCatalogEvidence(account: AccountConfig, pollIntervalM
19
19
  const expiresAt = snapshot.observedAt + maxAge;
20
20
  return { ...base, ...snapshot, expiresAt, freshness: snapshot.observedAt > now ? "unknown" : expiresAt > now ? "fresh" : "stale" };
21
21
  }
22
+ function catalogTarget(model: string): string {
23
+ return applyModelAlias(model).trim().replace(/^models\//i, "").toLowerCase();
24
+ }
22
25
  export function advertisedModelState(catalog: ProviderCatalogEvidence, model: string): "advertised" | "not-advertised" | "unknown" {
23
26
  if (catalog.freshness !== "fresh") return "unknown";
24
- const target = applyModelAlias(model).trim().replace(/^models\//i, "").toLowerCase();
27
+ const target = catalogTarget(model);
25
28
  return catalog.models.some(id => id.toLowerCase() === target) ? "advertised" : "not-advertised";
26
29
  }
30
+ export type CatalogModelState = "advertised" | "disabled" | "not-advertised" | "unknown";
31
+ /** Google lists a family it has not enabled for the account as `<family>-disabled`. */
32
+ export function catalogModelState(catalog: ProviderCatalogEvidence, model: string, allowStale = false): CatalogModelState {
33
+ if (catalog.freshness !== "fresh" && !(allowStale && catalog.freshness === "stale")) return "unknown";
34
+ const target = catalogTarget(model);
35
+ const ids = catalog.models.map(id => id.toLowerCase());
36
+ if (!target.endsWith("-disabled") && ids.includes(target)) return "advertised";
37
+ const disabled = ids.some(id => {
38
+ if (!id.endsWith("-disabled")) return false;
39
+ const family = id.slice(0, -"-disabled".length);
40
+ return target === id || target === family || target.startsWith(`${family}-`);
41
+ });
42
+ return disabled ? "disabled" : "not-advertised";
43
+ }
@@ -79,6 +79,8 @@ export interface ProviderModel {
79
79
  export interface ModelListContext {
80
80
  ollamaModels: readonly string[];
81
81
  codexModels: readonly string[];
82
+ /** Providers with a usable account right now; lets discovery avoid stealing ids. */
83
+ activeProviders?: readonly string[];
82
84
  }
83
85
 
84
86
  export interface ProviderFeatures {
@@ -135,6 +137,9 @@ export interface ProviderAdapter {
135
137
  body: RequestBody,
136
138
  originalHeaders: Record<string, string>,
137
139
  signal?: AbortSignal,
140
+ options?: {
141
+ apiRetry?: boolean | Record<string, unknown>;
142
+ },
138
143
  ): Promise<ForwardedResponse>;
139
144
  /** Forward one allowlisted non-generation Code Assist operation. */
140
145
  forwardCodeAssistRequest?(
@@ -115,6 +115,18 @@ export function isOllamaQuotaPoolKey(poolKey: string): boolean {
115
115
  poolKey === "weekly";
116
116
  }
117
117
 
118
+ export function isSafePoolKey(poolKey: unknown): poolKey is string {
119
+ return (
120
+ typeof poolKey === "string" &&
121
+ poolKey.length > 0 &&
122
+ poolKey.length <= 64 &&
123
+ /^[a-z0-9][a-z0-9._:-]*$/.test(poolKey) &&
124
+ poolKey !== "__proto__" &&
125
+ poolKey !== "constructor" &&
126
+ poolKey !== "prototype"
127
+ );
128
+ }
129
+
118
130
  export function getProviderIdForPoolKey(poolKey: string): string {
119
131
  if (poolKey.startsWith("codex:") || poolKey.startsWith("openai-codex")) return "openai-codex";
120
132
  if (poolKey.startsWith("opencode-zen:") || poolKey === "opencode-zen") return "opencode-zen";
@@ -157,3 +169,25 @@ export function sortAccountCredentials<T extends { provider: string }>(credentia
157
169
  return 0;
158
170
  });
159
171
  }
172
+
173
+ /**
174
+ * Format remaining time until an ISO reset timestamp for RAW POLL logs using
175
+ * days, hours, and minutes depending on magnitude (e.g. "45m", "2h 8m", "6d 21h 8m").
176
+ */
177
+ export function formatQuotaResetRemaining(
178
+ resetTime: string,
179
+ now = Date.now(),
180
+ ): string {
181
+ const resetMs = Date.parse(resetTime);
182
+ if (!Number.isFinite(resetMs)) return "unknown";
183
+ const totalMinutes = Math.max(0, Math.round((resetMs - now) / 60_000));
184
+ if (totalMinutes < 60) return `${totalMinutes}m`;
185
+ const days = Math.floor(totalMinutes / 1440);
186
+ const hours = Math.floor((totalMinutes % 1440) / 60);
187
+ const minutes = totalMinutes % 60;
188
+ const parts: string[] = [];
189
+ if (days > 0) parts.push(`${days}d`);
190
+ if (hours > 0) parts.push(`${hours}h`);
191
+ if (minutes > 0) parts.push(`${minutes}m`);
192
+ return parts.join(" ");
193
+ }