tuxevil-rotator 4.3.0 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +4 -2
- package/package.json +2 -1
- package/src/access-evidence.ts +153 -0
- package/src/access-probe.ts +85 -0
- package/src/admin-auth.ts +4 -1
- package/src/auto-access-shadow.ts +11 -0
- package/src/auto-model-access.ts +185 -0
- package/src/auto-output-health.ts +12 -0
- package/src/auto-routing-evaluation.ts +80 -0
- package/src/auto-routing-quality.ts +308 -0
- package/src/auto-routing.ts +403 -26
- package/src/compat.ts +223 -36
- package/src/compression/index.ts +6 -6
- package/src/compression/lite.ts +3 -9
- package/src/compression/rtk/index.ts +0 -3
- package/src/config-defaults.ts +7 -0
- package/src/dashboard.ts +5 -0
- package/src/db-store.ts +10 -0
- package/src/index.ts +2 -0
- package/src/model-access-api.ts +74 -0
- package/src/model-access.ts +56 -0
- package/src/ollama-output-gate.ts +18 -0
- package/src/onboarding.ts +1 -1
- package/src/provider-catalog-evidence.ts +26 -0
- package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
- package/src/providers/google-antigravity/quota.ts +3 -0
- package/src/providers/ollama/context-window.ts +13 -0
- package/src/providers/ollama/quota.ts +4 -0
- package/src/providers/ollama/translators.ts +19 -2
- package/src/providers/openai-codex/compat.ts +5 -1
- package/src/providers/openai-codex/credentials.ts +22 -6
- package/src/providers/openai-codex/index.ts +9 -1
- package/src/providers/openai-codex/quota.ts +19 -6
- package/src/providers/opencode-zen/forward.ts +1 -1
- package/src/providers/opencode-zen/quota.ts +2 -0
- package/src/proxy.ts +78 -3
- package/src/quota-observation.ts +26 -0
- package/src/quota-pools.ts +322 -0
- package/src/rotator.ts +151 -38
- package/src/settings-repository.ts +1 -0
- package/src/types.ts +28 -0
- package/src/usage-limits-auth.ts +24 -0
- package/src/usage-limits.ts +148 -0
- package/src/validators.ts +26 -0
- package/src/web/components/icons.tsx +15 -0
- package/src/web/components/overlays.tsx +4 -0
- package/src/web/components/ui.tsx +9 -9
- package/src/web/lib/playground.ts +35 -0
- package/src/web/lib/pool-navigation.ts +4 -0
- package/src/web/lib/pools.ts +2 -243
- package/src/web/pages/AccountDetail.tsx +2 -1
- package/src/web/pages/ModelAccess.tsx +88 -0
- package/src/web/pages/Models.tsx +2 -0
- package/src/web/pages/Overview.tsx +26 -9
- package/src/web/pages/Playground.tsx +1132 -551
- package/src/web/pages/Transcription.tsx +304 -170
- package/src/web/state/api.ts +3 -0
- package/src/web/styles/app.css +501 -45
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [4.4.0] - 2026-11-01
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **Auto-routing assessment and evaluation**: Record Artificial Analysis index assessments beside routing decisions, including comparable score versions, candidate ranks and fallback pools. Add effort-pool shadow evaluation, routing quality fixtures, and local evaluation tools for exact-match and isolated coding tasks.
|
|
8
|
+
- **Provider model-access evidence**: Track account-scoped model catalogs and entitlement evidence, run bounded access probes, enforce configured provider/account/model eligibility in `auto`, and expose access diagnostics in the dashboard.
|
|
9
|
+
- **Aggregated usage limits**: Add a read-only API and dashboard views for provider/model quota pools while preserving unknown values, partial coverage and source provenance.
|
|
10
|
+
- **Bounded auto recovery and continuity**: Recover eligible OpenAI Chat Completions requests after empty Ollama output or structured upstream availability failures before client output is committed. Add opt-in session continuity and bounded escalation after repeated structured tool failures.
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **Quota-aware deterministic fallback**: Prefer eligible Gemini 3.8 Flash variants matched to task effort, then GPT-6 Luna, followed by operational-score order. Exclude Claude Opus 4.6 from deterministic fallback while retaining confident classifier selection. Keep fallback choices independent of the classifier shortlist.
|
|
15
|
+
- **Provider eligibility and discovery**: Apply account-level access evidence before auto selection, preserve OpenCode-restricted free models for eligible OpenCode-originated requests, and expose `auto` in model discovery.
|
|
16
|
+
- **Provider reliability and metadata**: Preserve access evidence across verified Codex OAuth refreshes, honor discovered Ollama context limits, and reject empty or malformed Ollama completions before they reach clients.
|
|
17
|
+
- **Prompt compression**: Deduplicate repeated routing instructions and filter them before lossy compression.
|
|
18
|
+
- **Dashboard Playground design alignment**: Use shared layout and controls across the Playground tabs, improve compliance details and runnable-model selection, and streamline transcription actions ([PR #46](https://github.com/tuxevil/tuxevil-rotator/pull/46) by [@CyR1en](https://github.com/CyR1en)).
|
|
19
|
+
|
|
20
|
+
### Contributors
|
|
21
|
+
|
|
22
|
+
- Thanks to [@CyR1en](https://github.com/CyR1en) for aligning the Dashboard Playground (Chat, Compare, Compliance, and Transcription) with the shared design system, expandable compliance results table, request/response/routing inspector, audio-only model guards, and accessibility improvements in [PR #46](https://github.com/tuxevil/tuxevil-rotator/pull/46).
|
|
23
|
+
|
|
3
24
|
## [4.3.0] - 2026-10-29
|
|
4
25
|
|
|
5
26
|
### Added
|
package/README.md
CHANGED
|
@@ -55,7 +55,9 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
55
55
|
|
|
56
56
|
## Current Model Update
|
|
57
57
|
|
|
58
|
-
- **v4.
|
|
58
|
+
- **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))
|
|
59
|
+
|
|
60
|
+
- **v4.3.0: Dashboard Playground, Codex reasoning connectors, and persistent Antigravity catalogs**: Test enabled models from `/dashboard/playground` across Chat, 2–3 model Compare, 5-case Chat Completions Compliance, and Audio Transcription (file upload including `.oga`/`.ogg` plus browser microphone recording) with IndexedDB workspaces, JSON export/import, shared design-system components, expandable compliance result tables, and request/response/routing inspection. `GET /v1/models` now publishes Codex reasoning effort metadata (`low`, `medium`, `high`, `xhigh`, `max`) and propagates it through `install-opencode`, the OpenCode 2 discovery plugin, and `install-agent` (including the new `openclaw` target). Also strips data URL prefixes on Ollama vision image payloads and restores validated Antigravity model snapshots per account before the first quota poll with updated client headers and pricing estimates. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.3.0); [PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42) by [@javargasm](https://github.com/javargasm), [PR #43](https://github.com/tuxevil/tuxevil-rotator/pull/43), [PR #46](https://github.com/tuxevil/tuxevil-rotator/pull/46) by [@CyR1en](https://github.com/CyR1en))
|
|
59
61
|
|
|
60
62
|
- **v4.2.2: Security updates and dynamic model discovery**: Requires patched Node.js releases (22.23.4+, 24.22.1+, or 26.12.1+ on their supported release lines), updates Undici to 7.30.1, and prevents long URL slash sequences from blocking the OpenCode discovery plugin. Antigravity models now follow live account catalogs, and installers use the OpenCode 2 plugin API. Upgrade Node.js and restart existing rotator services after updating the package. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.2.2); [PR #41](https://github.com/tuxevil/tuxevil-rotator/pull/41) by [@CyR1en](https://github.com/CyR1en))
|
|
61
63
|
|
|
@@ -393,7 +395,7 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
393
395
|
|
|
394
396
|
- **[@CelestialCreator](https://github.com/CelestialCreator)** (Akshay) — Fixed admin token propagation on the hosted login landing page (`/login` to `/auth/antigravity/start`). ([PR #25](https://github.com/tuxevil/tuxevil-rotator/pull/25))
|
|
395
397
|
- **[@Codder-hermes](https://github.com/Codder-hermes)** — Fixed Claude Code tool-schema requests by stripping the unsupported JSON Schema `propertyNames` keyword for Gemini and Claude-via-Gemini routes, with regression coverage for both compatibility paths. ([PR #19](https://github.com/tuxevil/tuxevil-rotator/pull/19))
|
|
396
|
-
- **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6, Gemini 3.7, and Gemini 3.8 Flash model families, shared quota-pool routing, pricing, dashboard support, integration documentation, effort-based model routing, the rebuilt WebUI, the Models page with provider/model controls and dispatch-time switch enforcement, the effort routing editor, Claude-style effort selection, live configuration updates, unsaved-edit navigation protection, regression coverage, and Node.js/Undici security updates with deployment guidance. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21), [PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28), [PR #32](https://github.com/tuxevil/tuxevil-rotator/pull/32), [PR #38](https://github.com/tuxevil/tuxevil-rotator/pull/38), [PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39), [PR #40](https://github.com/tuxevil/tuxevil-rotator/pull/40), [PR #41](https://github.com/tuxevil/tuxevil-rotator/pull/41))
|
|
398
|
+
- **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6, Gemini 3.7, and Gemini 3.8 Flash model families, shared quota-pool routing, pricing, dashboard support, integration documentation, effort-based model routing, the rebuilt WebUI, the Models page with provider/model controls and dispatch-time switch enforcement, the effort routing editor, Claude-style effort selection, live configuration updates, unsaved-edit navigation protection, Dashboard Playground design-system alignment (shared components, expandable compliance results table, request/response/routing inspector, audio-only model guards, and accessibility improvements), regression coverage, and Node.js/Undici security updates with deployment guidance. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21), [PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28), [PR #32](https://github.com/tuxevil/tuxevil-rotator/pull/32), [PR #38](https://github.com/tuxevil/tuxevil-rotator/pull/38), [PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39), [PR #40](https://github.com/tuxevil/tuxevil-rotator/pull/40), [PR #41](https://github.com/tuxevil/tuxevil-rotator/pull/41), [PR #46](https://github.com/tuxevil/tuxevil-rotator/pull/46))
|
|
397
399
|
- **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
|
|
398
400
|
- **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
|
|
399
401
|
- **[@toRolex](https://github.com/toRolex)** (Rolex) — Added cached prompt-token extraction from Google Antigravity/Cloud Code usage and mapped it to OpenAI and Anthropic compatibility responses, with focused regression tests, plus transport-error retry recovery for single-account and exhausted-account pools. ([PR #34](https://github.com/tuxevil/tuxevil-rotator/pull/34), [PR #35](https://github.com/tuxevil/tuxevil-rotator/pull/35))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuxevil-rotator",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.0",
|
|
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",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"typecheck:test": "tsc --project tsconfig.test.json",
|
|
19
19
|
"test": "TUXEVIL_ROTATOR_ADMIN_TOKEN= PI_ROTATOR_ADMIN_TOKEN= ANTIGRAVITY_CLIENT_ID=test-client-id ANTIGRAVITY_CLIENT_SECRET=test-client-secret TUXEVIL_ROTATOR_DIR=/tmp/tuxevil-rotator-test node --import tsx/esm --test \"test/**/*.test.ts\"",
|
|
20
20
|
"lint": "eslint src test scripts/dashboard-dev.ts",
|
|
21
|
+
"evaluate:auto-quality": "tsx scripts/evaluate-aa-routing-selections.ts",
|
|
21
22
|
"coverage": "c8 --reporter=text --reporter=html --check-coverage --lines=60 --branches=50 --functions=60 --statements=60 npm test",
|
|
22
23
|
"check": "npm run typecheck && npm run typecheck:test && npm test && npm run lint",
|
|
23
24
|
"dashboard:dev": "tsx scripts/dashboard-dev.ts"
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { evaluateModelAccess } from "./model-access.js";
|
|
3
|
+
import type { AccountConfig } from "./types.js";
|
|
4
|
+
import { getAccountIdentity, getCredentialGenerationFingerprint } from "./account-identity.js";
|
|
5
|
+
import { getCachedAccessEvidence, isSettingsRepositoryInitialized, setCachedAccessEvidence } from "./db-store.js";
|
|
6
|
+
export type ObservationKind = "success" | "authentication" | "quota" | "payment-or-plan" | "client-restriction" | "entitlement" | "model-unavailable" | "transport" | "unknown";
|
|
7
|
+
export interface ProviderPlanEvidence { accountId: string; provider: string; credential: string; plan: string; source: "operator"; observedAt: number; expiresAt: number }
|
|
8
|
+
export interface AccessObservation { accountId: string; provider: string; credential: string; model: string; client: string; kind: ObservationKind; status: number | null; observedAt: number; expiresAt: number }
|
|
9
|
+
export interface AccessEvidenceSnapshot { version: 1; plans: ProviderPlanEvidence[]; observations: AccessObservation[] }
|
|
10
|
+
export const ACCESS_PLANS = ["unknown", "free", "plus", "pro-trial", "pro-paid", "ultra", "enterprise", "team"];
|
|
11
|
+
export function classifyAccessObservation(status: number | null, detail = "", transport = false, provider?: string, model?: string): ObservationKind {
|
|
12
|
+
if (transport) return "transport";
|
|
13
|
+
if (status !== null && status >= 200 && status < 300) return "success";
|
|
14
|
+
if (status === 401) return "authentication";
|
|
15
|
+
if (status === 429) return "quota";
|
|
16
|
+
if (status === 402) return "payment-or-plan";
|
|
17
|
+
// Require an explicit structured code; never infer plan access from generic prose/400.
|
|
18
|
+
let code: unknown;
|
|
19
|
+
let message: unknown;
|
|
20
|
+
try { const body = JSON.parse(detail); code = body?.error?.code ?? body?.error?.type ?? body?.type; message = body?.detail ?? body?.error?.message; } catch { /* unknown */ }
|
|
21
|
+
if (status === 403 && code === "FreeTierError") return "client-restriction";
|
|
22
|
+
if ([400, 403].includes(status ?? 0) && ["MODEL_NOT_SUPPORTED_FOR_PLAN", "model_not_available_for_plan", "insufficient_entitlement"].includes(String(code))) return "entitlement";
|
|
23
|
+
if (status === 400 && provider === "openai-codex" && typeof message === "string") {
|
|
24
|
+
const rejected = /^The ['"]([a-z0-9][a-z0-9._-]{0,255})['"] model is not supported when using Codex with a ChatGPT account\.$/.exec(message);
|
|
25
|
+
if (rejected && rejected[1] === model) return "model-unavailable";
|
|
26
|
+
}
|
|
27
|
+
return "unknown";
|
|
28
|
+
}
|
|
29
|
+
const scope = (a: { accountId: string; provider: string; credential: string }) => JSON.stringify([a.accountId, a.provider, a.credential]);
|
|
30
|
+
export class AccessEvidenceStore {
|
|
31
|
+
private plans: ProviderPlanEvidence[] = [];
|
|
32
|
+
private observations: AccessObservation[] = [];
|
|
33
|
+
private lastPrunedAt = 0;
|
|
34
|
+
constructor(input?: unknown) {
|
|
35
|
+
const value = input as Partial<AccessEvidenceSnapshot> | null;
|
|
36
|
+
if (value?.version !== 1) return;
|
|
37
|
+
// Whitelist fields on load; never round-trip arbitrary stored objects.
|
|
38
|
+
if (Array.isArray(value.plans)) for (const p of value.plans.slice(-2000)) {
|
|
39
|
+
if (p && [p.accountId, p.provider, p.credential, p.plan].every(x => typeof x === "string") && ACCESS_PLANS.includes(p.plan) && Number.isFinite(p.observedAt) && Number.isFinite(p.expiresAt)) this.plans.push({ accountId: p.accountId, provider: p.provider, credential: p.credential, plan: p.plan, source: "operator", observedAt: p.observedAt, expiresAt: p.expiresAt });
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(value.observations)) for (const o of value.observations.slice(-2000)) {
|
|
42
|
+
if (o && [o.accountId, o.provider, o.credential, o.model, o.client].every(x => typeof x === "string") && ["success", "authentication", "quota", "payment-or-plan", "client-restriction", "entitlement", "model-unavailable", "transport", "unknown"].includes(o.kind) && (o.status === null || Number.isInteger(o.status)) && Number.isFinite(o.observedAt) && Number.isFinite(o.expiresAt)) this.observations.push({ accountId: o.accountId, provider: o.provider, credential: o.credential, model: o.model, client: o.client, kind: o.kind, status: o.status, observedAt: o.observedAt, expiresAt: o.expiresAt });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
private pruneExpired(now: number): void {
|
|
46
|
+
if (now >= this.lastPrunedAt && now - this.lastPrunedAt < 1000) return;
|
|
47
|
+
this.plans = this.plans.filter(p => p.expiresAt > now);
|
|
48
|
+
this.observations = this.observations.filter(o => o.expiresAt > now);
|
|
49
|
+
this.lastPrunedAt = now;
|
|
50
|
+
}
|
|
51
|
+
snapshot(now = Date.now()): AccessEvidenceSnapshot {
|
|
52
|
+
this.pruneExpired(now);
|
|
53
|
+
return { version: 1, plans: this.plans.map(p => ({ ...p })), observations: this.observations.map(o => ({ ...o })) };
|
|
54
|
+
}
|
|
55
|
+
declarePlan(account: AccountConfig, provider: string, plan: string, now = Date.now()): void {
|
|
56
|
+
if (!ACCESS_PLANS.includes(plan)) throw new Error("Unknown plan");
|
|
57
|
+
const entry: ProviderPlanEvidence = { accountId: getAccountIdentity(account), provider, credential: getCredentialGenerationFingerprint(account, provider), plan, source: "operator", observedAt: now, expiresAt: now + 30 * 86400000 };
|
|
58
|
+
this.snapshot(now);
|
|
59
|
+
this.plans = this.plans.filter(p => scope(p) !== scope(entry));
|
|
60
|
+
this.plans.push(entry); this.plans = this.plans.slice(-2000);
|
|
61
|
+
}
|
|
62
|
+
observe(account: AccountConfig, provider: string, model: string, client: string, status: number | null, detail = "", transport = false, now = Date.now()): void {
|
|
63
|
+
if (model.length > 256) return;
|
|
64
|
+
const kind = classifyAccessObservation(status, detail, transport, provider, model);
|
|
65
|
+
const ttl = kind === "success" ? 86400000 : ["authentication", "quota", "transport"].includes(kind) ? 300000 : 3600000;
|
|
66
|
+
const entry: AccessObservation = { accountId: getAccountIdentity(account), provider, credential: getCredentialGenerationFingerprint(account, provider), model: model.slice(0, 256), client, status, kind, observedAt: now, expiresAt: now + ttl };
|
|
67
|
+
this.snapshot(now);
|
|
68
|
+
this.observations = this.observations.filter(o => !(scope(o) === scope(entry) && o.model === entry.model && o.client === client));
|
|
69
|
+
this.observations.push(entry); this.observations = this.observations.slice(-2000);
|
|
70
|
+
}
|
|
71
|
+
/** Only the OAuth refresh path may attest this same-principal transition. */
|
|
72
|
+
continueCodexRefresh(before: AccountConfig, after: AccountConfig, verifiedAccountId: string, now = Date.now()): boolean {
|
|
73
|
+
const provider = "openai-codex";
|
|
74
|
+
const oldId = before.credentials?.find(c => c.provider === provider)?.providerAccountId;
|
|
75
|
+
const newId = after.credentials?.find(c => c.provider === provider)?.providerAccountId;
|
|
76
|
+
if (!verifiedAccountId || oldId !== verifiedAccountId || newId !== verifiedAccountId || getAccountIdentity(before) !== getAccountIdentity(after)) return false;
|
|
77
|
+
const oldScope = scope({ accountId: getAccountIdentity(before), provider, credential: getCredentialGenerationFingerprint(before, provider) });
|
|
78
|
+
const credential = getCredentialGenerationFingerprint(after, provider);
|
|
79
|
+
const newScope = scope({ accountId: getAccountIdentity(after), provider, credential });
|
|
80
|
+
if (oldScope === newScope) return false;
|
|
81
|
+
this.snapshot(now);
|
|
82
|
+
let changed = false;
|
|
83
|
+
for (const entry of this.plans.filter(p => scope(p) === oldScope)) {
|
|
84
|
+
const existing = this.plans.find(p => scope(p) === newScope);
|
|
85
|
+
this.plans = this.plans.filter(p => p !== entry && p !== existing);
|
|
86
|
+
this.plans.push(existing && existing.observedAt >= entry.observedAt ? existing : { ...entry, credential });
|
|
87
|
+
changed = true;
|
|
88
|
+
}
|
|
89
|
+
for (const entry of this.observations.filter(o => scope(o) === oldScope)) {
|
|
90
|
+
const existing = this.observations.find(o => scope(o) === newScope && o.model === entry.model && o.client === entry.client);
|
|
91
|
+
this.observations = this.observations.filter(o => o !== entry && o !== existing);
|
|
92
|
+
this.observations.push(existing && existing.observedAt >= entry.observedAt ? existing : { ...entry, credential });
|
|
93
|
+
changed = true;
|
|
94
|
+
}
|
|
95
|
+
return changed;
|
|
96
|
+
}
|
|
97
|
+
forAccount(account: AccountConfig, now = Date.now()) {
|
|
98
|
+
this.pruneExpired(now);
|
|
99
|
+
const valid = (entry: { accountId: string; provider: string; credential: string; expiresAt: number }) => entry.expiresAt > now && entry.accountId === getAccountIdentity(account) && entry.credential === getCredentialGenerationFingerprint(account, entry.provider);
|
|
100
|
+
return { plans: this.plans.filter(valid), observations: this.observations.filter(valid) };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
let singleton: AccessEvidenceStore | undefined;
|
|
104
|
+
let hydrated = false;
|
|
105
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
106
|
+
let pendingWrite: AccessEvidenceSnapshot | undefined;
|
|
107
|
+
let writer: Promise<void> | undefined;
|
|
108
|
+
export function accessEvidenceStore(): AccessEvidenceStore {
|
|
109
|
+
if (isSettingsRepositoryInitialized() && !hydrated) { singleton = new AccessEvidenceStore(getCachedAccessEvidence()); hydrated = true; }
|
|
110
|
+
singleton ??= new AccessEvidenceStore();
|
|
111
|
+
return singleton;
|
|
112
|
+
}
|
|
113
|
+
export async function persistAccessEvidence(): Promise<void> {
|
|
114
|
+
if (!isSettingsRepositoryInitialized()) return;
|
|
115
|
+
pendingWrite = accessEvidenceStore().snapshot();
|
|
116
|
+
if (!writer) writer = (async () => {
|
|
117
|
+
while (pendingWrite) {
|
|
118
|
+
const snapshot = pendingWrite;
|
|
119
|
+
pendingWrite = undefined;
|
|
120
|
+
await setCachedAccessEvidence(snapshot);
|
|
121
|
+
}
|
|
122
|
+
})().finally(() => { writer = undefined; });
|
|
123
|
+
await writer;
|
|
124
|
+
if (pendingWrite) await persistAccessEvidence();
|
|
125
|
+
}
|
|
126
|
+
export function observeAccessAttempt(account: AccountConfig, provider: string, model: string, headers: Record<string, string>, status: number | null, detail = "", transport = false): void {
|
|
127
|
+
if (!isSettingsRepositoryInitialized()) return;
|
|
128
|
+
try {
|
|
129
|
+
const agent = Object.entries(headers).find(([key]) => key.toLowerCase() === "user-agent")?.[1];
|
|
130
|
+
const client = !agent ? "unknown" : agent.toLowerCase().startsWith("opencode/") ? "opencode-declared" : "other";
|
|
131
|
+
accessEvidenceStore().observe(account, provider, model, client, status, detail, transport);
|
|
132
|
+
if (!timer) { timer = setTimeout(() => { timer = undefined; void persistAccessEvidence().catch(() => {}); }, 250); timer.unref(); }
|
|
133
|
+
} catch { /* Optional evidence must never fail a completion. */ }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A comparison only. Never interpreted as authorization by the rotation code. */
|
|
137
|
+
export function buildAccessShadowDecision(account: AccountConfig, provider: string, model: string, headers: Record<string, string>, store: AccessEvidenceStore = accessEvidenceStore(), now = Date.now()) {
|
|
138
|
+
const plans = store.forAccount(account, now).plans;
|
|
139
|
+
const declared = plans.find(p => p.provider === provider);
|
|
140
|
+
const providers = account.credentials?.map(c => c.provider) ?? [account.provider ?? "google-antigravity"];
|
|
141
|
+
const tier = account.tier ?? account.type ?? "unknown";
|
|
142
|
+
const inferred = providers.length === 1 && ["free", "plus", "ultra"].includes(tier) ? tier : "unknown";
|
|
143
|
+
const agent = Object.entries(headers).find(([name]) => name.toLowerCase() === "user-agent")?.[1];
|
|
144
|
+
const client = agent?.toLowerCase().startsWith("opencode/") ? "opencode" : agent ? "other" : "unknown";
|
|
145
|
+
const decision = evaluateModelAccess({ provider, model, plan: declared?.plan ?? inferred, client, at: new Date(now).toISOString() });
|
|
146
|
+
return { event: "model-access-policy-shadow", account: createHash("sha256").update(getAccountIdentity(account)).digest("hex"), provider, model,
|
|
147
|
+
plan: decision.declaredPlan, planSource: declared ? "provider-declaration" : inferred === "unknown" ? "unknown" : "single-provider-account",
|
|
148
|
+
clientDeclaration: client, clientVerified: false, policyState: decision.state, wouldBlock: decision.state === "blocked", reason: decision.reason,
|
|
149
|
+
ruleIds: decision.rules.map(r => r.id), enforced: false };
|
|
150
|
+
}
|
|
151
|
+
export function logAccessPolicyShadow(account: AccountConfig, provider: string, model: string, headers: Record<string, string>): void {
|
|
152
|
+
try { console.info("[tuxevil-rotator]", JSON.stringify(buildAccessShadowDecision(account, provider, model, headers))); } catch { /* Never change a request outcome. */ }
|
|
153
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { antigravityCatalogEvidence, advertisedModelState } from "./provider-catalog-evidence.js";
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
3
|
+
import { isSettingsRepositoryInitialized } from "./db-store.js";
|
|
4
|
+
import { isRecord } from "./compat/schema-sanitizer.js";
|
|
5
|
+
import type { AccountRotator } from "./rotator.js";
|
|
6
|
+
import { getAccountIdentity } from "./account-identity.js";
|
|
7
|
+
import { readLimitedBody } from "./body-limit.js";
|
|
8
|
+
import { getProviderAdapter, isKnownProvider } from "./providers/registry.js";
|
|
9
|
+
import { listCatalogModels, isProviderModelOff } from "./model-catalog.js";
|
|
10
|
+
import { accessEvidenceStore, persistAccessEvidence, classifyAccessObservation, logAccessPolicyShadow } from "./access-evidence.js";
|
|
11
|
+
|
|
12
|
+
/** HTTP 200 is insufficient: streaming providers can return an error inside it. */
|
|
13
|
+
export function completedAccessProbe(provider: string, raw: string): boolean {
|
|
14
|
+
try {
|
|
15
|
+
if (provider === "ollama") { const value = JSON.parse(raw); return value.done === true && !value.error; }
|
|
16
|
+
if (provider === "opencode-zen") { const value = JSON.parse(raw); return !value.error && value.choices?.some((c: { finish_reason?: string }) => c.finish_reason); }
|
|
17
|
+
const events = raw.split(/\r?\n/).filter(line => line.startsWith("data:")).flatMap(line => {
|
|
18
|
+
try { return [JSON.parse(line.slice(5).trim())]; } catch { return []; }
|
|
19
|
+
});
|
|
20
|
+
if (events.some(e => e.error || ["error", "response.error", "response.failed"].includes(e.type) || e.response?.error)) return false;
|
|
21
|
+
if (provider === "openai-codex") return events.some(e => e.type === "response.completed");
|
|
22
|
+
return events.some(e => (e.response ?? e).candidates?.some((c: { finishReason?: string }) => c.finishReason === "STOP" || c.finishReason === "MAX_TOKENS"));
|
|
23
|
+
} catch { return false; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let running = false;
|
|
27
|
+
export async function serveAccessProbe(req: IncomingMessage, res: ServerResponse, rotator: AccountRotator): Promise<void> {
|
|
28
|
+
res.setHeader("Cache-Control", "no-store");
|
|
29
|
+
const send = (status: number, value: unknown) => { if (!res.destroyed) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(value)); } };
|
|
30
|
+
if (!isSettingsRepositoryInitialized()) { send(503, { error: "Evidence persistence is not ready" }); return; }
|
|
31
|
+
if (running) { send(409, { error: "An access probe is already running", reason: "probe-busy" }); return; }
|
|
32
|
+
running = true;
|
|
33
|
+
try {
|
|
34
|
+
const input = JSON.parse((await readLimitedBody(req, 4096)).toString("utf8"));
|
|
35
|
+
const { accountId, provider, model } = input;
|
|
36
|
+
if (input.allowUnadvertised !== undefined && typeof input.allowUnadvertised !== "boolean") { send(400, { error: "allowUnadvertised must be boolean" }); return; }
|
|
37
|
+
const diagnosticOverride = input.allowUnadvertised === true;
|
|
38
|
+
if (typeof accountId !== "string" || typeof provider !== "string" || !isKnownProvider(provider) || typeof model !== "string" || model.length > 256) { send(400, { error: "Invalid account, provider or model" }); return; }
|
|
39
|
+
const account = rotator.getBenchmarkAccounts().find(a => getAccountIdentity(a.config) === accountId);
|
|
40
|
+
const providers = account?.config.credentials?.map(c => c.provider) ?? [account?.config.provider ?? "google-antigravity"];
|
|
41
|
+
if (!account || !providers.includes(provider)) { send(400, { error: "Account/provider unavailable", reason: "account-unavailable" }); return; }
|
|
42
|
+
if (!listCatalogModels(rotator).some(m => m.providerId === provider && m.id === model)) { send(400, { error: "Model is not in the provider catalog" }); return; }
|
|
43
|
+
const unavailable = rotator.isProviderOffForAccount(account, provider) ? "provider-disabled" : isProviderModelOff(rotator, provider, model) ? "model-disabled" : account.inFlightRequests >= (rotator.getConfig().maxConcurrentRequestsPerAccount ?? 5) ? "account-busy" : null;
|
|
44
|
+
if (unavailable) { send(409, { error: "Probe unavailable", reason: unavailable }); return; }
|
|
45
|
+
const catalog = provider === "google-antigravity" ? antigravityCatalogEvidence(account.config, rotator.getConfig().quotaPollIntervalMs) : undefined;
|
|
46
|
+
const catalogState = catalog ? advertisedModelState(catalog, model) : "unknown";
|
|
47
|
+
if (catalog && catalogState !== "advertised" && !diagnosticOverride) {
|
|
48
|
+
send(409, { error: "Account catalog does not currently advertise this model", reason: catalog.freshness === "fresh" ? "model-not-advertised" : `catalog-${catalog.freshness}`, catalogAvailability: { state: catalogState, source: catalog.source, observedAt: catalog.observedAt, expiresAt: catalog.expiresAt } }); return;
|
|
49
|
+
}
|
|
50
|
+
const adapter = getProviderAdapter(provider);
|
|
51
|
+
const body = structuredClone(adapter.getBenchmark(account).body);
|
|
52
|
+
body.model = model;
|
|
53
|
+
body.request = { ...(isRecord(body.request) ? body.request : {}), ...(provider === "google-antigravity" ? {} : { model }), ...(provider === "ollama" || provider === "opencode-zen" ? { stream: false } : {}) };
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timer = setTimeout(() => controller.abort(), 30000);
|
|
56
|
+
const disconnect = () => controller.abort();
|
|
57
|
+
res.once("close", disconnect);
|
|
58
|
+
rotator.startRequest(account, model, provider);
|
|
59
|
+
let status: number | null = null, detail = "", transport = false;
|
|
60
|
+
const started = Date.now();
|
|
61
|
+
try {
|
|
62
|
+
await rotator.ensureValidToken(account, provider);
|
|
63
|
+
controller.signal.throwIfAborted();
|
|
64
|
+
if (rotator.getConfig().modelAccessShadow === true) logAccessPolicyShadow(account.config, provider, model, {});
|
|
65
|
+
rotator.recordUpstreamAttempt(account);
|
|
66
|
+
const forwarded = await adapter.forwardRequest(account, body, {}, controller.signal);
|
|
67
|
+
status = forwarded.response.status;
|
|
68
|
+
const reader = forwarded.response.body?.getReader();
|
|
69
|
+
if (reader) {
|
|
70
|
+
const decoder = new TextDecoder(); let size = 0;
|
|
71
|
+
try { while (true) { const chunk = await reader.read(); if (chunk.done) break; size += chunk.value.byteLength; if (size > 262144) throw new Error("Probe response limit"); detail += decoder.decode(chunk.value, { stream: true }); } detail += decoder.decode(); }
|
|
72
|
+
finally { await reader.cancel().catch(() => {}); }
|
|
73
|
+
}
|
|
74
|
+
// Do not turn a successful HTTP envelope with missing/failed completion into access success.
|
|
75
|
+
if (forwarded.response.ok && !completedAccessProbe(provider, detail)) status = null;
|
|
76
|
+
} catch { status = null; transport = true; }
|
|
77
|
+
finally { clearTimeout(timer); res.off("close", disconnect); rotator.finishRequest(account, model, provider); }
|
|
78
|
+
const kind = classifyAccessObservation(status, detail, transport, provider, model);
|
|
79
|
+
accessEvidenceStore().observe(account.config, provider, model, "unknown", status, detail, transport);
|
|
80
|
+
await persistAccessEvidence();
|
|
81
|
+
const observation = accessEvidenceStore().forAccount(account.config).observations.find(o => o.provider === provider && o.model === model && o.client === "unknown");
|
|
82
|
+
send(200, { provider, model, failureReason: kind === "model-unavailable" ? "provider-model-not-supported-for-account" : undefined, diagnosticOverride, catalogAvailability: catalogState, kind, status, observedAt: observation?.observedAt, expiresAt: observation?.expiresAt, durationMs: Date.now() - started, clientVerified: false, enforced: false });
|
|
83
|
+
} catch { send(400, { error: "Probe input or persistence unavailable" }); }
|
|
84
|
+
finally { running = false; }
|
|
85
|
+
}
|
package/src/admin-auth.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isUsageReadToken, carriesUsageReadToken } from "./usage-limits-auth.js";
|
|
1
2
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
3
|
import {
|
|
3
4
|
createHash,
|
|
@@ -277,7 +278,7 @@ export function hasValidDashboardSession(
|
|
|
277
278
|
req: AdminAuthRequest,
|
|
278
279
|
expectedToken: string | null = getConfiguredAdminToken(),
|
|
279
280
|
): boolean {
|
|
280
|
-
if (!expectedToken) return false;
|
|
281
|
+
if (!expectedToken || isUsageReadToken(expectedToken)) return false;
|
|
281
282
|
const value = readRequestCookie(req, DASHBOARD_SESSION_COOKIE);
|
|
282
283
|
loadPersistedRevocations();
|
|
283
284
|
if (persistedRevocationsLoadError && isSettingsRepositoryInitialized()) {
|
|
@@ -291,6 +292,7 @@ export function isAdminTokenValid(
|
|
|
291
292
|
candidate: string | null | undefined,
|
|
292
293
|
expectedToken: string | null = getConfiguredAdminToken(),
|
|
293
294
|
): boolean {
|
|
295
|
+
if (isUsageReadToken(candidate)) return false;
|
|
294
296
|
if (!expectedToken) return true;
|
|
295
297
|
return typeof candidate === "string" && safeEqual(candidate, expectedToken);
|
|
296
298
|
}
|
|
@@ -299,6 +301,7 @@ export function isAdminAuthorized(
|
|
|
299
301
|
req: AdminAuthRequest,
|
|
300
302
|
expectedToken: string | null = getConfiguredAdminToken(),
|
|
301
303
|
): boolean {
|
|
304
|
+
if (carriesUsageReadToken(req) || isUsageReadToken(expectedToken)) return false;
|
|
302
305
|
if (!expectedToken) return true;
|
|
303
306
|
if (isAdminTokenValid(getRequestAdminToken(req), expectedToken)) return true;
|
|
304
307
|
if (!hasValidDashboardSession(req, expectedToken)) return false;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AccountConfig } from "./types.js";
|
|
2
|
+
import { accessEvidenceStore, type AccessEvidenceStore } from "./access-evidence.js";
|
|
3
|
+
/** Inputs are operationally eligible accounts. One account's denial never excludes its siblings. */
|
|
4
|
+
export function summarizeAutoAccess(accounts: AccountConfig[], provider: string, model: string, store: AccessEvidenceStore = accessEvidenceStore(), now = Date.now()) {
|
|
5
|
+
let rejectedAccounts=0;
|
|
6
|
+
for(const account of accounts){
|
|
7
|
+
const latest=store.forAccount(account,now).observations.filter(o=>o.provider===provider&&o.model===model&&o.client==='unknown').sort((a,b)=>b.observedAt-a.observedAt)[0];
|
|
8
|
+
if(latest&&['model-unavailable','entitlement'].includes(latest.kind))rejectedAccounts++;
|
|
9
|
+
}
|
|
10
|
+
return {eligibleAccounts:accounts.length,rejectedAccounts,wouldExclude:accounts.length>0&&rejectedAccounts===accounts.length};
|
|
11
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { accessEvidenceStore, type AccessEvidenceStore } from "./access-evidence.js";
|
|
2
|
+
import { evaluateModelAccess, MODEL_ACCESS_RULES } from "./model-access.js";
|
|
3
|
+
import type { AccountConfig } from "./types.js";
|
|
4
|
+
|
|
5
|
+
export interface AutoModelAccessDecision {
|
|
6
|
+
eligible: boolean;
|
|
7
|
+
plan: string;
|
|
8
|
+
planSource:
|
|
9
|
+
| "provider-declaration"
|
|
10
|
+
| "operator-provider-default"
|
|
11
|
+
| "account-tier"
|
|
12
|
+
| "unknown";
|
|
13
|
+
reason: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface AutoAccountScope {
|
|
17
|
+
providerId: string;
|
|
18
|
+
modelId: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function matchesRule(rule: (typeof MODEL_ACCESS_RULES)[number], model: string): boolean {
|
|
22
|
+
if (rule.modelPrefix === "*-free") return model.endsWith("-free");
|
|
23
|
+
return rule.exact
|
|
24
|
+
? rule.modelPrefix === model
|
|
25
|
+
: model === rule.modelPrefix || model.startsWith(`${rule.modelPrefix}-`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function providersForAccount(account: AccountConfig): string[] {
|
|
29
|
+
const providers = account.credentials?.map((credential) => credential.provider) ?? [];
|
|
30
|
+
if (providers.length) return [...new Set(providers)];
|
|
31
|
+
return [
|
|
32
|
+
account.provider === "google"
|
|
33
|
+
? "google-antigravity"
|
|
34
|
+
: account.provider ?? "google-antigravity",
|
|
35
|
+
];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function accountTierPlan(account: AccountConfig, provider: string): string | undefined {
|
|
39
|
+
const tier = account.tier ?? account.type;
|
|
40
|
+
if (tier && ["free", "plus", "ultra", "team"].includes(tier)) return tier;
|
|
41
|
+
// The operator has confirmed that the configured Antigravity Pro accounts
|
|
42
|
+
// are paid. This inference applies only to their primary Google provider.
|
|
43
|
+
if (provider === "google-antigravity" && tier === "pro") return "pro-paid";
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isModelAccessRejection(kind: string): boolean {
|
|
48
|
+
return ["payment-or-plan", "entitlement", "model-unavailable"].includes(kind);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function evaluateAutoModelAccess(
|
|
52
|
+
account: AccountConfig,
|
|
53
|
+
provider: string,
|
|
54
|
+
model: string,
|
|
55
|
+
store: AccessEvidenceStore = accessEvidenceStore(),
|
|
56
|
+
now = Date.now(),
|
|
57
|
+
): AutoModelAccessDecision {
|
|
58
|
+
const evidence = store.forAccount(account, now);
|
|
59
|
+
const declared = evidence.plans
|
|
60
|
+
.filter((entry) => entry.provider === provider)
|
|
61
|
+
.sort((a, b) => b.observedAt - a.observedAt)[0];
|
|
62
|
+
let plan = declared?.plan ?? "unknown";
|
|
63
|
+
let planSource: AutoModelAccessDecision["planSource"] = declared
|
|
64
|
+
? "provider-declaration"
|
|
65
|
+
: "unknown";
|
|
66
|
+
|
|
67
|
+
if (!declared && provider === "ollama") {
|
|
68
|
+
// The operator confirmed that all linked Ollama accounts are Free.
|
|
69
|
+
plan = "free";
|
|
70
|
+
planSource = "operator-provider-default";
|
|
71
|
+
} else if (!declared) {
|
|
72
|
+
const providers = providersForAccount(account);
|
|
73
|
+
const isPrimaryGoogle =
|
|
74
|
+
provider === "google-antigravity" &&
|
|
75
|
+
(account.provider === undefined ||
|
|
76
|
+
account.provider === "google" ||
|
|
77
|
+
account.provider === "google-antigravity");
|
|
78
|
+
if (isPrimaryGoogle || providers.length === 1) {
|
|
79
|
+
const inferred = accountTierPlan(account, provider);
|
|
80
|
+
if (inferred) {
|
|
81
|
+
plan = inferred;
|
|
82
|
+
planSource = "account-tier";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const latestObservation = evidence.observations
|
|
88
|
+
.filter(
|
|
89
|
+
(entry) =>
|
|
90
|
+
entry.provider === provider &&
|
|
91
|
+
entry.model === model &&
|
|
92
|
+
["success", "payment-or-plan", "entitlement", "model-unavailable"].includes(
|
|
93
|
+
entry.kind,
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
.sort(
|
|
97
|
+
(a, b) =>
|
|
98
|
+
b.observedAt - a.observedAt ||
|
|
99
|
+
Number(isModelAccessRejection(b.kind)) - Number(isModelAccessRejection(a.kind)),
|
|
100
|
+
)[0];
|
|
101
|
+
if (
|
|
102
|
+
latestObservation &&
|
|
103
|
+
isModelAccessRejection(latestObservation.kind)
|
|
104
|
+
) {
|
|
105
|
+
return {
|
|
106
|
+
eligible: false,
|
|
107
|
+
plan,
|
|
108
|
+
planSource,
|
|
109
|
+
reason: `recent ${latestObservation.kind} rejection for this account and model`,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (plan === "unknown") {
|
|
114
|
+
const hasPlanSpecificRule = MODEL_ACCESS_RULES.some((rule) =>
|
|
115
|
+
rule.provider === provider && matchesRule(rule, model),
|
|
116
|
+
);
|
|
117
|
+
if (provider === "openai-codex" || hasPlanSpecificRule) {
|
|
118
|
+
return {
|
|
119
|
+
eligible: false,
|
|
120
|
+
plan,
|
|
121
|
+
planSource,
|
|
122
|
+
reason: "provider plan is unknown for this model's access policy",
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
eligible: true,
|
|
127
|
+
plan,
|
|
128
|
+
planSource,
|
|
129
|
+
reason: "no confirmed plan restriction for this model",
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const matchingRules = MODEL_ACCESS_RULES.filter((rule) =>
|
|
134
|
+
rule.provider === provider &&
|
|
135
|
+
(rule.plans.includes(plan) || rule.plans.includes("*")) &&
|
|
136
|
+
matchesRule(rule, model),
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
const decision = evaluateModelAccess({
|
|
140
|
+
provider,
|
|
141
|
+
model,
|
|
142
|
+
plan,
|
|
143
|
+
at: new Date(now).toISOString(),
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// Free accounts have a complete, operator-confirmed catalog for these
|
|
147
|
+
// providers. Unknown or stale entries must not silently inherit free access.
|
|
148
|
+
if ((provider === "ollama" || provider === "openai-codex") && plan === "free") {
|
|
149
|
+
const confirmedAllow = matchingRules.some((rule) =>
|
|
150
|
+
rule.state === "allowed" && rule.evidence === "operator-confirmed",
|
|
151
|
+
);
|
|
152
|
+
if (!confirmedAllow || decision.state === "unknown") {
|
|
153
|
+
return {
|
|
154
|
+
eligible: false,
|
|
155
|
+
plan,
|
|
156
|
+
planSource,
|
|
157
|
+
reason: confirmedAllow
|
|
158
|
+
? "Free-plan model policy needs re-verification"
|
|
159
|
+
: "model is outside the confirmed Free-plan auto-routing list",
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (provider === "google-antigravity" && ["free", "plus"].includes(plan)) {
|
|
164
|
+
// The operator confirmed Free/Plus access is limited to the listed model
|
|
165
|
+
// families. Do not treat an unlisted dynamic-catalog entry as permission.
|
|
166
|
+
const listedAllow = matchingRules.some((rule) => rule.state === "allowed");
|
|
167
|
+
if (!listedAllow) {
|
|
168
|
+
return {
|
|
169
|
+
eligible: false,
|
|
170
|
+
plan,
|
|
171
|
+
planSource,
|
|
172
|
+
reason: decision.state === "blocked"
|
|
173
|
+
? decision.reason
|
|
174
|
+
: "model is outside the confirmed Antigravity Free/Plus auto-routing list",
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
if (decision.state !== "allowed") {
|
|
178
|
+
return { eligible: false, plan, planSource, reason: decision.reason };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (decision.state === "blocked" || decision.state === "conditional") {
|
|
182
|
+
return { eligible: false, plan, planSource, reason: decision.reason };
|
|
183
|
+
}
|
|
184
|
+
return { eligible: true, plan, planSource, reason: decision.reason };
|
|
185
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Transient output-quality circuit, separate from account entitlement evidence. */
|
|
2
|
+
const failures=new Map<string,number>();
|
|
3
|
+
const key=(provider:string,model:string)=>JSON.stringify([provider,model]);
|
|
4
|
+
export function markEmptyAutoOutput(provider:string,model:string,now=Date.now()):void {
|
|
5
|
+
for(const [k,expiry] of failures)if(expiry<=now)failures.delete(k);
|
|
6
|
+
if(failures.size>=256)failures.delete(failures.keys().next().value!);
|
|
7
|
+
failures.set(key(provider,model),now+300000);
|
|
8
|
+
}
|
|
9
|
+
export function isAutoOutputCooling(provider:string,model:string,now=Date.now()):boolean {
|
|
10
|
+
const k=key(provider,model),expiry=failures.get(k);if(expiry===undefined)return false;
|
|
11
|
+
if(expiry<=now){failures.delete(k);return false;}return true;
|
|
12
|
+
}
|