tuxevil-rotator 4.4.1 → 4.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [4.4.3] - 2026-11-20
6
+
7
+ ### Fixed
8
+
9
+ - Enforce provider and model eligibility for direct requests, account selection, and retries across Antigravity and Codex, preventing requests from being sent to accounts without the required plan access.
10
+ - Record compatibility requests rejected before account selection in request history and spend logs, including their HTTP status.
11
+ - Calculate retry estimates from accounts eligible for the requested provider model so unavailable accounts do not distort cooldown responses.
12
+
13
+ ## [4.4.2] - 2026-11-14
14
+
15
+ ### Changed
16
+
17
+ - **Model access panel**: Rebuild the Models page's Model access panel from the dashboard's shared components and reduce it to one dropdown. The account select sits in the panel header; provider and plan are segmented controls in one row (plans that do not change the provider's rules fold behind "+N"; the plan control is hidden when plans do not matter), and client appears only for providers with client-dependent rules. Checking a model runs as you type, with the verdict inside the field, the reason and plan source on two quiet lines below, an "As of today" link that opens a date picker, and suggestions from the rules and the account's advertised models. Account observations and advertised models are one line of links that open inset details. Rules show model, access state, plans and note, with evidence dates in a tooltip, end dates under the state and the source as an icon link.
18
+
19
+ ### Fixed
20
+
21
+ - Preserve a newer plan selection when a previous plan declaration finishes saving, and guard access checks during the save.
22
+
23
+ ### Contributors
24
+
25
+ - Thanks to [@CyR1en](https://github.com/CyR1en) for redesigning the Model access panel in [PR #49](https://github.com/tuxevil/tuxevil-rotator/pull/49).
26
+
5
27
  ## [4.4.1] - 2026-11-09
6
28
 
7
29
  ### Fixed
package/README.md CHANGED
@@ -55,6 +55,10 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
55
55
 
56
56
  ## Current Model Update
57
57
 
58
+ - **v4.4.3: Account model access and routing visibility**: Enforce provider plan eligibility for direct requests, selection, and retries across Antigravity and Codex. Admission rejections now appear in request history, and cooldown estimates use accounts eligible for the requested model. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.3))
59
+
60
+ - **v4.4.2: Model access dashboard**: A redesigned Model access panel with live checks, account evidence, clearer rules and safer plan saving. Thanks to [@CyR1en](https://github.com/CyR1en) for [PR #49](https://github.com/tuxevil/tuxevil-rotator/pull/49). ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.2))
61
+
58
62
  - **v4.4.1: Telemetry reliability**: Prevent failed or timed-out flag telemetry requests from terminating the rotator, and update the development-only minimatch override. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.1))
59
63
  - **v4.4.0: Benchmark-informed auto routing, provider access, and usage visibility**: Rank eligible models with Artificial Analysis scores and effort-aware, quota-conscious fallbacks; enforce provider/account entitlements; add access diagnostics and aggregated usage-limit views. Includes bounded auto recovery and session continuity, Ollama empty-output handling, and prompt-compression improvements. The Playground now follows the dashboard design system. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.4.0); [PR #46](https://github.com/tuxevil/tuxevil-rotator/pull/46) by [@CyR1en](https://github.com/CyR1en))
60
64
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tuxevil-rotator",
3
- "version": "4.4.1",
3
+ "version": "4.4.3",
4
4
  "description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -64,6 +64,7 @@
64
64
  "@types/pg": "^8.20.0",
65
65
  "c8": "^11.0.0",
66
66
  "eslint": "^10.6.0",
67
+ "happy-dom": "^21.0.4",
67
68
  "typescript": "^5.7.0",
68
69
  "typescript-eslint": "^8.62.1"
69
70
  },
@@ -18,6 +18,10 @@ export interface AutoAccountScope {
18
18
  modelId: string;
19
19
  }
20
20
 
