tuxevil-rotator 4.2.2 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -1
- package/README.md +11 -4
- package/package.json +2 -1
- package/plugins/opencode-discovery/capabilities.d.mts +7 -0
- package/plugins/opencode-discovery/capabilities.mjs +54 -0
- package/plugins/opencode-discovery/index.d.mts +2 -1
- package/plugins/opencode-discovery/index.mjs +6 -1
- package/plugins/opencode-discovery/package.json +3 -1
- package/src/access-evidence.ts +153 -0
- package/src/access-probe.ts +85 -0
- package/src/admin-auth.ts +4 -1
- package/src/audio-transcription.ts +32 -6
- 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/cli.ts +3 -3
- package/src/compat/model-specs.ts +4 -0
- package/src/compat.ts +253 -37
- 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-app.ts +1 -0
- package/src/dashboard.ts +5 -0
- package/src/db-store.ts +10 -0
- package/src/index.ts +2 -0
- package/src/install-agent.ts +211 -129
- package/src/install-opencode.ts +80 -18
- 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/catalog.ts +14 -6
- package/src/providers/google-antigravity/dynamic-catalog.ts +87 -3
- package/src/providers/google-antigravity/forward.ts +4 -2
- package/src/providers/google-antigravity/quota.ts +7 -0
- package/src/providers/ollama/context-window.ts +13 -0
- package/src/providers/ollama/forward.ts +10 -0
- package/src/providers/ollama/quota.ts +4 -0
- package/src/providers/ollama/translators.ts +19 -2
- package/src/providers/openai-codex/catalog.ts +157 -18
- 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 +113 -5
- package/src/quota-observation.ts +26 -0
- package/src/quota-pools.ts +322 -0
- package/src/rotator.ts +167 -40
- package/src/settings-repository.ts +1 -0
- package/src/types.ts +106 -29
- package/src/usage-limits-auth.ts +24 -0
- package/src/usage-limits.ts +148 -0
- package/src/validators.ts +26 -0
- package/src/web/app.tsx +4 -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/audio-recorder.ts +159 -0
- package/src/web/lib/colors.ts +4 -0
- package/src/web/lib/playground-storage.ts +261 -0
- package/src/web/lib/playground.ts +483 -0
- package/src/web/lib/pool-navigation.ts +4 -0
- package/src/web/lib/pools.ts +2 -243
- package/src/web/nav.ts +1 -0
- 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 +1692 -0
- package/src/web/pages/Transcription.tsx +562 -0
- package/src/web/state/api.ts +6 -0
- package/src/web/state/playground-client.ts +136 -0
- package/src/web/state/playground.ts +69 -0
- package/src/web/state/router.ts +2 -2
- package/src/web/state/transcription-client.ts +93 -0
- package/src/web/styles/app.css +501 -0
- package/tools/telemetry-receiver/receiver.js +59 -46
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## [
|
|
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
|
+
|
|
24
|
+
## [4.3.0] - 2026-10-29
|
|
25
|
+
|
|
26
|
+
### Added
|
|
27
|
+
|
|
28
|
+
- **Dashboard Playground**: New `/dashboard/playground` workspace (`?tab=chat|compare|compliance|transcription`) for testing enabled models directly from an authenticated admin session via same-origin `/api/playground/chat/completions`, `/api/playground/audio/transcriptions`, and `/api/playground/config` routes without requiring a virtual key. ([PR #43](https://github.com/tuxevil/tuxevil-rotator/pull/43))
|
|
29
|
+
- **Chat & Compare**: Multi-turn chat with PNG/JPEG/WebP vision attachments, system prompt, streaming, temperature, max output tokens, reasoning effort, and OpenAI tools JSON inspection, plus side-by-side 2–3 model comparison with synchronized or per-panel controls.
|
|
30
|
+
- **API Compliance**: Five-case Chat Completions verification suite (basic response structure, SSE streaming, system instruction, JSON mode output, and forced tool calling) across up to three concurrent model workers.
|
|
31
|
+
- **Transcription**: Audio file upload (`.wav`, `.mp3`, `.m4a`, `.webm`, `.ogg`, `.oga`, `.flac`, `.pcm`) and browser `MediaRecorder` microphone capture with preview, lifecycle cleanup, and transcript export.
|
|
32
|
+
- **Local workspaces**: Browser IndexedDB persistence with versioned JSON export/import and privacy-mask redaction; raw audio stays in-tab only.
|
|
33
|
+
- **Codex reasoning metadata & agent connectors**: Expose `meta.reasoning`, `meta.reasoning_efforts` (`low`, `medium`, `high`, `xhigh`, `max`), and `meta.default_reasoning_effort` on Codex entries in `GET /v1/models` from upstream discovery and known-model defaults (excluding harness-only `ultra`). Propagate reasoning capabilities across `install-opencode`, the OpenCode 2 discovery plugin (including metadata-only refreshes), and `install-agent` for OpenCode, Hermes, Pi, and the new `openclaw` target (`--target openclaw`, `auto`, and `all`) while preserving existing user configs. ([PR #43](https://github.com/tuxevil/tuxevil-rotator/pull/43))
|
|
34
|
+
|
|
35
|
+
### Fixed
|
|
36
|
+
|
|
37
|
+
- **Ollama vision base64 payloads**: Strip `data:<mime>;base64,` prefixes when building Ollama `images[]` payloads so multimodal requests (such as `gemma4:31b`) no longer fail upstream with `illegal base64 data`.
|
|
38
|
+
- **OGA audio uploads**: Accept `.oga` files in the transcription playground and preserve `audio/ogg` MIME type and raw Ogg bytes without PCM/WAV re-wrapping. ([PR #43](https://github.com/tuxevil/tuxevil-rotator/pull/43))
|
|
39
|
+
- **Persistent Antigravity catalogs**: Save versioned model snapshots per account with credential fingerprints and validated metadata, restoring availability before the first quota poll. Persist successful catalog updates even without quota values, reject malformed saved snapshots, and exclude disabled or flagged accounts. Historical model IDs without an active snapshot return 404 without forwarding. ([PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42) by [@javargasm](https://github.com/javargasm))
|
|
40
|
+
- **Antigravity benchmark responses**: Extract visible text from the upstream `response.candidates` envelope, omit thinking parts, and count cumulative output-token usage once instead of summing repeated totals. Verified with a live `gemini-3-flash` response returning `OK` and one output token.
|
|
41
|
+
|
|
42
|
+
### Changed
|
|
43
|
+
|
|
44
|
+
- **Dynamic model metadata**: Allow upstream-advertised Gemini 3.5 IDs, preserve exact model variants and explicit effort aliases, and prefer dynamic context metadata after operator overrides. Add Gemini 4 Argon metadata without inventing availability for unadvertised variants. ([PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42))
|
|
45
|
+
- **Antigravity client headers**: Update the default client version to 2.26.0 with the `antigravity/hub` User-Agent and include client metadata headers on quota requests. ([PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42))
|
|
46
|
+
- **Pricing estimates**: Refresh model pricing and synchronize the standalone telemetry receiver table; document official sources, historical estimates, promotional windows, and estimation limits in [the pricing audit](docs/model-pricing.md). ([PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42))
|
|
47
|
+
|
|
48
|
+
### Contributors
|
|
49
|
+
|
|
50
|
+
- Thanks to [@javargasm](https://github.com/javargasm) for persistent Antigravity catalog snapshots, snapshot-based admission, model metadata and client-header updates, pricing maintenance, and restart/HTTP routing regression coverage in [PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42).
|
|
4
51
|
|
|
5
52
|
## [4.2.2] - 2026-10-24
|
|
6
53
|
|
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.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))
|
|
61
|
+
|
|
58
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))
|
|
59
63
|
|
|
60
64
|
- **v4.2.0: Effort routing editor**: Create, edit, rename and disable effort aliases from the Models page, with route previews and unsaved-edit protection. Claude-style requests now select variants from `output_config.effort` or thinking budgets, and model configuration edits apply immediately. Includes automatic discovery of future Codex GPT models across account catalogs. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.2.0); [PR #40](https://github.com/tuxevil/tuxevil-rotator/pull/40) by [@CyR1en](https://github.com/CyR1en))
|
|
@@ -73,7 +77,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
73
77
|
- **Tier-first routing under concurrency**: Concurrent least-loaded account selection now enforces tier priority, and persisted lower-tier assignments are re-evaluated while idle. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
|
|
74
78
|
- **Codex kickstart lifecycle**: Unstarted Codex quota timers are kicked off on startup and stale kickstart responses are drained to avoid blocking subsequent requests. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
|
|
75
79
|
- **Gemini 3.8 Flash Support**: Native Antigravity model IDs `gemini-3.8-flash-high`, `gemini-3.8-flash-medium`, and `gemini-3.8-flash-low`, with 1M-token context, 65,536-token output, pricing, quota routing, dashboard visualization, and telemetry support. Gemini 3.5 Flash has been removed from the user-facing catalog to match Antigravity 2.11. ([PR #28](https://github.com/tuxevil/tuxevil-rotator/pull/28) by [@CyR1en](https://github.com/CyR1en))
|
|
76
|
-
- **Dynamic Antigravity Discovery**: Successful quota polls reconcile live model IDs and metadata per full account identity. Newly advertised models appear in `/v1/models` and route only to accounts that advertised them; removed models disappear without falling back to the generic Gemini pool.
|
|
80
|
+
- **Dynamic Antigravity Discovery**: Successful quota polls reconcile live model IDs and metadata per full account identity. Newly advertised models appear in `/v1/models` and route only to accounts that advertised them; removed models disappear without falling back to the generic Gemini pool. Configured `modelSpecs` substring overrides retain precedence. The original Gemini 3.5 discovery restriction was lifted in [PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42); availability now follows upstream snapshots. ([PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29) by [@javargasm](https://github.com/javargasm))
|
|
77
81
|
- **Dynamic Catalog Hardening**: Quota snapshots reject malformed data while preserving the last known-good state, stale account responses are ignored, and dynamic model ownership and quota-safety state survive restarts without routing a model through an account that did not advertise it. ([PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30) by [@javargasm](https://github.com/javargasm))
|
|
78
82
|
- **Partial Model Specification Overrides**: `modelSpecs` entries can override selected output, thinking, and context fields while inheriting the remaining effective runtime, static, or family metadata. Overrides are preserved through configuration normalization and persistence. ([PR #31](https://github.com/tuxevil/tuxevil-rotator/pull/31) by [@javargasm](https://github.com/javargasm))
|
|
79
83
|
- **Effort-Based Model Routing**: Optional `effortRouting` aliases dispatch requests to concrete model variants from `reasoning_effort`, while preserving the alias for clients and tracking quotas against the resolved target. See [Effort-Based Model Routing](docs/configuration.md#effort-based-model-routing). ([PR #32](https://github.com/tuxevil/tuxevil-rotator/pull/32) by [@CyR1en](https://github.com/CyR1en))
|
|
@@ -236,9 +240,11 @@ You can configure supported local agents automatically with:
|
|
|
236
240
|
|
|
237
241
|
```bash
|
|
238
242
|
tuxevil-rotator install-agent --target auto
|
|
243
|
+
# Select agents explicitly (includes model reasoning capabilities):
|
|
244
|
+
tuxevil-rotator install-agent --target opencode,hermes,openclaw
|
|
239
245
|
```
|
|
240
246
|
|
|
241
|
-
Use `--target all` or a comma-separated list (`opencode,hermes,pi,codex`) to choose clients. Add `--host <hostname> --user <ssh-user>` to configure them over SSH, or `--dry-run` to review the generated installer first. For OpenCode's live model catalog, use `tuxevil-rotator install-opencode`; see the [OpenCode integration guide](docs/integrations/opencode.md).
|
|
247
|
+
Use `--target all` or a comma-separated list (`opencode,hermes,openclaw,pi,codex`) to choose clients. Add `--host <hostname> --user <ssh-user>` to configure them over SSH, or `--dry-run` to review the generated installer first. For OpenCode's live model catalog, use `tuxevil-rotator install-opencode`; see the [OpenCode integration guide](docs/integrations/opencode.md).
|
|
242
248
|
|
|
243
249
|
> **Rather have your agent do all of this?** The [`agent-install-prompt`](docs/agent-install-prompt.md) is a copy-paste prompt (English/Spanish) that makes any coding agent perform the whole setup for a non-technical user: install, account logins with hand-holding, background service, agent wiring, and verification.
|
|
244
250
|
|
|
@@ -299,6 +305,7 @@ After starting the proxy, open `http://localhost:51200/dashboard` and sign in wi
|
|
|
299
305
|
- **Overview** — whether routing works right now, one row per model pool (Claude, Gemini, Codex, Ollama, OpenCode) with pooled quota, the account serving it, what is next in line, the next reset and how long the quota lasts at the current rate, plus a list of what needs you with the fix one click away
|
|
300
306
|
- **Accounts** — cards with each account's quota per model, or a compact sortable list; each account opens a drawer with its quota windows, routing decisions, health breakdown, limits and every action (re-enable, restore, start idle windows, tier, quarantine, remove)
|
|
301
307
|
- **Models** — provider order, provider and per-account switches, individual model switches, quota and health summaries, and optional review of newly discovered models
|
|
308
|
+
- **Playground** — interactive Chat (with vision and tools inspection), side-by-side 2–3 model Compare, 5-case Chat Completions API Compliance, and Audio Transcription (file upload and microphone recording) with browser-saved workspaces and JSON export/import
|
|
302
309
|
- **Requests** — a live tail of requests and rotator events, and with PostgreSQL the full history with payloads and per-key totals
|
|
303
310
|
- **Usage** — token volume by model with 1h–30d ranges, estimated savings at list prices, latency percentiles and a 60-day activity heatmap
|
|
304
311
|
- **Virtual keys** and **Settings** — key management, routing controls and policy, a benchmark, and the raw configuration file
|
|
@@ -388,11 +395,11 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
388
395
|
|
|
389
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))
|
|
390
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))
|
|
391
|
-
- **[@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, and regression coverage. ([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))
|
|
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))
|
|
392
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))
|
|
393
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))
|
|
394
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))
|
|
395
|
-
- **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, account-scoped dynamic Antigravity discovery and routing, dynamic catalog and quota-safety hardening, persistent dynamic model ownership across restarts, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, compat test suite expansion, model-scoped cooldowns, explicit Antigravity reset-duration parsing, idle pool normalization, RAW POLL deadline reconciliation, serialized per-account quota polling, Ollama kickstart routing for multi-provider accounts, and OpenAI-compatible audio transcription plus bidirectional live WebSocket streaming through the local Antigravity observer model, with PR #36 adding rotator-backed transcription, Language Server fallback, model-scope checks, and live timeout/control-frame hardening. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24), [PR #26](https://github.com/tuxevil/tuxevil-rotator/pull/26), [PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29), [PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30), [PR #31](https://github.com/tuxevil/tuxevil-rotator/pull/31), [PR #33](https://github.com/tuxevil/tuxevil-rotator/pull/33), [PR #36](https://github.com/tuxevil/tuxevil-rotator/pull/36))
|
|
402
|
+
- **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, account-scoped dynamic Antigravity discovery and routing, dynamic catalog and quota-safety hardening, persistent dynamic model ownership and validated catalog snapshots across restarts, exact upstream variant preservation, snapshot-based request admission, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, compat test suite expansion, model-scoped cooldowns, explicit Antigravity reset-duration parsing, idle pool normalization, RAW POLL deadline reconciliation, serialized per-account quota polling, Ollama kickstart routing for multi-provider accounts, and OpenAI-compatible audio transcription plus bidirectional live WebSocket streaming through the local Antigravity observer model, with PR #36 adding rotator-backed transcription, Language Server fallback, model-scope checks, and live timeout/control-frame hardening. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24), [PR #26](https://github.com/tuxevil/tuxevil-rotator/pull/26), [PR #29](https://github.com/tuxevil/tuxevil-rotator/pull/29), [PR #30](https://github.com/tuxevil/tuxevil-rotator/pull/30), [PR #31](https://github.com/tuxevil/tuxevil-rotator/pull/31), [PR #33](https://github.com/tuxevil/tuxevil-rotator/pull/33), [PR #36](https://github.com/tuxevil/tuxevil-rotator/pull/36), [PR #42](https://github.com/tuxevil/tuxevil-rotator/pull/42))
|
|
396
403
|
|
|
397
404
|
## Development
|
|
398
405
|
|
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,7 @@
|
|
|
1
|
+
import type { RawRotatorModel } from "./index.mjs";
|
|
2
|
+
export function reasoningCapabilities(raw: RawRotatorModel): { supported: boolean; efforts: string[]; defaultEffort?: string };
|
|
3
|
+
export function openCodeReasoning(raw: RawRotatorModel): Record<string, unknown>;
|
|
4
|
+
export function openCodeVariants(raw: RawRotatorModel): Array<{ id: string; settings: { reasoningEffort: string } }>;
|
|
5
|
+
export function mergeOpenCodeModels(existing?: Record<string, unknown>, models?: RawRotatorModel[]): Record<string, unknown>;
|
|
6
|
+
export function mapAgentModel(raw: RawRotatorModel): Record<string, unknown>;
|
|
7
|
+
export function fetchModels(baseURL: string, apiKey?: string, timeoutMs?: number): Promise<RawRotatorModel[]>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Model capability translation shared by discovery and standalone installers.
|
|
2
|
+
// Scalar API efforts only: harness modes such as "ultra" are not wire values.
|
|
3
|
+
const EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max"])
|
|
4
|
+
export function reasoningCapabilities(raw) {
|
|
5
|
+
const meta = raw.meta || raw.info || {}
|
|
6
|
+
const supported = Boolean(meta.reasoning ?? meta.thinking)
|
|
7
|
+
const efforts = supported && Array.isArray(meta.reasoning_efforts)
|
|
8
|
+
? [...new Set(meta.reasoning_efforts.filter(value => EFFORTS.has(value)))] : []
|
|
9
|
+
return { supported, efforts, defaultEffort: efforts.includes(meta.default_reasoning_effort) ? meta.default_reasoning_effort : undefined }
|
|
10
|
+
}
|
|
11
|
+
export function openCodeReasoning(raw) {
|
|
12
|
+
const { supported, efforts } = reasoningCapabilities(raw)
|
|
13
|
+
if (!supported) return {}
|
|
14
|
+
return { reasoning: { supported: true, ...(efforts.length ? { effort: efforts.filter(e => e !== "none"), ...(efforts.includes("none") ? { toggle: true } : {}) } : {}) } }
|
|
15
|
+
}
|
|
16
|
+
export function openCodeVariants(raw) {
|
|
17
|
+
return reasoningCapabilities(raw).efforts.map(effort => ({ id: effort, settings: { reasoningEffort: effort } }))
|
|
18
|
+
}
|
|
19
|
+
/** Legacy OpenCode config is migrated by V2; keep user options/variants authoritative. */
|
|
20
|
+
export function mergeOpenCodeModels(existing = {}, rawModels = []) {
|
|
21
|
+
const merged = { ...existing }
|
|
22
|
+
for (const raw of rawModels) {
|
|
23
|
+
const meta = raw.meta || {}
|
|
24
|
+
const prior = merged[raw.id] || {}
|
|
25
|
+
const reasoning = reasoningCapabilities(raw)
|
|
26
|
+
const variants = Object.fromEntries(reasoning.efforts.map(effort => [effort, { reasoningEffort: effort }]))
|
|
27
|
+
merged[raw.id] = { name: raw.id, ...prior,
|
|
28
|
+
limit: { context: meta.context_length || raw.context_window || 128000, output: meta.max_output_tokens || 8192, ...prior.limit },
|
|
29
|
+
...(reasoning.supported && prior.reasoning === undefined ? { reasoning: true } : {}),
|
|
30
|
+
...(reasoning.efforts.length ? { variants: { ...variants, ...prior.variants } } : {}),
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return merged
|
|
34
|
+
}
|
|
35
|
+
export function mapAgentModel(raw) {
|
|
36
|
+
const meta = raw.meta || {}
|
|
37
|
+
const reasoning = reasoningCapabilities(raw)
|
|
38
|
+
return { id: raw.id, name: raw.name || raw.id, reasoning: reasoning.supported,
|
|
39
|
+
input: meta.multimodal ? ["text", "image"] : ["text"],
|
|
40
|
+
contextWindow: meta.context_length || raw.context_window || 128000,
|
|
41
|
+
maxTokens: meta.max_output_tokens || 8192,
|
|
42
|
+
...(reasoning.efforts.length ? { compat: { supportsReasoningEffort: true, supportedReasoningEfforts: reasoning.efforts } } : {}),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export async function fetchModels(baseURL, apiKey, timeoutMs = 3500) {
|
|
46
|
+
const response = await fetch(baseURL.replace(/\/+$/, "") + "/models", {
|
|
47
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
48
|
+
headers: { Accept: "application/json", ...(apiKey && apiKey !== "no-key" ? { Authorization: `Bearer ${apiKey}` } : {}) },
|
|
49
|
+
})
|
|
50
|
+
if (!response.ok) throw new Error(`Model catalog HTTP ${response.status}`)
|
|
51
|
+
const body = await response.json()
|
|
52
|
+
if (!Array.isArray(body.data)) throw new Error("Invalid model catalog")
|
|
53
|
+
return body.data.filter(model => typeof model?.id === "string" && model.id.length > 0)
|
|
54
|
+
}
|
|
@@ -41,7 +41,8 @@ export interface RawRotatorModel {
|
|
|
41
41
|
export interface ModelDef {
|
|
42
42
|
name: string;
|
|
43
43
|
limit: { context: number; output: number };
|
|
44
|
-
capabilities: { tools: boolean; input: string[]; output: string[] };
|
|
44
|
+
capabilities: { tools: boolean; input: string[]; output: string[]; reasoning?: unknown };
|
|
45
|
+
variants?: Array<{ id: string; settings: { reasoningEffort: string } }>;
|
|
45
46
|
}
|
|
46
47
|
|
|
47
48
|
export function normalizeProviderEntries(input: unknown): ProviderEntry[];
|
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
* - refreshMs background re-discovery interval (default 600000; 0 disables)
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
+
import { openCodeReasoning, openCodeVariants } from "./capabilities.mjs"
|
|
21
|
+
|
|
20
22
|
const PLUGIN_ID = "tuxevil.model-discovery"
|
|
21
23
|
const DEFAULT_BASE_URL = "http://127.0.0.1:51200/v1"
|
|
22
24
|
const DEFAULT_PROVIDER_PACKAGE = "@opencode/ai/providers/openai-compatible"
|
|
@@ -208,7 +210,9 @@ export function mapModelToOpenCode(rawModel) {
|
|
|
208
210
|
tools: toolCalling,
|
|
209
211
|
input: isMultimodal ? ["text", "image"] : ["text"],
|
|
210
212
|
output: ["text"],
|
|
213
|
+
...openCodeReasoning(rawModel),
|
|
211
214
|
},
|
|
215
|
+
...(openCodeVariants(rawModel).length ? { variants: openCodeVariants(rawModel) } : {}),
|
|
212
216
|
},
|
|
213
217
|
}
|
|
214
218
|
}
|
|
@@ -230,7 +234,7 @@ function safeGet(editor, id) {
|
|
|
230
234
|
function modelSignature(models) {
|
|
231
235
|
return JSON.stringify(
|
|
232
236
|
(models ?? [])
|
|
233
|
-
.map((model) => model?.id)
|
|
237
|
+
.map((model) => [model?.id, model?.meta])
|
|
234
238
|
.filter(Boolean)
|
|
235
239
|
.sort(),
|
|
236
240
|
)
|
|
@@ -294,6 +298,7 @@ export default {
|
|
|
294
298
|
name: existingModel?.name || modelDef.name,
|
|
295
299
|
capabilities: { ...modelDef.capabilities, ...(existingModel?.capabilities ?? {}) },
|
|
296
300
|
limit: { ...modelDef.limit, ...(existingModel?.limit ?? {}) },
|
|
301
|
+
...(modelDef.variants ? { variants: [...new Map([...modelDef.variants, ...(Array.isArray(existingModel?.variants) ? existingModel.variants : [])].map(v => [v.id, v])).values()] } : {}),
|
|
297
302
|
}
|
|
298
303
|
}
|
|
299
304
|
|
|
@@ -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;
|