tuxevil-rotator 4.2.1 → 4.3.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 +20 -6
- package/package.json +3 -3
- package/plugins/opencode-discovery/capabilities.d.mts +7 -0
- package/plugins/opencode-discovery/capabilities.mjs +54 -0
- package/plugins/opencode-discovery/index.d.mts +60 -0
- package/plugins/opencode-discovery/index.mjs +333 -0
- package/plugins/opencode-discovery/package.json +24 -0
- package/src/audio-transcription.ts +32 -6
- package/src/cli.ts +3 -3
- package/src/compat/model-specs.ts +4 -0
- package/src/compat.ts +34 -6
- package/src/dashboard-app.ts +1 -0
- package/src/install-agent.ts +252 -143
- package/src/install-opencode.ts +211 -43
- package/src/providers/google-antigravity/catalog.ts +45 -166
- package/src/providers/google-antigravity/dynamic-catalog.ts +107 -10
- package/src/providers/google-antigravity/forward.ts +4 -2
- package/src/providers/google-antigravity/index.ts +12 -4
- package/src/providers/google-antigravity/quota.ts +9 -7
- package/src/providers/ollama/forward.ts +10 -0
- package/src/providers/openai-codex/catalog.ts +157 -18
- package/src/proxy.ts +54 -5
- package/src/rotator.ts +32 -22
- package/src/types.ts +79 -67
- package/src/web/app.tsx +4 -0
- 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 +448 -0
- package/src/web/nav.ts +1 -0
- package/src/web/pages/Playground.tsx +1111 -0
- package/src/web/pages/Transcription.tsx +428 -0
- package/src/web/state/api.ts +3 -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 +45 -0
- package/tools/telemetry-receiver/receiver.js +59 -46
- package/plugins/opencode-discovery.js +0 -174
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## [
|
|
3
|
+
## [4.3.0] - 2026-10-29
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **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))
|
|
8
|
+
- **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.
|
|
9
|
+
- **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.
|
|
10
|
+
- **Transcription**: Audio file upload (`.wav`, `.mp3`, `.m4a`, `.webm`, `.ogg`, `.oga`, `.flac`, `.pcm`) and browser `MediaRecorder` microphone capture with preview, lifecycle cleanup, and transcript export.
|
|
11
|
+
- **Local workspaces**: Browser IndexedDB persistence with versioned JSON export/import and privacy-mask redaction; raw audio stays in-tab only.
|
|
12
|
+
- **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))
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **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`.
|
|
17
|
+
- **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))
|
|
18
|
+
- **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))
|
|
19
|
+
- **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.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- **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))
|
|
24
|
+
- **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))
|
|
25
|
+
- **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))
|
|
26
|
+
|
|
27
|
+
### Contributors
|
|
28
|
+
|
|
29
|
+
- 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).
|
|
30
|
+
|
|
31
|
+
## [4.2.2] - 2026-10-24
|
|
32
|
+
|
|
33
|
+
### Security
|
|
34
|
+
|
|
35
|
+
- Require Node.js 22.23.4+ on 22.x, 24.22.1+ on 24.x, or 26.12.1+ to address the bundled Brotli decoder vulnerability [CVE-2026-111497](https://nodejs.org/en/blog/vulnerability/october-2026-security-releases). Pin Docker and CI to Node.js 22.23.4 and document runtime upgrades and service restarts. Updating npm dependencies alone does not patch an existing Node.js process. ([PR #41](https://github.com/tuxevil/tuxevil-rotator/pull/41))
|
|
36
|
+
- Update the direct Undici dependency to 7.30.1 for its upstream security fixes.
|
|
37
|
+
- Replace the OpenCode discovery plugin's quadratic trailing-slash regular expression with a linear scan. Long slash sequences in configured base URLs can no longer block plugin startup through regular-expression backtracking (CodeQL alert #53). Add regression coverage for large matching and nonmatching inputs and URL normalization behavior.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
|
|
41
|
+
- Discover Antigravity models from live account quota snapshots instead of advertising retired static model IDs. Preserve valid snapshots on malformed quota-only responses and keep request reservations scoped to the provider when model IDs overlap.
|
|
42
|
+
- Update the OpenCode discovery plugin and installers to the OpenCode 2 plugin API and configuration format.
|
|
43
|
+
|
|
44
|
+
### Documentation
|
|
45
|
+
|
|
46
|
+
- Add English and Spanish agent installation prompts covering account logins, background services and agent configuration, and surface them in the README and repository agent instructions.
|
|
47
|
+
|
|
48
|
+
### Contributors
|
|
49
|
+
|
|
50
|
+
- Thanks to [@CyR1en](https://github.com/CyR1en) for the Node.js and Undici security updates and deployment guidance in [PR #41](https://github.com/tuxevil/tuxevil-rotator/pull/41).
|
|
4
51
|
|
|
5
52
|
## [4.2.1] - 2026-10-17
|
|
6
53
|
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/tuxevil-rotator)
|
|
4
|
-
[](package.json)
|
|
5
5
|
[](LICENSE)
|
|
6
6
|
[](https://github.com/tuxevil/tuxevil-rotator/actions)
|
|
7
7
|
[](https://www.typescriptlang.org)
|
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
|
|
25
25
|
**Production-ready OpenAI-compatible gateway for multiple free-tier LLM providers.**
|
|
26
26
|
|
|
27
|
+
> **Not a developer? No manual steps needed.** Ask your AI agent (OpenCode, Codex, Claude Code, Cursor, Cline…) to: *"Install tuxevil-rotator following docs/agent-install-prompt.md"* — that file contains a ready-made copy-paste prompt (English and Spanish) that walks your agent through the whole installation, account logins, background service, and wiring your agent to it.
|
|
28
|
+
|
|
27
29
|
> **Container migration notice:** `ghcr.io/tuxevil/pi-antigravity-rotator` is deprecated. Use [`ghcr.io/tuxevil/tuxevil-rotator:latest`](https://github.com/tuxevil/tuxevil-rotator/pkgs/container/tuxevil-rotator) for new deployments. The legacy image remains available as a frozen compatibility reference; see the [migration guide](docs/migrating-from-pi-antigravity-rotator.md).
|
|
28
30
|
|
|
29
31
|
Multi-account load balancing, per-model quota routing, account health scoring, access control with Virtual Keys, and cost auditing — via a single local endpoint that any agent can use. Even with a single account.
|
|
@@ -53,6 +55,10 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
53
55
|
|
|
54
56
|
## Current Model Update
|
|
55
57
|
|
|
58
|
+
- **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 and JSON export/import. `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))
|
|
59
|
+
|
|
60
|
+
- **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
|
+
|
|
56
62
|
- **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))
|
|
57
63
|
|
|
58
64
|
- **v4.1.0: Models and provider controls**: Manage provider order, provider and per-account switches, individual model availability, and review of newly discovered models at `/dashboard/models`. Controls apply to aliases, automatic routing, native requests, audio, benchmarks, and warm-up. Includes Ollama credit-balance polling and clearer Codex reauthentication status. ([Release notes](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v4.1.0); [PR #39](https://github.com/tuxevil/tuxevil-rotator/pull/39) by [@CyR1en](https://github.com/CyR1en))
|
|
@@ -69,7 +75,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
69
75
|
- **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))
|
|
70
76
|
- **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))
|
|
71
77
|
- **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))
|
|
72
|
-
- **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.
|
|
78
|
+
- **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))
|
|
73
79
|
- **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))
|
|
74
80
|
- **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))
|
|
75
81
|
- **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))
|
|
@@ -171,7 +177,9 @@ Existing `enc:v1` records remain decryptable during migration; newly written rec
|
|
|
171
177
|
|
|
172
178
|
## Quick Start
|
|
173
179
|
|
|
174
|
-
**Requirements:** Node.js 22+ for npm/source installs. Docker image uses Node 22.
|
|
180
|
+
**Requirements:** Node.js 22.23.4+ on 22.x, 24.22.1+ on 24.x, or 26.12.1+ for npm/source installs. The Docker image uses Node 22.23.4. These releases fix the [Brotli decoder vulnerability, CVE-2026-111497](https://nodejs.org/en/blog/vulnerability/october-2026-security-releases). Restart the rotator after upgrading Node.js.
|
|
181
|
+
|
|
182
|
+
> **Non-technical? Don't follow the steps — paste a prompt instead.** Copy the ready-made install prompt from [`docs/agent-install-prompt.md`](docs/agent-install-prompt.md) (English and Spanish versions) into your AI agent — OpenCode, Codex, Claude Code, Cursor, Cline… — and it installs the rotator, walks you through the account logins, runs it as a background service, and wires your agent to it automatically.
|
|
175
183
|
|
|
176
184
|
### Option A: npm
|
|
177
185
|
|
|
@@ -230,9 +238,13 @@ You can configure supported local agents automatically with:
|
|
|
230
238
|
|
|
231
239
|
```bash
|
|
232
240
|
tuxevil-rotator install-agent --target auto
|
|
241
|
+
# Select agents explicitly (includes model reasoning capabilities):
|
|
242
|
+
tuxevil-rotator install-agent --target opencode,hermes,openclaw
|
|
233
243
|
```
|
|
234
244
|
|
|
235
|
-
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).
|
|
245
|
+
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).
|
|
246
|
+
|
|
247
|
+
> **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.
|
|
236
248
|
|
|
237
249
|
| Agent | Guide |
|
|
238
250
|
|-------|-------|
|
|
@@ -291,6 +303,7 @@ After starting the proxy, open `http://localhost:51200/dashboard` and sign in wi
|
|
|
291
303
|
- **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
|
|
292
304
|
- **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)
|
|
293
305
|
- **Models** — provider order, provider and per-account switches, individual model switches, quota and health summaries, and optional review of newly discovered models
|
|
306
|
+
- **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
|
|
294
307
|
- **Requests** — a live tail of requests and rotator events, and with PostgreSQL the full history with payloads and per-key totals
|
|
295
308
|
- **Usage** — token volume by model with 1h–30d ranges, estimated savings at list prices, latency percentiles and a 60-day activity heatmap
|
|
296
309
|
- **Virtual keys** and **Settings** — key management, routing controls and policy, a benchmark, and the raw configuration file
|
|
@@ -333,6 +346,7 @@ tuxevil-rotator keys generate --alias "cursor-agent" --models "gemini-3.6-flash-
|
|
|
333
346
|
| Migration from pi-antigravity-rotator | [docs/migrating-from-pi-antigravity-rotator.md](docs/migrating-from-pi-antigravity-rotator.md) |
|
|
334
347
|
| Troubleshooting | [docs/troubleshooting.md](docs/troubleshooting.md) |
|
|
335
348
|
| Telemetry | [docs/telemetry.md](docs/telemetry.md) |
|
|
349
|
+
| One-Prompt Agent Install | [docs/agent-install-prompt.md](docs/agent-install-prompt.md) |
|
|
336
350
|
| PostgreSQL Setup | [docs/integrations/setup-postgresql.md](docs/integrations/setup-postgresql.md) |
|
|
337
351
|
|
|
338
352
|
---
|
|
@@ -379,11 +393,11 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
379
393
|
|
|
380
394
|
- **[@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))
|
|
381
395
|
- **[@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))
|
|
382
|
-
- **[@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,
|
|
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))
|
|
383
397
|
- **[@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))
|
|
384
398
|
- **[@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))
|
|
385
399
|
- **[@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))
|
|
386
|
-
- **[@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))
|
|
400
|
+
- **[@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))
|
|
387
401
|
|
|
388
402
|
## Development
|
|
389
403
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuxevil-rotator",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.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",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"pi-antigravity-rotator": "bin/pi-antigravity-rotator.js"
|
|
10
10
|
},
|
|
11
11
|
"engines": {
|
|
12
|
-
"node": "
|
|
12
|
+
"node": "^22.23.4 || ^24.22.1 || >=26.12.1"
|
|
13
13
|
},
|
|
14
14
|
"scripts": {
|
|
15
15
|
"start": "tsx src/cli.ts start",
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"pg": "^8.22.0",
|
|
56
56
|
"preact": "^10.29.8",
|
|
57
57
|
"tsx": "^4.22.4",
|
|
58
|
-
"undici": "^7.
|
|
58
|
+
"undici": "^7.30.1"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"@eslint/js": "^10.0.1",
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loose ambient types for plugins/opencode-discovery/index.mjs, so the repo's
|
|
3
|
+
* TS tests can import the untyped module without pull-in of @opencode/plugin.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface ProviderEntry {
|
|
7
|
+
id?: string;
|
|
8
|
+
providerID?: string;
|
|
9
|
+
name?: string | null;
|
|
10
|
+
baseURL?: string | null;
|
|
11
|
+
info?: {
|
|
12
|
+
id?: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
settings?: { baseURL?: string };
|
|
15
|
+
};
|
|
16
|
+
provider?: {
|
|
17
|
+
id?: string;
|
|
18
|
+
name?: string;
|
|
19
|
+
settings?: { baseURL?: string };
|
|
20
|
+
};
|
|
21
|
+
settings?: { baseURL?: string };
|
|
22
|
+
options?: { baseURL?: string };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ResolvedOptions {
|
|
26
|
+
baseURL: string;
|
|
27
|
+
providerID: string;
|
|
28
|
+
providerName: string;
|
|
29
|
+
timeoutMs: number;
|
|
30
|
+
refreshMs: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface RawRotatorModel {
|
|
34
|
+
id: string;
|
|
35
|
+
meta?: Record<string, unknown>;
|
|
36
|
+
info?: Record<string, unknown>;
|
|
37
|
+
context_window?: number;
|
|
38
|
+
max_model_len?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ModelDef {
|
|
42
|
+
name: string;
|
|
43
|
+
limit: { context: number; output: number };
|
|
44
|
+
capabilities: { tools: boolean; input: string[]; output: string[]; reasoning?: unknown };
|
|
45
|
+
variants?: Array<{ id: string; settings: { reasoningEffort: string } }>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function normalizeProviderEntries(input: unknown): ProviderEntry[];
|
|
49
|
+
export function resolvePluginOptions(
|
|
50
|
+
options?: Record<string, unknown>,
|
|
51
|
+
providerEntries?: unknown,
|
|
52
|
+
): ResolvedOptions;
|
|
53
|
+
export function fetchRotatorModels(baseURL: string, timeoutMs?: number): Promise<RawRotatorModel[]>;
|
|
54
|
+
export function mapModelToOpenCode(rawModel: RawRotatorModel): { id: string; modelDef: ModelDef };
|
|
55
|
+
|
|
56
|
+
const plugin: {
|
|
57
|
+
id: string;
|
|
58
|
+
setup(ctx: unknown): Promise<(() => void) | undefined>;
|
|
59
|
+
};
|
|
60
|
+
export default plugin;
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode V2 Model Discovery Plugin for tuxevil-rotator
|
|
3
|
+
*
|
|
4
|
+
* Fetches the active model list from a tuxevil-rotator (or any OpenAI-compatible)
|
|
5
|
+
* /v1/models endpoint and registers / refreshes the provider through the OpenCode 2
|
|
6
|
+
* plugin API (`ctx.provider.transform`).
|
|
7
|
+
*
|
|
8
|
+
* Replaces the V1 `plugins/opencode-discovery.js`, whose function-style default
|
|
9
|
+
* export OpenCode 2.x refuses to load ("Plugin must export a default definition
|
|
10
|
+
* with an id and an effect or setup function").
|
|
11
|
+
*
|
|
12
|
+
* Options (`plugins[].options` in opencode.json):
|
|
13
|
+
* - baseURL explicit rotator endpoint (else env, else config scan, else default)
|
|
14
|
+
* - providerID target provider id (default "antigravity")
|
|
15
|
+
* - providerName display name (default "Antigravity (rotator)")
|
|
16
|
+
* - timeoutMs fetch timeout (default 3500)
|
|
17
|
+
* - refreshMs background re-discovery interval (default 600000; 0 disables)
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { openCodeReasoning, openCodeVariants } from "./capabilities.mjs"
|
|
21
|
+
|
|
22
|
+
const PLUGIN_ID = "tuxevil.model-discovery"
|
|
23
|
+
const DEFAULT_BASE_URL = "http://127.0.0.1:51200/v1"
|
|
24
|
+
const DEFAULT_PROVIDER_PACKAGE = "@opencode/ai/providers/openai-compatible"
|
|
25
|
+
|
|
26
|
+
// The host provides `@opencode/plugin` at runtime and redirects the import to its
|
|
27
|
+
// own instance; outside OpenCode (unit tests) the import simply fails and the
|
|
28
|
+
// guarded helpers below fall back to plain objects.
|
|
29
|
+
let SDK = {}
|
|
30
|
+
try {
|
|
31
|
+
SDK = await import("@opencode/plugin")
|
|
32
|
+
} catch {
|
|
33
|
+
SDK = {}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function makeModelID(id) {
|
|
37
|
+
try {
|
|
38
|
+
return SDK?.Model?.ID?.make?.(id) ?? id
|
|
39
|
+
} catch {
|
|
40
|
+
return id
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function makeProviderID(id) {
|
|
45
|
+
try {
|
|
46
|
+
return SDK?.Provider?.ID?.make?.(id) ?? id
|
|
47
|
+
} catch {
|
|
48
|
+
return id
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function modelInfoDefault(providerID, id) {
|
|
53
|
+
try {
|
|
54
|
+
return SDK?.Model?.Info?.default?.(makeProviderID(providerID), makeModelID(id)) ?? {}
|
|
55
|
+
} catch {
|
|
56
|
+
return {}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function providerInfoEmpty(providerID) {
|
|
61
|
+
try {
|
|
62
|
+
return SDK?.Provider?.Info?.empty?.(makeProviderID(providerID)) ?? {}
|
|
63
|
+
} catch {
|
|
64
|
+
return {}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Normalizes the many shapes a provider collection can take into
|
|
70
|
+
* `{ id, name, baseURL }` records.
|
|
71
|
+
*
|
|
72
|
+
* Accepted inputs:
|
|
73
|
+
* - V2 `ctx.provider.list()` output (array or `{ providers }`)
|
|
74
|
+
* - V2 provider records (`{ info: { name, settings: { baseURL } } }`)
|
|
75
|
+
* - V1 `config.provider` maps (`{ [id]: { name, options: { baseURL } } }`)
|
|
76
|
+
*/
|
|
77
|
+
export function normalizeProviderEntries(input) {
|
|
78
|
+
let list
|
|
79
|
+
if (Array.isArray(input)) {
|
|
80
|
+
list = input
|
|
81
|
+
} else if (input && typeof input === "object" && Array.isArray(input.providers)) {
|
|
82
|
+
list = input.providers
|
|
83
|
+
} else if (input && typeof input === "object") {
|
|
84
|
+
list = Object.entries(input).map(([id, value]) => ({ id, ...value }))
|
|
85
|
+
} else {
|
|
86
|
+
list = []
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return list
|
|
90
|
+
.map((entry) => {
|
|
91
|
+
const id =
|
|
92
|
+
entry?.id ?? entry?.providerID ?? entry?.info?.id ?? entry?.provider?.id ?? (typeof entry === "string" ? entry : undefined)
|
|
93
|
+
if (!id) return null
|
|
94
|
+
const baseURL =
|
|
95
|
+
entry?.info?.settings?.baseURL ??
|
|
96
|
+
entry?.settings?.baseURL ??
|
|
97
|
+
entry?.provider?.settings?.baseURL ??
|
|
98
|
+
entry?.options?.baseURL ??
|
|
99
|
+
entry?.baseURL ??
|
|
100
|
+
null
|
|
101
|
+
const name =
|
|
102
|
+
entry?.info?.name ?? entry?.provider?.name ?? entry?.name ?? null
|
|
103
|
+
return { id, name, baseURL }
|
|
104
|
+
})
|
|
105
|
+
.filter(Boolean)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Resolves the options for this plugin run.
|
|
110
|
+
* Precedence (same as the V1 plugin):
|
|
111
|
+
* 1. explicit plugin options
|
|
112
|
+
* 2. environment variables (TUXEVIL_ROTATOR_BASE_URL, ROTATOR_URL)
|
|
113
|
+
* 3. discovered provider whose baseURL mentions 51200 / rotator / antigravity
|
|
114
|
+
* 4. default http://127.0.0.1:51200/v1
|
|
115
|
+
*/
|
|
116
|
+
export function resolvePluginOptions(options = {}, providerEntries = []) {
|
|
117
|
+
const entries = normalizeProviderEntries(providerEntries)
|
|
118
|
+
const envBaseURL = process.env.TUXEVIL_ROTATOR_BASE_URL || process.env.ROTATOR_URL
|
|
119
|
+
|
|
120
|
+
let baseURL = options.baseURL || envBaseURL || null
|
|
121
|
+
let providerID = options.providerID || null
|
|
122
|
+
let providerName = options.providerName || null
|
|
123
|
+
|
|
124
|
+
if (!baseURL) {
|
|
125
|
+
const found = entries.find((entry) => {
|
|
126
|
+
const url = entry.baseURL
|
|
127
|
+
return typeof url === "string" && (url.includes("51200") || url.includes("rotator") || url.includes("antigravity"))
|
|
128
|
+
})
|
|
129
|
+
if (found) {
|
|
130
|
+
baseURL = found.baseURL ?? null
|
|
131
|
+
if (!providerID) providerID = found.id
|
|
132
|
+
if (!providerName) providerName = found.name
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Scan backwards once so a long internal slash run cannot cause ReDoS.
|
|
137
|
+
const baseURLText = String(baseURL ?? DEFAULT_BASE_URL)
|
|
138
|
+
let end = baseURLText.length
|
|
139
|
+
while (end > 0 && baseURLText.charCodeAt(end - 1) === 47) end--
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
baseURL: baseURLText.slice(0, end),
|
|
143
|
+
providerID: providerID || "antigravity",
|
|
144
|
+
providerName: providerName || "Antigravity (rotator)",
|
|
145
|
+
timeoutMs: Number(options.timeoutMs) || 3500,
|
|
146
|
+
refreshMs: options.refreshMs === 0 ? 0 : Number(options.refreshMs) || 600_000,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Fetches available models from the target rotator endpoint.
|
|
152
|
+
*/
|
|
153
|
+
export async function fetchRotatorModels(baseURL, timeoutMs = 3500) {
|
|
154
|
+
const modelsUrl = `${baseURL}/models`
|
|
155
|
+
let url
|
|
156
|
+
try {
|
|
157
|
+
url = new URL(modelsUrl)
|
|
158
|
+
} catch {
|
|
159
|
+
throw new Error(`fetch() URL is invalid: "${modelsUrl}" (bad baseURL "${baseURL}")`)
|
|
160
|
+
}
|
|
161
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
162
|
+
throw new Error(`Unsupported URL protocol in "${modelsUrl}"`)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const controller = new AbortController()
|
|
166
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
167
|
+
|
|
168
|
+
try {
|
|
169
|
+
const res = await fetch(url, {
|
|
170
|
+
signal: controller.signal,
|
|
171
|
+
headers: { Accept: "application/json" },
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
if (!res.ok) {
|
|
175
|
+
throw new Error(`Endpoint returned status ${res.status}: ${res.statusText}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const json = await res.json()
|
|
179
|
+
if (!json || !Array.isArray(json.data)) {
|
|
180
|
+
throw new Error('Invalid response format: "data" array not found')
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return json.data
|
|
184
|
+
} finally {
|
|
185
|
+
clearTimeout(timer)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Maps a raw model object from the rotator /v1/models endpoint to an
|
|
191
|
+
* OpenCode model definition core (limit + capabilities).
|
|
192
|
+
*/
|
|
193
|
+
export function mapModelToOpenCode(rawModel) {
|
|
194
|
+
const id = rawModel.id
|
|
195
|
+
const meta = rawModel.meta || rawModel.info || {}
|
|
196
|
+
|
|
197
|
+
const contextLimit =
|
|
198
|
+
Number(meta.context_length) || Number(rawModel.context_window) || Number(rawModel.max_model_len) || 128000
|
|
199
|
+
const outputLimit = Number(meta.max_output_tokens) || 8192
|
|
200
|
+
|
|
201
|
+
const isMultimodal = Boolean(meta.multimodal)
|
|
202
|
+
const toolCalling = meta.tool_calling !== false
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
id,
|
|
206
|
+
modelDef: {
|
|
207
|
+
name: id,
|
|
208
|
+
limit: { context: contextLimit, output: outputLimit },
|
|
209
|
+
capabilities: {
|
|
210
|
+
tools: toolCalling,
|
|
211
|
+
input: isMultimodal ? ["text", "image"] : ["text"],
|
|
212
|
+
output: ["text"],
|
|
213
|
+
...openCodeReasoning(rawModel),
|
|
214
|
+
},
|
|
215
|
+
...(openCodeVariants(rawModel).length ? { variants: openCodeVariants(rawModel) } : {}),
|
|
216
|
+
},
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function toModelMap(models) {
|
|
221
|
+
if (models instanceof Map) return models
|
|
222
|
+
if (models && typeof models === "object") return new Map(Object.entries(models))
|
|
223
|
+
return new Map()
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function safeGet(editor, id) {
|
|
227
|
+
try {
|
|
228
|
+
return editor?.get?.(id)
|
|
229
|
+
} catch {
|
|
230
|
+
return undefined
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function modelSignature(models) {
|
|
235
|
+
return JSON.stringify(
|
|
236
|
+
(models ?? [])
|
|
237
|
+
.map((model) => [model?.id, model?.meta])
|
|
238
|
+
.filter(Boolean)
|
|
239
|
+
.sort(),
|
|
240
|
+
)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function mergeProviderInfo(existingProvider, resolved) {
|
|
244
|
+
const prior = existingProvider ?? {}
|
|
245
|
+
return {
|
|
246
|
+
...providerInfoEmpty(resolved.providerID),
|
|
247
|
+
...prior,
|
|
248
|
+
name: prior.name || resolved.providerName,
|
|
249
|
+
activation: prior.activation || "enabled",
|
|
250
|
+
package: prior.package || DEFAULT_PROVIDER_PACKAGE,
|
|
251
|
+
settings: { ...(prior.settings ?? {}), baseURL: resolved.baseURL },
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* OpenCode V2 Plugin Entrypoint (plain-object definition, same pattern the
|
|
257
|
+
* official @openviking/opencode-plugin uses).
|
|
258
|
+
*/
|
|
259
|
+
export default {
|
|
260
|
+
id: PLUGIN_ID,
|
|
261
|
+
async setup(ctx) {
|
|
262
|
+
const options = (ctx && ctx.options) || {}
|
|
263
|
+
let entries
|
|
264
|
+
try {
|
|
265
|
+
entries = normalizeProviderEntries(await ctx?.provider?.list?.())
|
|
266
|
+
} catch {
|
|
267
|
+
entries = []
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const resolved = resolvePluginOptions(options, entries)
|
|
271
|
+
const source = { models: null }
|
|
272
|
+
let lastSignature = null
|
|
273
|
+
|
|
274
|
+
async function load() {
|
|
275
|
+
try {
|
|
276
|
+
const models = await fetchRotatorModels(resolved.baseURL, resolved.timeoutMs)
|
|
277
|
+
const list = Array.isArray(models) ? models : []
|
|
278
|
+
const changed = lastSignature !== null && modelSignature(list) !== lastSignature
|
|
279
|
+
source.models = list
|
|
280
|
+
lastSignature = modelSignature(list)
|
|
281
|
+
return { ok: true, changed }
|
|
282
|
+
} catch (err) {
|
|
283
|
+
// Safe degrade: never fail OpenCode startup when the rotator is unreachable
|
|
284
|
+
console.warn(`[opencode-discovery] model discovery skipped: ${err?.message ?? err}`)
|
|
285
|
+
return { ok: false, changed: false }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const first = await load()
|
|
290
|
+
if (!first.ok || !source.models?.length) return undefined
|
|
291
|
+
|
|
292
|
+
const toModelInfo = (raw, existingModel) => {
|
|
293
|
+
const { id, modelDef } = mapModelToOpenCode(raw)
|
|
294
|
+
return {
|
|
295
|
+
...modelInfoDefault(resolved.providerID, id),
|
|
296
|
+
...(existingModel ?? {}),
|
|
297
|
+
id: makeModelID(id),
|
|
298
|
+
name: existingModel?.name || modelDef.name,
|
|
299
|
+
capabilities: { ...modelDef.capabilities, ...(existingModel?.capabilities ?? {}) },
|
|
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()] } : {}),
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
await ctx.provider.transform((editor) => {
|
|
306
|
+
if (!source.models?.length) return
|
|
307
|
+
const existing = safeGet(editor, resolved.providerID)
|
|
308
|
+
const existingModels = toModelMap(existing?.models)
|
|
309
|
+
const models = source.models.flatMap((raw) =>
|
|
310
|
+
raw?.id ? [toModelInfo(raw, existingModels.get(raw.id) ?? null)] : [],
|
|
311
|
+
)
|
|
312
|
+
editor.add({ info: mergeProviderInfo(existing?.provider, resolved), models })
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
if (resolved.refreshMs <= 0) return undefined
|
|
316
|
+
|
|
317
|
+
const timer = setInterval(() => {
|
|
318
|
+
void (async () => {
|
|
319
|
+
const result = await load()
|
|
320
|
+
if (!result.changed) return
|
|
321
|
+
try {
|
|
322
|
+
await ctx.provider.reload()
|
|
323
|
+
} catch {
|
|
324
|
+
// Registry reload unavailable; keep the last known inventory
|
|
325
|
+
}
|
|
326
|
+
})()
|
|
327
|
+
}, resolved.refreshMs)
|
|
328
|
+
if (typeof timer.unref === "function") timer.unref()
|
|
329
|
+
|
|
330
|
+
return () => clearInterval(timer)
|
|
331
|
+
},
|
|
332
|
+
}
|
|
333
|
+
|