21
+ export function requiresAntigravityAccessPolicy(model: string): boolean {
22
+ return /^(?:claude-(?:opus|sonnet)-(?:5-5|4-6)(?:-|$)|gemini-4(?:-|$)|gemini-3\.(?:7-flash|6-flash|1-pro)(?:-|$))/i.test(model);
23
+ }
24
+
21
25
  function matchesRule(rule: (typeof MODEL_ACCESS_RULES)[number], model: string): boolean {
22
26
  if (rule.modelPrefix === "*-free") return model.endsWith("-free");
23
27
  return rule.exact
@@ -111,6 +115,14 @@ export function evaluateAutoModelAccess(
111
115
  }
112
116
 
113
117
  if (plan === "unknown") {
118
+ // A verified Free-plan model is also safe to try when the Codex plan is
119
+ // unknown; paid-only and unlisted models still require a known plan.
120
+ if (provider === "openai-codex" && MODEL_ACCESS_RULES.some((rule) =>
121
+ rule.provider === provider && rule.plans.includes("free") && rule.state === "allowed" &&
122
+ matchesRule(rule, model) && evaluateModelAccess({ provider, model, plan: "free", at: new Date(now).toISOString() }).state === "allowed",
123
+ )) {
124
+ return { eligible: true, plan, planSource, reason: "model is documented for Codex Free" };
125
+ }
114
126
  const hasPlanSpecificRule = MODEL_ACCESS_RULES.some((rule) =>
115
127
  rule.provider === provider && matchesRule(rule, model),
116
128
  );
@@ -143,11 +155,24 @@ export function evaluateAutoModelAccess(
143
155
  at: new Date(now).toISOString(),
144
156
  });
145
157
 
146
- // Free accounts have a complete, operator-confirmed catalog for these
147
- // providers. Unknown or stale entries must not silently inherit free access.
158
+ // An overdue review must not turn a documented denial into permission.
159
+ if (provider === "google-antigravity" && matchingRules.some((rule) =>
160
+ (rule.state === "blocked" || rule.state === "conditional" ||
161
+ (rule.validUntil !== undefined && now >= Date.parse(`${rule.validUntil}T00:00:00Z`))) &&
162
+ now >= Date.parse(`${rule.validFrom}T00:00:00Z`),
163
+ )) {
164
+ return { eligible: false, plan, planSource, reason: decision.reason };
165
+ }
166
+
167
+ if (provider === "google-antigravity" && model.startsWith("gemini-4-") && decision.state === "unknown") {
168
+ return { eligible: false, plan, planSource, reason: decision.reason };
169
+ }
170
+
171
+ // Unknown or stale entries must not silently inherit free access.
148
172
  if ((provider === "ollama" || provider === "openai-codex") && plan === "free") {
149
173
  const confirmedAllow = matchingRules.some((rule) =>
150
- rule.state === "allowed" && rule.evidence === "operator-confirmed",
174
+ rule.state === "allowed" && (rule.evidence === "operator-confirmed" ||
175
+ (provider === "openai-codex" && rule.evidence === "documented")),
151
176
  );
152
177
  if (!confirmedAllow || decision.state === "unknown") {
153
178
  return {
@@ -156,7 +181,7 @@ export function evaluateAutoModelAccess(
156
181
  planSource,
157
182
  reason: confirmedAllow
158
183
  ? "Free-plan model policy needs re-verification"
159
- : "model is outside the confirmed Free-plan auto-routing list",
184
+ : provider === "ollama" ? "model is outside the confirmed Free-plan auto-routing list" : "model is outside the confirmed Free-plan model list",
160
185
  };
161
186
  }
162
187
  }
package/src/compat.ts CHANGED
@@ -777,6 +777,7 @@ function recordCompatFailure(
777
777
  rotator: AccountRotator,
778
778
  body: RequestBody,
779
779
  outcome: RotationOutcome<unknown>,
780
+ startedAt: number,
780
781
  options?: {
781
782
  callType?: string;
782
783
  apiKeyHash?: string | null;
@@ -785,7 +786,21 @@ function recordCompatFailure(
785
786
  rawResponse?: unknown;
786
787
  },
787
788
  ): void {
788
- if (outcome.ok || !outcome.context) return;
789
+ if (outcome.ok) return;
790
+ if (!outcome.context) {
791
+ const model = body.displayModel || body.model;
792
+ const durationMs = Date.now() - startedAt;
793
+ rotator.recordRequestLog({ model, account: "No account", statusCode: outcome.status, ttfbMs: durationMs, totalMs: durationMs, inputTokens: 0, outputTokens: 0 });
794
+ logSpend({
795
+ apiKeyHash: options?.apiKeyHash || null, model, accountEmail: null,
796
+ callType: options?.callType || "compat", status: "failure", promptTokens: 0, completionTokens: 0,
797
+ startTime: new Date(startedAt).toISOString(), endTime: new Date().toISOString(),
798
+ ttfbMs: durationMs, durationMs, requestMessages: options?.rawRequest || body.request || body,
799
+ responseContent: null, requesterIp: options?.requesterIp || null,
800
+ metadata: { statusCode: outcome.status, stage: "admission" },
801
+ });
802
+ return;
803
+ }
789
804
  recordCompatOutcome(
790
805
  rotator,
791
806
  body,
@@ -2301,6 +2316,7 @@ async function completeResponsesViaRotator(
2301
2316
  context?: RotationAttemptContext;
2302
2317
  compressionStats?: CompressionStats | null;
2303
2318
  }> {
2319
+ const startedAt = Date.now();
2304
2320
  const createdAt = Math.floor(Date.now() / 1000);
2305
2321
  const controller = new AbortController();
2306
2322
  const abort = (): void => controller.abort();
@@ -2346,7 +2362,7 @@ async function completeResponsesViaRotator(
2346
2362
  controller.signal,
2347
2363
  );
2348
2364
  if (!outcome.ok) {
2349
- recordCompatFailure(rotator, body, outcome, options);
2365
+ recordCompatFailure(rotator, body, outcome, startedAt, options);
2350
2366
  return {
2351
2367
  completion: { text: "", inputTokens: 0, outputTokens: 0 },
2352
2368
  status: outcome.status,
@@ -2396,6 +2412,7 @@ async function completeViaRotator(
2396
2412
  isDeduplicated?: boolean;
2397
2413
  compressionStats?: CompressionStats | null;
2398
2414
  }> {
2415
+ const startedAt = Date.now();
2399
2416
  const cfg = typeof rotator?.getConfig === "function" ? rotator.getConfig() : undefined;
2400
2417
  const enabled = cfg?.idempotencyEnabled === true;
2401
2418
  const windowMs = cfg?.idempotencyWindowMs ?? 2000;
@@ -2531,7 +2548,7 @@ async function completeViaRotator(
2531
2548
  }
2532
2549
 
2533
2550
  if (!outcome.ok) {
2534
- recordCompatFailure(rotator, body, outcome, options);
2551
+ recordCompatFailure(rotator, body, outcome, startedAt, options);
2535
2552
  if (outcome.status === 404) {
2536
2553
  compatLogger.warn(
2537
2554
  `Compat upstream 404 endpoint=${outcome.endpoint || "unknown"} ${summarizeCompatRequest(body)} error=${(outcome.errorText || "").slice(0, 300)}`,
@@ -1,4 +1,4 @@
1
- /** Policy data for access explanations and auto eligibility; it never authorizes explicit requests. */
1
+ /** Policy data for access explanations and account eligibility. */
2
2
  export type AccessState = "allowed" | "blocked" | "conditional" | "unknown";
3
3
  export interface AccessRule {
4
4
  id: string;
@@ -17,15 +17,24 @@ export interface AccessRule {
17
17
  note: string;
18
18
  }
19
19
  const google = "https://antigravity.google/docs/models";
20
- const rule = (id: string, provider: string, plans: string[], modelPrefix: string, state: AccessState, evidence: AccessRule["evidence"], source: string, note: string, extra: Partial<AccessRule> = {}): AccessRule => ({ id, provider, plans, modelPrefix, state, evidence, source, verifiedAt: "2026-10-30", validFrom: "2026-10-30", reviewAfter: "2026-11-29", note, ...extra });
20
+ const rule = (id: string, provider: string, plans: string[], modelPrefix: string, state: AccessState, evidence: AccessRule["evidence"], source: string, note: string, extra: Partial<AccessRule> = {}): AccessRule => ({ id, provider, plans, modelPrefix, state, evidence, source, verifiedAt: provider === "google-antigravity" ? "2026-11-20" : "2026-10-30", validFrom: "2026-10-30", reviewAfter: provider === "google-antigravity" ? "2026-12-20" : "2026-11-29", note, ...extra });
21
21
  export const MODEL_ACCESS_RULES: readonly AccessRule[] = [
22
22
  rule("ag-flash-free", "google-antigravity", ["free", "plus", "pro-trial", "pro-paid", "ultra", "enterprise"], "gemini-3.8-flash", "allowed", "documented", google, "Gemini 3.8 Flash is listed for Free/Plus."),
23
- ...["claude-sonnet-4-6", "claude-opus-4-6"].map(model => rule(`ag-legacy-${model}`, "google-antigravity", ["free", "plus"], model, "allowed", "documented", google, "Removal announced for November 2; diagnostic cutoff uses UTC, exact upstream rollout may differ.", { validUntil: "2026-11-02" })),
24
- ...["gemini-4-argon", "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.")),
23
+ ...["gemini-3.7-flash", "gemini-3.6-flash", "gemini-3.1-pro"].flatMap(model => [
24
+ rule(`ag-enterprise-only-${model}`, "google-antigravity", ["free", "plus", "pro-trial", "pro-paid", "ultra"], model, "blocked", "documented", google, "Listed only for Enterprise."),
25
+ rule(`ag-enterprise-${model}`, "google-antigravity", ["enterprise"], model, "allowed", "documented", google, "Listed for Enterprise."),
26
+ ]),
27
+ ...["claude-sonnet-4-6", "claude-opus-4-6"].map(model => rule(`ag-legacy-${model}`, "google-antigravity", ["free", "plus", "pro-paid", "pro-trial"], model, "allowed", "documented", google, "Removal announced for November 18; exact upstream rollout may differ.", { validUntil: "2026-11-18" })),
28
+ ...["claude-sonnet-4-6", "claude-opus-4-6"].map(model => rule(`ag-legacy-unavailable-${model}`, "google-antigravity", ["ultra", "enterprise"], model, "blocked", "documented", google, "Not listed for Ultra or Enterprise.")),
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.")),
25
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.")),
26
- ...["gemini-4-argon", "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.")),
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."),
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
+ rule("ag-neon-trial", "google-antigravity", ["pro-trial"], "gemini-4-neon", "conditional", "documented", google, "Only eligible premium-device trials."),
27
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."),
28
- ...["gpt-6-luna", "gpt-5.6-terra", "gpt-5.6-luna"].map(model => rule(`codex-free-${model}`, "openai-codex", ["free"], model, "allowed", "operator-confirmed", "Operator account-access report, 2026-10-30", "Confirmed as available on Codex Free accounts; live quota and account entitlement still apply.")),
37
+ ...["gpt-6-luna", "gpt-5.6-terra"].map(model => rule(`codex-free-${model}`, "openai-codex", ["free"], model, "allowed", "documented", "https://help.openai.com/en/articles/20001354-gpt-6-and-other-models-in-chatgpt", "Listed for Free; live account entitlement and quota still apply.", { exact: true, verifiedAt: "2026-11-20", reviewAfter: "2026-12-20" })),
29
38
  rule("codex-terra61-free", "openai-codex", ["free"], "gpt-6.1-terra", "blocked", "documented", "https://learn.chatgpt.com/docs/pricing", "Official ChatGPT Work/Codex availability lists paid plans for Terra 6.1. Free is not included; account-specific provider rejections are separate evidence.", { exact: true, verifiedAt: "2026-10-31", validFrom: "2026-10-26", reviewAfter: "2026-11-30" }),
30
39
  rule("codex-terra61-plus", "openai-codex", ["plus"], "gpt-6.1-terra", "allowed", "documented", "https://learn.chatgpt.com/docs/pricing", "Terra 6.1 is listed for Plus in Work/Codex; rollout, surface access, quota and account restrictions still apply.", { exact: true, verifiedAt: "2026-10-31", validFrom: "2026-10-26", reviewAfter: "2026-11-30" }),
31
40
  ...["beam", "gemma4:31b", "gpt-oss:120b", "gpt-oss:20b", "nemotron-3-nano:30b", "nemotron-3-super", "nemotron-3-ultra"].map(model => rule(`ollama-free-${model}`, "ollama", ["free"], model, "allowed", "operator-confirmed", "Operator-provided Ollama free-credit list, 2026-10-30", "Included in the supplied free-credit list; quota and live entitlement are separate.")),
package/src/proxy.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { serveAccessProbe } from "./access-probe.js";
2
+ import { requiresAntigravityAccessPolicy } from "./auto-model-access.js";
2
3
  import { observeAccessAttempt, logAccessPolicyShadow } from "./access-evidence.js";
3
4
  import { serveModelAccessApi, serveProviderPlanApi } from "./model-access-api.js";
4
5
  import { createUsageLimitsHandler, USAGE_LIMITS_PATH } from "./usage-limits.js";
@@ -1278,8 +1279,12 @@ export async function withRotation<T>(
1278
1279
  ollamaModels: new Set(rotator.getOllamaModels?.() ?? []),
1279
1280
  codexModels: new Set(rotator.getCodexModels?.() ?? []),
1280
1281
  })?.id;
1281
- const autoScope = body.displayModel?.toLowerCase() === "auto" && providerId
1282
- ? { providerId, modelId: model }
1282
+ const policyModel = requiresAntigravityAccessPolicy(model) || body.displayModel?.toLowerCase() === "auto"
1283
+ ? model
1284
+ : body.catalogModel ?? model;
1285
+ const autoScope = providerId && (body.displayModel?.toLowerCase() === "auto" ||
1286
+ (providerId === DEFAULT_PROVIDER && requiresAntigravityAccessPolicy(policyModel)))
1287
+ ? { providerId, modelId: policyModel }
1283
1288
  : undefined;
1284
1289
  const modelQuotaFamily = resolveQuotaModelKey(model) ??
1285
1290
  resolveQuotaModelKey(applyModelAlias(model));
@@ -1311,7 +1316,7 @@ export async function withRotation<T>(
1311
1316
  context?: RotationAttemptContext,
1312
1317
  ): RotationOutcome<T> => {
1313
1318
  log(`[${model}] No healthy account available: ${reason}`, rotator, "warn");
1314
- const retryAfterMs = rotator.getRetryAfterMs(model, providerId);
1319
+ const retryAfterMs = rotator.getRetryAfterMs(model, providerId, autoScope);
1315
1320
  const contextFields = context
1316
1321
  ? { context, totalMs: Date.now() - context.requestStartMs }
1317
1322
  : {};
@@ -1784,7 +1789,7 @@ async function handleProxyRequest(
1784
1789
  const sendNoAccountsAvailable = (reason: string): void => {
1785
1790
  if (clientController.signal.aborted || res.destroyed) return;
1786
1791
  proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
1787
- const retryAfterMs = rotator.getRetryAfterMs(body.model, providerId);
1792
+ const retryAfterMs = rotator.getRetryAfterMs(body.model, providerId, accessScope);
1788
1793
  if (retryAfterMs > 0) {
1789
1794
  const retrySec = Math.ceil(retryAfterMs / 1000);
1790
1795
  res.writeHead(429, {
@@ -1877,6 +1882,10 @@ async function handleProxyRequest(
1877
1882
  res.end(decision.errorText || JSON.stringify({ error: "Upstream error" }));
1878
1883
  };
1879
1884
 
1885
+ const policyModel = requiresAntigravityAccessPolicy(body.model) ? body.model : body.catalogModel ?? body.model;
1886
+ const accessScope = providerId === DEFAULT_PROVIDER && requiresAntigravityAccessPolicy(policyModel)
1887
+ ? { providerId, modelId: policyModel }
1888
+ : undefined;
1880
1889
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1881
1890
  const maxAttempts = maxRetries + 1;
1882
1891
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
@@ -1889,6 +1898,7 @@ async function handleProxyRequest(
1889
1898
  body.model,
1890
1899
  clientController.signal,
1891
1900
  providerId,
1901
+ accessScope,
1892
1902
  );
1893
1903
  if (!account) {
1894
1904
  if (clientController.signal.aborted || res.destroyed) return;
@@ -1913,7 +1923,7 @@ async function handleProxyRequest(
1913
1923
  };
1914
1924
  const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
1915
1925
  releaseCurrentAccount();
1916
- const nextAccount = await rotator.rotateToNext(body.model, account, providerId);
1926
+ const nextAccount = await rotator.rotateToNext(body.model, account, providerId, accessScope);
1917
1927
  return nextAccount;
1918
1928
  };
1919
1929
  proxyLog(
@@ -2138,7 +2148,7 @@ async function handleProxyRequest(
2138
2148
  res.end();
2139
2149
 
2140
2150
  if (shouldRotate) {
2141
- await rotator.rotateToNext(body.model, account, providerId);
2151
+ await rotator.rotateToNext(body.model, account, providerId, accessScope);
2142
2152
  }
2143
2153
  return;
2144
2154
  } catch (err) {
package/src/rotator.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { summarizeAutoAccess } from "./auto-access-shadow.js";
2
- import { evaluateAutoModelAccess, type AutoAccountScope } from "./auto-model-access.js";
2
+ import { evaluateAutoModelAccess, requiresAntigravityAccessPolicy, type AutoAccountScope } from "./auto-model-access.js";
3
3
  import { primeOllamaContextWindows } from "./providers/ollama/context-window.js";
4
4
  import {
5
5
  type AccountConfig,
@@ -1740,7 +1740,7 @@ export class AccountRotator {
1740
1740
  if (!access.eligible) {
1741
1741
  return {
1742
1742
  reason: "provider-ineligible",
1743
- detail: `auto access policy: ${access.reason}`,
1743
+ detail: `model access policy: ${access.reason}`,
1744
1744
  };
1745
1745
  }
1746
1746
  }
@@ -2117,6 +2117,7 @@ export class AccountRotator {
2117
2117
  autoScope?: AutoAccountScope,
2118
2118
  ): Promise<AccountRuntime | null> {
2119
2119
  if (signal?.aborted) return null;
2120
+ autoScope ??= this.getExplicitAccessScope(model, providerId);
2120
2121
  const queueKey = this.getRequestQueueKey(model, providerId);
2121
2122
  if (
2122
2123
  this.hasQueuedRequest(queueKey) ||
@@ -2793,6 +2794,7 @@ export class AccountRotator {
2793
2794
  autoScope?: AutoAccountScope,
2794
2795
  ): Promise<AccountRuntime | null> {
2795
2796
  if (this.isProtectivePauseActive(Date.now())) return null;
2797
+ autoScope ??= this.getExplicitAccessScope(model, providerId);
2796
2798
  const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
2797
2799
  let excludeIdx: number;
2798
2800
  if (typeof failedAccount === "number") {
@@ -2815,6 +2817,13 @@ export class AccountRotator {
2815
2817
  : this.rotateDefault(Date.now(), false, excludeIdx);
2816
2818
  }
2817
2819
 
2820
+ private getExplicitAccessScope(model?: string, providerId?: string): AutoAccountScope | undefined {
2821
+ if (!model) return undefined;
2822
+ const provider = providerId ?? getProviderIdForPoolKey(this.resolveRequestPoolKey(model, providerId));
2823
+ return provider === "openai-codex" || (provider === DEFAULT_PROVIDER && requiresAntigravityAccessPolicy(model))
2824
+ ? { providerId: provider, modelId: model } : undefined;
2825
+ }
2826
+
2818
2827
  // Record a successful request. Returns true if rotation is needed.
2819
2828
  recordRequest(account: AccountRuntime, model?: string, providerId?: string): boolean {
2820
2829
  account.requestsSinceRotation++;
@@ -4277,6 +4286,7 @@ export class AccountRotator {
4277
4286
  for (const account of this.accounts) {
4278
4287
  if (account.disabled || account.flagged) continue;
4279
4288
  const candidateProviderId = providerId ?? getProviderIdForPoolKey(modelKey);
4289
+ if (this.getProviderEligibilityRejection(account, modelKey, now)?.reason === "provider-ineligible") continue;
4280
4290
  if (
4281
4291
  autoScope &&
4282
4292
  !evaluateAutoModelAccess(
@@ -4333,9 +4343,9 @@ export class AccountRotator {
4333
4343
  return retryTimes.length > 0 ? Math.min(...retryTimes) : null;
4334
4344
  }
4335
4345
 
4336
- getRetryAfterMs(model?: string, providerId?: string): number {
4346
+ getRetryAfterMs(model?: string, providerId?: string, autoScope?: AutoAccountScope): number {
4337
4347
  const now = Date.now();
4338
- const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId);
4348
+ const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId, autoScope ?? this.getExplicitAccessScope(model, providerId));
4339
4349
  if (retryTimes.length === 0) return 0;
4340
4350
  return Math.max(1000, Math.min(...retryTimes) - now);
4341
4351
  }
@@ -204,7 +204,7 @@ export function Segmented<T extends string>({
204
204
  size = "md",
205
205
  class: className,
206
206
  }: {
207
- options: Array<{ value: T; label: ComponentChildren; title?: string }>;
207
+ options: Array<{ value: T; label: ComponentChildren; title?: string; disabled?: boolean }>;
208
208
  value: T;
209
209
  onChange: (value: T) => void;
210
210
  label: string;
@@ -220,6 +220,7 @@ export function Segmented<T extends string>({
220
220
  class={option.value === value ? "is-active" : undefined}
221
221
  aria-pressed={option.value === value}
222
222
  title={option.title}
223
+ disabled={option.disabled}
223
224
  onClick={() => onChange(option.value)}
224
225
  >
225
226
  {option.label}
@@ -1,10 +1,65 @@
1
+ // Model access: what each plan is documented to reach, and an explainer for
2
+ // one account, provider and model. Informational only; nothing here routes.
3
+
1
4
  import type { JSX } from "preact";
2
- import { useEffect, useState } from "preact/hooks";
5
+ import { useEffect, useRef, useState } from "preact/hooks";
3
6
  import type { AccessReport } from "../../model-access-api.js";
7
+ import type { AccessRule, AccessState } from "../../model-access.js";
8
+ import { formatDateTime, pluralize } from "../lib/format.js";
9
+ import { providerLabel, type Tone } from "../lib/status.js";
4
10
  import { api } from "../state/api.js";
5
11
  import { query } from "../state/router.js";
6
12
  import { masker } from "../state/store.js";
7
- import { Panel, Button } from "../components/ui.js";
13
+ import { Icon } from "../components/icons.js";
14
+ import { EmptyState, Panel, SearchInput, Segmented, Spinner } from "../components/ui.js";
15
+
16
+ const PROVIDERS = ["google-antigravity", "openai-codex", "ollama", "opencode-zen"];
17
+ const PLANS = ["free", "plus", "pro-trial", "pro-paid", "ultra", "enterprise"];
18
+ const CLIENTS = ["unknown", "opencode", "other"] as const;
19
+ const CLIENT_LABEL: Record<(typeof CLIENTS)[number], string> = { unknown: "Unknown", opencode: "OpenCode", other: "Other" };
20
+
21
+ const STATE: Record<AccessState, { label: string; tone: Tone }> = {
22
+ allowed: { label: "Allowed", tone: "ok" },
23
+ blocked: { label: "Blocked", tone: "bad" },
24
+ conditional: { label: "Conditional", tone: "warn" },
25
+ unknown: { label: "Unknown", tone: "neutral" },
26
+ };
27
+
28
+ const EVIDENCE: Record<AccessRule["evidence"], string> = {
29
+ documented: "Documented",
30
+ "operator-confirmed": "Operator confirmed",
31
+ "operator-pending": "Operator pending",
32
+ };
33
+
34
+ const PLAN_SOURCE: Record<NonNullable<AccessReport["planSource"]>, string> = {
35
+ "query-assumption": "Assumed plan",
36
+ "single-provider-account": "Plan from the account tier",
37
+ "provider-declaration": "Plan from the stored declaration",
38
+ unknown: "Plan unknown",
39
+ };
40
+
41
+ function sourceHost(url: string): string {
42
+ try {
43
+ return new URL(url).hostname.replace(/^www\./, "");
44
+ } catch {
45
+ return url;
46
+ }
47
+ }
48
+
49
+ function planList(plans: string[]): string {
50
+ if (plans.includes("*")) return "Any plan";
51
+ return plans.length <= 3 ? plans.join(", ") : `${plans.slice(0, 2).join(", ")} +${plans.length - 2}`;
52
+ }
53
+
54
+ function StateMark({ state, title }: { state: AccessState; title?: string }): JSX.Element {
55
+ const meta = STATE[state];
56
+ return (
57
+ <span class={`access-state tone-${meta.tone}`} title={title}>
58
+ <span class="access-dot" aria-hidden="true" />
59
+ {meta.label}
60
+ </span>
61
+ );
62
+ }
8
63
 
9
64
  export function ModelAccessPanel(): JSX.Element {
10
65
  const [now, setNow] = useState(Date.now());
@@ -13,76 +68,344 @@ export function ModelAccessPanel(): JSX.Element {
13
68
  const [accountId, setAccount] = useState(query.value.get("accessAccount") ?? "");
14
69
  const [provider, setProvider] = useState("google-antigravity");
15
70
  const [plan, setPlan] = useState("");
16
- const [client, setClient] = useState("unknown");
71
+ const [morePlans, setMorePlans] = useState(false);
72
+ const [client, setClient] = useState<(typeof CLIENTS)[number]>("unknown");
17
73
  const [at, setAt] = useState("");
74
+ const [pickDate, setPickDate] = useState(false);
18
75
  const [ruleFilter, setRuleFilter] = useState("");
19
76
  const [model, setModel] = useState("gemini-3.8-flash-medium");
20
- const [decision, setDecision] = useState<AccessReport | null>(null);
21
- const [decisionKey, setDecisionKey] = useState("");
22
- const formKey = JSON.stringify([accountId, provider, plan, client, model, at]);
23
- const [error, setError] = useState("");
24
- const [busy, setBusy] = useState(false);
77
+ const [decision, setDecision] = useState<{ report: AccessReport; key: string; model: string } | null>(null);
78
+ const [evidence, setEvidence] = useState<"observations" | "catalog" | null>(null);
79
+ const [loadError, setLoadError] = useState("");
80
+ const [checkError, setCheckError] = useState("");
81
+ const [saveError, setSaveError] = useState("");
82
+ const [saving, setSaving] = useState(false);
83
+ const trimmedModel = model.trim();
84
+ const formKey = JSON.stringify([accountId, provider, plan, client, trimmedModel, at]);
85
+ const request = useRef(0);
86
+ const currentForm = useRef(formKey);
87
+ currentForm.current = formKey;
88
+
25
89
  useEffect(() => {
26
90
  let active = true;
27
- api.modelAccess().then(value => { if (active) setReport(value); }).catch(() => { if (active) setError("Access rules could not be loaded."); });
91
+ api.modelAccess().then(value => { if (active) setReport(value); }).catch(() => { if (active) setLoadError("Access rules could not be loaded."); });
28
92
  return () => { active = false; };
29
93
  }, []);
30
- // Clear an earlier decision when its inputs no longer apply.
31
- useEffect(() => { setDecision(null); }, [accountId, provider, plan, client, model, at]);
94
+
32
95
  const selected = report?.accounts.find(a => a.id === accountId);
33
96
  useEffect(() => {
34
97
  if (selected && !selected.providers.includes(provider)) setProvider(selected.providers[0] ?? "google-antigravity");
35
98
  }, [selected, provider]);
99
+
36
100
  const catalog = selected?.providerCatalogs?.find(c => c.provider === provider);
37
101
  const catalogFreshness = catalog?.freshness === "fresh" && catalog.expiresAt !== null && catalog.expiresAt <= now ? "stale" : catalog?.freshness;
38
102
  const declaredPlan = selected?.providerPlans.find(p => p.provider === provider);
39
- const effectivePlan = plan || declaredPlan?.plan || selected?.inferredPlan || "unknown";
40
- const rules = report?.rules.filter(r => r.modelPrefix.toLowerCase().includes(ruleFilter.toLowerCase()) && r.provider === provider && ((effectivePlan === "unknown" || !accountId && !plan) || r.plans.includes(effectivePlan) || r.plans.includes("*"))) ?? [];
41
- const inspect = async () => {
42
- setBusy(true); setError("");
43
- try {
44
- const params = new URLSearchParams({ provider, model, client });
103
+ const knownPlan = declaredPlan?.plan || selected?.inferredPlan || "unknown";
104
+ const effectivePlan = plan || knownPlan;
105
+ const allPlans = effectivePlan === "unknown" || !accountId && !plan;
106
+ const ruleSet = report?.rules.filter(r => r.provider === provider) ?? [];
107
+ const providerRules = ruleSet.filter(r => allPlans || r.plans.includes(effectivePlan) || r.plans.includes("*"));
108
+ const rules = providerRules.filter(r => r.modelPrefix.toLowerCase().includes(ruleFilter.toLowerCase()));
109
+ const observations = selected?.observations.filter(o => o.provider === provider) ?? [];
110
+
111
+ // Plans that change this provider's rules come first; the rest fold away.
112
+ const rulePlans = new Set(ruleSet.flatMap(r => r.plans).filter(p => p !== "*"));
113
+ const offeredPlans = PLANS;
114
+ const relevantPlans = offeredPlans.filter(p => rulePlans.has(p) || p === plan);
115
+ // Folding away a single plan saves nothing, so only fold two or more.
116
+ const foldable = offeredPlans.length - relevantPlans.length >= 2;
117
+ const planChoices = morePlans || !foldable ? offeredPlans : relevantPlans;
118
+ const planMatters = rulePlans.size > 0;
119
+ const clientMatters = ruleSet.some(r => r.client);
120
+
121
+ // Suggestions for the model field: rule families and the account's advertised IDs.
122
+ const suggestions = [...new Set([...ruleSet.filter(r => !r.modelPrefix.includes("*")).map(r => r.modelPrefix), ...(catalog?.models ?? [])])].sort();
123
+
124
+ // Explain as the inputs change. The previous answer stays visible, dimmed,
125
+ // until the new one arrives; late responses for older inputs are dropped.
126
+ const ready = Boolean(report) && (!accountId || Boolean(selected?.providers.includes(provider)));
127
+ useEffect(() => {
128
+ if (!ready || saving) return;
129
+ if (!trimmedModel) { request.current++; setDecision(null); setCheckError(""); return; }
130
+ const id = ++request.current;
131
+ const key = formKey;
132
+ const timer = setTimeout(() => {
133
+ const params = new URLSearchParams({ provider, model: trimmedModel, client });
45
134
  if (accountId) params.set("accountId", accountId);
46
135
  if (plan) params.set("plan", plan);
47
136
  if (at) params.set("at", at);
48
- const result = await api.modelAccess(params);
49
- setReport(result); setDecision(result); setDecisionKey(formKey);
50
- } catch { setError("Check the selected account, provider and model."); }
51
- finally { setBusy(false); }
52
- };
137
+ api.modelAccess(params)
138
+ .then(result => {
139
+ if (id !== request.current) return;
140
+ setReport(result); setDecision({ report: result, key, model: trimmedModel }); setCheckError("");
141
+ })
142
+ .catch(() => {
143
+ if (id !== request.current) return;
144
+ setDecision(null); setCheckError("Access could not be explained for this account, provider and model.");
145
+ });
146
+ }, 250);
147
+ return () => clearTimeout(timer);
148
+ }, [formKey, ready, saving]);
149
+
53
150
  const savePlan = async () => {
54
151
  if (!accountId || !plan) return;
55
- setBusy(true); setError("");
56
- try { setReport(await api.declareProviderPlan(accountId, provider, plan)); setPlan(""); setDecision(null); }
57
- catch { setError("Provider plan could not be persisted."); }
58
- finally { setBusy(false); }
152
+ const savedForm = formKey;
153
+ request.current++;
154
+ setSaving(true); setSaveError("");
155
+ try {
156
+ const updated = await api.declareProviderPlan(accountId, provider, plan);
157
+ request.current++;
158
+ setReport(updated);
159
+ if (currentForm.current === savedForm) setPlan("");
160
+ }
161
+ catch { setSaveError("The plan could not be saved."); }
162
+ finally { setSaving(false); }
59
163
  };
60
- return <Panel id="model-access" title="Model access" subtitle="Informational rules only. Quota, credentials, capabilities and routing are checked separately.">
61
- <div class="form-grid">
62
- <label>Account<select value={accountId} onChange={e => setAccount(e.currentTarget.value)}><option value="">No account — simulate policy</option>{report?.accounts.map(a => <option key={a.id} value={a.id}>{masker.value.email(a.label)}</option>)}</select></label>
63
- <label>Provider<select value={provider} onChange={e => setProvider(e.currentTarget.value)}>{["google-antigravity", "openai-codex", "ollama", "opencode-zen"].map(p => <option key={p}>{p}</option>)}</select></label>
64
- <label>Plan assumption<select value={plan} onChange={e => setPlan(e.currentTarget.value)}><option value="">Use known account plan</option>{["unknown", "free", "plus", "pro-trial", "pro-paid", "ultra", "enterprise"].map(p => <option key={p}>{p}</option>)}</select></label>
65
- <label>Client declaration<select value={client} onChange={e => setClient(e.currentTarget.value)}>{["unknown", "opencode", "other"].map(p => <option key={p}>{p}</option>)}</select></label>
66
- <label>Policy date (optional)<input type="date" value={at} onInput={e => setAt(e.currentTarget.value)} /></label>
67
- <label>Model ID<input value={model} onInput={e => setModel(e.currentTarget.value)} maxLength={256} /></label>
68
- </div>
69
- <p>Plan: {effectivePlan}. {selected && selected.providers.length > 1 ? "Linked providers need separate plan evidence." : "Pro without billing evidence remains unknown."} Client identity is not verified here.</p>
70
- <p>{declaredPlan ? `Stored provider declaration: ${declaredPlan.plan}, expires ${new Date(declaredPlan.expiresAt).toISOString()}.` : "No current provider-specific plan declaration."}</p>
71
- <Button onClick={() => { void savePlan(); }} disabled={busy || !accountId || !plan}>Save provider plan declaration</Button>
72
- <Button onClick={() => { void inspect(); }} disabled={busy || !report || !model}>{busy ? "Checking…" : "Explain access"}</Button>
73
- {error && <p role="alert">{error}</p>}
74
- {decisionKey === formKey && decision?.decision && <div role="status"><strong>{decision.decision.state}</strong><p>{decision.decision.reason}</p><p>Plan source: {decision.planSource}. This result does not grant access.</p><p>Account catalog: {decision.catalogAvailability?.expiresAt != null && decision.catalogAvailability.expiresAt <= now ? "unknown (expired snapshot)" : decision.catalogAvailability?.state ?? "unknown"}.</p></div>}
75
- {selected && <details><summary>Recent account observations ({selected.observations.filter(o => o.provider === provider).length})</summary>
76
- <p>Latest result per model and declared client. No plan inference or routing blocks are created.</p>
77
- <div class="table-wrap"><table><thead><tr><th>Model</th><th>Client</th><th>Result</th><th>HTTP</th><th>Observed</th><th>Expires</th></tr></thead><tbody>{selected.observations.filter(o => o.provider === provider).map(o => <tr key={`${o.provider}/${o.model}/${o.client}`}><td>{o.model}</td><td>{o.client}</td><td>{o.kind === "model-unavailable" ? "Provider rejects this model for this account" : o.kind}</td><td>{o.status ?? "—"}</td><td>{new Date(o.observedAt).toISOString()}</td><td>{new Date(o.expiresAt).toISOString()}</td></tr>)}</tbody></table></div>
78
- </details>}
79
- {selected && <details><summary>Provider-advertised models ({catalog?.observedAt == null ? "unknown" : catalog.models.length})</summary>
80
- <p>{catalog ? `Source: ${catalog.source}. Snapshot: ${catalogFreshness}. Observed: ${catalog.observedAt === null ? "unknown" : new Date(catalog.observedAt).toISOString()}. Valid until: ${catalog.expiresAt === null ? "unknown" : new Date(catalog.expiresAt).toISOString()}.` : "No account-level provider catalog is available for this provider."}</p>
81
- <p>Advertisement is separate from subscription rules and observed access. Missing or stale data means unknown.</p>
82
- {catalog && <ul>{catalog.models.map(id => <li key={id}>{id}</li>)}</ul>}
83
- </details>}
84
- <label>Filter rule models<input value={ruleFilter} onInput={e => setRuleFilter(e.currentTarget.value)} /></label>
85
- <div class="table-wrap"><table><thead><tr><th>Model / family</th><th>Plans</th><th>Declared access</th><th>Evidence</th><th>Availability ends</th><th>Notes / source</th></tr></thead><tbody>{rules.map(r => <tr key={r.id}><td>{r.modelPrefix}{r.exact ? " (exact model)" : ""}</td><td>{r.plans.join(", ")}</td><td>{r.state}</td><td>{r.evidence}<br />{r.verifiedAt}<br />Review: {r.reviewAfter}</td><td>{r.validUntil ?? "Not specified"}</td><td>{r.note}<br />{r.source.startsWith("https://") ? <a href={r.source} target="_blank" rel="noreferrer">Source</a> : r.source}</td></tr>)}</tbody></table></div>
86
- {!report && !error && <p>Loading access rules…</p>}
87
- </Panel>;
164
+
165
+ let planHint: string;
166
+ if (declaredPlan) planHint = `Stored declaration, expires ${formatDateTime(declaredPlan.expiresAt)}`;
167
+ else if (selected && selected.providers.length > 1) planHint = "Linked providers need separate plan evidence";
168
+ else if (selected && selected.inferredPlan !== "unknown") planHint = "From the account tier";
169
+ else if (selected) planHint = "Pro without billing evidence stays unknown";
170
+ else planHint = "Lists every rule; checks stay unknown without a plan";
171
+
172
+ const result = decision?.report;
173
+ const pending = decision !== null && decision.key !== formKey;
174
+ const catalogState = result?.catalogAvailability;
175
+ const catalogText = !catalogState || catalogState.state === "unknown"
176
+ ? null
177
+ : catalogState.expiresAt != null && catalogState.expiresAt <= now
178
+ ? "Catalog snapshot expired"
179
+ : catalogState.state === "advertised" ? "In the account catalog" : "Not in the account catalog";
180
+
181
+ const meta = result?.decision
182
+ ? [PLAN_SOURCE[result.planSource ?? "unknown"], catalogText, clientMatters ? "Client declared, not verified" : null, "Does not grant access"].filter(Boolean).join(" · ")
183
+ : null;
184
+
185
+ return (
186
+ <Panel
187
+ flush
188
+ id="model-access"
189
+ class="access-panel"
190
+ title="Model access"
191
+ subtitle="Which plans each model is documented for. Informational only."
192
+ actions={
193
+ <label class="access-account">
194
+ <span class="sr-only">Account</span>
195
+ <select class="select" value={accountId} onChange={e => { setAccount(e.currentTarget.value); setPlan(""); setEvidence(null); }}>
196
+ <option value="">No account</option>
197
+ {report?.accounts.map(a => <option key={a.id} value={a.id}>{masker.value.email(a.label)}</option>)}
198
+ </select>
199
+ </label>
200
+ }
201
+ >
202
+ <div class="access-context">
203
+ <Segmented
204
+ label="Provider"
205
+ size="sm"
206
+ value={provider}
207
+ onChange={p => { setProvider(p); setPlan(""); setMorePlans(false); setEvidence(null); }}
208
+ options={PROVIDERS.map(p => {
209
+ const missing = Boolean(selected) && !selected!.providers.includes(p);
210
+ return { value: p, label: providerLabel(p), disabled: missing, title: missing ? "Not connected on this account" : undefined };
211
+ })}
212
+ />
213
+ {planMatters && (
214
+ <div class="access-context-group">
215
+ <Segmented
216
+ label="Plan"
217
+ size="sm"
218
+ value={plan}
219
+ onChange={setPlan}
220
+ options={[
221
+ { value: "", label: selected ? <>Account <span class="access-known">{knownPlan}</span></> : "Any", title: planHint },
222
+ ...planChoices.map(p => ({ value: p, label: p, title: selected ? "Assume this plan for the check" : undefined })),
223
+ ]}
224
+ />
225
+ {foldable && (
226
+ <button type="button" class="link-button access-quiet-link" aria-expanded={morePlans} onClick={() => setMorePlans(!morePlans)}>
227
+ {morePlans ? "Fewer" : `+${offeredPlans.length - relevantPlans.length}`}
228
+ </button>
229
+ )}
230
+ </div>
231
+ )}
232
+ {clientMatters && (
233
+ <Segmented label="Client" size="sm" value={client} onChange={setClient} options={CLIENTS.map(c => ({ value: c, label: CLIENT_LABEL[c], title: "Declared client, not verified" }))} />
234
+ )}
235
+ </div>
236
+
237
+ <div class="access-check">
238
+ <div class="access-check-head">
239
+ <label class="field-label" for="access-model">Check a model</label>
240
+ {pickDate || at ? (
241
+ <span class="access-date">
242
+ <input class="input input-sm" type="date" aria-label="Policy date" value={at} onInput={e => setAt(e.currentTarget.value)} />
243
+ <button type="button" class="access-icon-button" aria-label="Use today" onClick={() => { setAt(""); setPickDate(false); }}>
244
+ <Icon name="x" size={14} />
245
+ </button>
246
+ </span>
247
+ ) : (
248
+ <button type="button" class="link-button access-quiet-link" onClick={() => setPickDate(true)}>As of today</button>
249
+ )}
250
+ </div>
251
+ <div class={`access-probe${pending ? " is-pending" : ""}`}>
252
+ <input
253
+ id="access-model"
254
+ class="input input-lg mono-input"
255
+ value={model}
256
+ onInput={e => setModel(e.currentTarget.value)}
257
+ maxLength={256}
258
+ spellcheck={false}
259
+ autocomplete="off"
260
+ placeholder="Model ID"
261
+ list="access-model-suggestions"
262
+ />
263
+ <datalist id="access-model-suggestions">
264
+ {suggestions.map(id => <option key={id} value={id} />)}
265
+ </datalist>
266
+ {result?.decision && !checkError && <span class="access-verdict"><StateMark state={result.decision.state} /></span>}
267
+ </div>
268
+ <div class="access-explain" role="status" aria-busy={pending}>
269
+ {checkError || loadError ? (
270
+ <p class="form-error">{checkError || loadError}</p>
271
+ ) : result?.decision ? (
272
+ <>
273
+ <p class="access-reason">{result.decision.reason}</p>
274
+ <p class="access-meta">{meta}</p>
275
+ </>
276
+ ) : null}
277
+ {accountId && plan && (
278
+ <p class="access-meta">
279
+ <button type="button" class="link-button" disabled={saving} onClick={() => { void savePlan(); }} title="Stores an unverified operator declaration for 30 days">
280
+ {saving ? "Saving…" : `Save ${plan} as this account's ${providerLabel(provider)} plan`}
281
+ </button>
282
+ {saveError && <span class="form-error"> {saveError}</span>}
283
+ </p>
284
+ )}
285
+ </div>
286
+
287
+ {selected && (
288
+ <div class="access-evidence">
289
+ <p class="access-meta">
290
+ {observations.length > 0 ? (
291
+ <button type="button" class="link-button access-quiet-link" aria-expanded={evidence === "observations"} onClick={() => setEvidence(evidence === "observations" ? null : "observations")}>
292
+ {pluralize(observations.length, "recent observation")}
293
+ </button>
294
+ ) : (
295
+ <span>No recent observations</span>
296
+ )}
297
+ <span aria-hidden="true"> · </span>
298
+ {catalog && catalog.observedAt != null ? (
299
+ <button type="button" class="link-button access-quiet-link" aria-expanded={evidence === "catalog"} onClick={() => setEvidence(evidence === "catalog" ? null : "catalog")}>
300
+ {pluralize(catalog.models.length, "advertised model")}{catalogFreshness === "fresh" ? "" : `, ${catalogFreshness}`}
301
+ </button>
302
+ ) : (
303
+ <span>Advertised models unknown</span>
304
+ )}
305
+ </p>
306
+ {evidence === "observations" && (
307
+ <div class="access-well">
308
+ <table class="table table-compact">
309
+ <thead>
310
+ <tr>
311
+ <th scope="col">Model</th>
312
+ <th scope="col">Result</th>
313
+ <th scope="col" class="num-col">HTTP</th>
314
+ <th scope="col" class="hide-sm">Observed</th>
315
+ </tr>
316
+ </thead>
317
+ <tbody>
318
+ {observations.map(o => (
319
+ <tr key={`${o.provider}/${o.model}/${o.client}`}>
320
+ <th scope="row">
321
+ <span class="model-id">{o.model}</span>
322
+ <div class="cell-sub">{o.client} client</div>
323
+ </th>
324
+ <td>{o.kind === "model-unavailable" ? "Rejected for this account" : o.kind}</td>
325
+ <td class="num num-col">{o.status ?? <span class="muted">—</span>}</td>
326
+ <td class="num hide-sm" title={`Expires ${new Date(o.expiresAt).toISOString()}`}>{formatDateTime(o.observedAt)}</td>
327
+ </tr>
328
+ ))}
329
+ </tbody>
330
+ </table>
331
+ </div>
332
+ )}
333
+ {evidence === "catalog" && catalog && (
334
+ <div class="access-well">
335
+ <p class="access-meta">
336
+ {catalog.source} · observed {catalog.observedAt === null ? "unknown" : formatDateTime(catalog.observedAt)} · valid until {catalog.expiresAt === null ? "unknown" : formatDateTime(catalog.expiresAt)}
337
+ </p>
338
+ <div class="tag-row">
339
+ {catalog.models.map(id => (
340
+ <button key={id} type="button" class="tag access-model-tag" title="Check this model" onClick={() => setModel(id)}>{id}</button>
341
+ ))}
342
+ </div>
343
+ </div>
344
+ )}
345
+ </div>
346
+ )}
347
+ </div>
348
+
349
+ <div class="toolbar panel-toolbar access-rules-toolbar">
350
+ <h3 class="access-rules-title">
351
+ Rules <span class="num muted">{rules.length}</span>
352
+ </h3>
353
+ <SearchInput value={ruleFilter} onInput={setRuleFilter} placeholder="Filter" label="Filter rules by model" />
354
+ </div>
355
+
356
+ {!report ? (
357
+ loadError ? null : <div class="panel-loading"><Spinner /></div>
358
+ ) : rules.length === 0 ? (
359
+ <EmptyState icon="search" title={providerRules.length === 0 ? "No rules for this provider and plan" : "No rules match"}>
360
+ {providerRules.length === 0 ? "Without a rule, checks report access as unknown." : undefined}
361
+ </EmptyState>
362
+ ) : (
363
+ <div class="table-scroll">
364
+ <table class="table access-table">
365
+ <thead>
366
+ <tr>
367
+ <th scope="col">Model</th>
368
+ <th scope="col">Access</th>
369
+ <th scope="col" class="hide-sm">Plans</th>
370
+ <th scope="col">Note</th>
371
+ </tr>
372
+ </thead>
373
+ <tbody>
374
+ {rules.map(r => {
375
+ const url = r.source.startsWith("https://");
376
+ return (
377
+ <tr key={r.id}>
378
+ <th scope="row">
379
+ <span class="model-id">{r.modelPrefix}</span>
380
+ {(r.exact || r.client) && (
381
+ <div class="cell-sub">
382
+ {r.exact ? "Exact ID" : `${r.client === "opencode" ? "OpenCode" : r.client} client`}
383
+ </div>
384
+ )}
385
+ </th>
386
+ <td>
387
+ <StateMark state={r.state} title={`${EVIDENCE[r.evidence]} · verified ${r.verifiedAt} · review ${r.reviewAfter}`} />
388
+ {r.validUntil && <div class="cell-sub num">Until {r.validUntil}</div>}
389
+ {r.evidence !== "documented" && <div class="cell-sub">{EVIDENCE[r.evidence]}</div>}
390
+ </td>
391
+ <td class="hide-sm access-plans" title={r.plans.join(", ")}>{planList(r.plans)}</td>
392
+ <td class="access-note">
393
+ {r.note}
394
+ {url ? (
395
+ <a href={r.source} target="_blank" rel="noreferrer" class="access-source" title={r.source} aria-label={`Source: ${sourceHost(r.source)}`}>
396
+ <Icon name="arrowUpRight" size={13} />
397
+ </a>
398
+ ) : (
399
+ <div class="cell-sub">{r.source}</div>
400
+ )}
401
+ </td>
402
+ </tr>
403
+ );
404
+ })}
405
+ </tbody>
406
+ </table>
407
+ </div>
408
+ )}
409
+ </Panel>
410
+ );
88
411
  }
@@ -4572,6 +4572,274 @@ a.hero-metric:hover {
4572
4572
  }
4573
4573
  }
4574
4574
 
4575
+ /* ── Model access (Models page) ───────────────────────────────────────── */
4576
+
4577
+ .access-account .select {
4578
+ height: 30px;
4579
+ max-width: 220px;
4580
+ font-size: 13px;
4581
+ }
4582
+
4583
+ /* Provider, plan and client: one quiet row the check and the rules share. */
4584
+ .access-context {
4585
+ display: flex;
4586
+ align-items: center;
4587
+ gap: 12px 16px;
4588
+ flex-wrap: wrap;
4589
+ padding: 4px 20px 20px;
4590
+ }
4591
+
4592
+ .access-context > .segmented,
4593
+ .access-context-group > .segmented {
4594
+ max-width: 100%;
4595
+ overflow-x: auto;
4596
+ }
4597
+
4598
+ .access-context-group {
4599
+ display: flex;
4600
+ align-items: center;
4601
+ gap: 8px;
4602
+ min-width: 0;
4603
+ }
4604
+
4605
+ .access-known {
4606
+ margin-left: 4px;
4607
+ color: var(--text-3);
4608
+ font-weight: 500;
4609
+ }
4610
+
4611
+ .segmented button:disabled {
4612
+ color: var(--text-4);
4613
+ cursor: not-allowed;
4614
+ }
4615
+
4616
+ .link-button.access-quiet-link {
4617
+ color: var(--text-3);
4618
+ font-weight: 500;
4619
+ font-size: 12.5px;
4620
+ }
4621
+
4622
+ .link-button.access-quiet-link:hover {
4623
+ color: var(--text);
4624
+ }
4625
+
4626
+ .access-check {
4627
+ display: flex;
4628
+ flex-direction: column;
4629
+ gap: 8px;
4630
+ padding: 20px;
4631
+ border-top: 1px solid var(--border);
4632
+ }
4633
+
4634
+ .access-check-head {
4635
+ display: flex;
4636
+ align-items: center;
4637
+ justify-content: space-between;
4638
+ gap: 12px;
4639
+ min-height: 30px;
4640
+ }
4641
+
4642
+ .access-date {
4643
+ display: inline-flex;
4644
+ align-items: center;
4645
+ gap: 4px;
4646
+ }
4647
+
4648
+ .access-date .input {
4649
+ width: 152px;
4650
+ }
4651
+
4652
+ .access-icon-button {
4653
+ display: inline-flex;
4654
+ align-items: center;
4655
+ justify-content: center;
4656
+ width: 28px;
4657
+ height: 28px;
4658
+ border: 0;
4659
+ border-radius: var(--radius-xs);
4660
+ background: none;
4661
+ color: var(--text-3);
4662
+ cursor: pointer;
4663
+ transition: background-color 0.15s, color 0.15s;
4664
+ }
4665
+
4666
+ .access-icon-button:hover {
4667
+ background: var(--surface-2);
4668
+ color: var(--text);
4669
+ }
4670
+
4671
+ /* The verdict sits inside the field, so the question and answer read as one. */
4672
+ .access-probe {
4673
+ position: relative;
4674
+ }
4675
+
4676
+ .access-probe .input {
4677
+ width: 100%;
4678
+ padding-right: 136px;
4679
+ }
4680
+
4681
+ .mono-input {
4682
+ font-family: var(--mono);
4683
+ font-size: 14px;
4684
+ }
4685
+
4686
+ /* Suggestions appear while typing; the native arrow would read as a select. */
4687
+ .mono-input::-webkit-calendar-picker-indicator {
4688
+ display: none !important;
4689
+ }
4690
+
4691
+ .access-verdict {
4692
+ position: absolute;
4693
+ top: 50%;
4694
+ right: 16px;
4695
+ transform: translateY(-50%);
4696
+ pointer-events: none;
4697
+ transition: opacity 0.15s;
4698
+ }
4699
+
4700
+ .access-explain {
4701
+ display: flex;
4702
+ flex-direction: column;
4703
+ gap: 4px;
4704
+ min-height: 44px;
4705
+ padding-top: 4px;
4706
+ transition: opacity 0.15s;
4707
+ }
4708
+
4709
+ .access-probe.is-pending .access-verdict,
4710
+ .access-probe.is-pending + .access-explain {
4711
+ opacity: 0.5;
4712
+ }
4713
+
4714
+ .access-reason {
4715
+ color: var(--text-2);
4716
+ }
4717
+
4718
+ .access-meta {
4719
+ font-size: 12.5px;
4720
+ color: var(--text-3);
4721
+ }
4722
+
4723
+ .access-state {
4724
+ display: inline-flex;
4725
+ align-items: center;
4726
+ gap: 8px;
4727
+ font-size: 13px;
4728
+ font-weight: 560;
4729
+ color: var(--tone);
4730
+ white-space: nowrap;
4731
+ }
4732
+
4733
+ .access-state.tone-neutral {
4734
+ color: var(--text-2);
4735
+ }
4736
+
4737
+ .access-dot {
4738
+ width: 6px;
4739
+ height: 6px;
4740
+ border-radius: 50%;
4741
+ background: var(--tone);
4742
+ box-shadow: 0 0 0 3px var(--tone-soft);
4743
+ }
4744
+
4745
+ .access-evidence {
4746
+ display: flex;
4747
+ flex-direction: column;
4748
+ gap: 12px;
4749
+ padding-top: 12px;
4750
+ border-top: 1px solid var(--border);
4751
+ }
4752
+
4753
+ .access-well {
4754
+ display: flex;
4755
+ flex-direction: column;
4756
+ gap: 12px;
4757
+ padding: 12px 16px;
4758
+ border-radius: var(--radius);
4759
+ background: var(--surface-2);
4760
+ }
4761
+
4762
+ .access-well .table th,
4763
+ .access-well .table td {
4764
+ border-color: var(--border);
4765
+ }
4766
+
4767
+ .access-model-tag {
4768
+ font-family: var(--mono);
4769
+ cursor: pointer;
4770
+ transition: color 0.15s, border-color 0.15s;
4771
+ }
4772
+
4773
+ .access-model-tag:hover {
4774
+ color: var(--text);
4775
+ border-color: var(--border-strong);
4776
+ }
4777
+
4778
+ .access-rules-toolbar {
4779
+ padding-top: 16px;
4780
+ border-top: 1px solid var(--border);
4781
+ }
4782
+
4783
+ .access-rules-title {
4784
+ display: flex;
4785
+ align-items: baseline;
4786
+ gap: 8px;
4787
+ font-size: 14px;
4788
+ font-weight: 600;
4789
+ color: var(--text);
4790
+ }
4791
+
4792
+ .access-rules-title .num {
4793
+ font-weight: 500;
4794
+ }
4795
+
4796
+ .access-rules-toolbar .search {
4797
+ min-width: 200px;
4798
+ }
4799
+
4800
+ .access-table .model-id {
4801
+ white-space: nowrap;
4802
+ word-break: normal;
4803
+ }
4804
+
4805
+ .access-table tbody th .cell-sub {
4806
+ white-space: nowrap;
4807
+ }
4808
+
4809
+ .access-plans {
4810
+ color: var(--text-3);
4811
+ white-space: nowrap;
4812
+ }
4813
+
4814
+ .access-note {
4815
+ min-width: 240px;
4816
+ color: var(--text-2);
4817
+ }
4818
+
4819
+ .access-source {
4820
+ display: inline-flex;
4821
+ align-items: center;
4822
+ margin-left: 4px;
4823
+ vertical-align: -2px;
4824
+ color: var(--text-3);
4825
+ transition: color 0.15s;
4826
+ }
4827
+
4828
+ .access-source:hover {
4829
+ color: var(--text);
4830
+ }
4831
+
4832
+ @container canvas (max-width: 700px) {
4833
+ .access-probe .input {
4834
+ padding-right: 124px;
4835
+ }
4836
+
4837
+ .access-rules-toolbar .search {
4838
+ min-width: 0;
4839
+ flex: 1;
4840
+ }
4841
+ }
4842
+
4575
4843
  /* ── Keys ─────────────────────────────────────────────────────────────── */
4576
4844
 
4577
4845
  .model-groups {