tuxevil-rotator 3.7.1 → 3.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +4 -0
- package/package.json +2 -1
- package/src/auto-routing.ts +370 -0
- package/src/compat.ts +419 -51
- package/src/config-defaults.ts +13 -0
- package/src/dashboard.ts +2 -2
- package/src/db-store.ts +9 -3
- package/src/fetch-with-retry.ts +71 -0
- package/src/key-auth.ts +15 -15
- package/src/onboarding.ts +174 -2
- package/src/providers/adapter.ts +1 -0
- package/src/providers/google-antigravity/forward.ts +38 -5
- package/src/providers/google-antigravity/translators.ts +2 -1
- package/src/providers/ollama/forward.ts +5 -2
- package/src/providers/openai-codex/compat.ts +95 -12
- package/src/providers/openai-codex/forward.ts +5 -2
- package/src/providers/opencode-zen/forward.ts +36 -4
- package/src/providers/registry.ts +12 -1
- package/src/proxy.ts +138 -24
- package/src/rate-limit-parser.ts +29 -0
- package/src/response-headers.ts +21 -0
- package/src/rotator.ts +233 -62
- package/src/stream-guards.ts +85 -0
- package/src/token-encryption.ts +91 -0
- package/src/types.ts +23 -0
- package/src/validators.ts +38 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [3.8.0] - 2026-09-20
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Optional TypeSafe Jev model selection**: `model: "auto"` can now semantically select a currently routable model across active providers for OpenAI Chat/Responses, Anthropic Messages, and Gemini compatibility routes. The bounded candidate shortlist, encrypted `/login-cli` configuration, and deterministic fail-open fallback keep the feature opt-in and operationally safe when Jev is unavailable or uncertain.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **Single-account transport retry recovery**: Transient upstream transport failures now retry the current account with cancellable jittered exponential backoff when no replacement account is available, preserving recovery for single-account deployments and exhausted pools across native, compatibility, and Code Assist routes ([#35](https://github.com/tuxevil/tuxevil-rotator/pull/35) by [@toRolex](https://github.com/toRolex)).
|
|
14
|
+
|
|
15
|
+
## [3.7.2] - 2026-09-16
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
|
|
19
|
+
- **Cached token usage propagation**: Google Antigravity cached prompt usage is now preserved as OpenAI `prompt_tokens_details.cached_tokens` and Anthropic `cache_read_input_tokens` across the compatibility layer ([#34](https://github.com/tuxevil/tuxevil-rotator/pull/34) by [@toRolex](https://github.com/toRolex)).
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- **Native Gemini usage reporting**: Native `generateContent` responses now expose `cachedContentTokenCount` when Google reports cached prompt tokens.
|
|
24
|
+
- **OpenCode Zen Responses usage**: Cached input tokens now survive JSON and SSE translation through Chat and Responses compatibility paths, with regression coverage.
|
|
25
|
+
|
|
5
26
|
## [3.7.1] - 2026-09-12
|
|
6
27
|
|
|
7
28
|
### Added
|
package/README.md
CHANGED
|
@@ -53,6 +53,8 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
53
53
|
|
|
54
54
|
## Current Model Update
|
|
55
55
|
|
|
56
|
+
- **Single-Account Transport Retry Recovery**: Transient upstream network failures now retry the current account with cancellable jittered exponential backoff when no alternate account is available, covering native proxy, compatibility, and Code Assist routes. ([PR #35](https://github.com/tuxevil/tuxevil-rotator/pull/35) by [@toRolex](https://github.com/toRolex))
|
|
57
|
+
- **Cached Token Usage Propagation**: Google Antigravity cached prompt usage is preserved as `cachedContentTokenCount` for native Gemini responses and as cache-read details across OpenAI, Anthropic, and OpenCode Zen Responses compatibility routes. ([PR #34](https://github.com/tuxevil/tuxevil-rotator/pull/34) by [@toRolex](https://github.com/toRolex); follow-up compatibility fixes included in [v3.7.2](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.2))
|
|
56
58
|
- **OpenCode Zen catalog sync**: Added `big-pickle` and removed the retired `deepseek-v4-flash-free` and `hy3-free` entries; `muse-spark-1.3-contributor-free` is now routed through the Responses endpoint with full Chat, Responses, and Anthropic surface compatibility. ([v3.7.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.7.1))
|
|
57
59
|
- **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))
|
|
58
60
|
- **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))
|
|
@@ -61,6 +63,7 @@ Originally built as a multi-account rotator for Google Antigravity. It now gener
|
|
|
61
63
|
- **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))
|
|
62
64
|
- **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))
|
|
63
65
|
- **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))
|
|
66
|
+
- **Optional TypeSafe Jev Routing**: `model: "auto"` can semantically select a currently routable model across active providers for OpenAI, Anthropic, and Gemini compatibility routes, with encrypted `/login-cli` configuration and deterministic fail-open fallback. See [TypeSafe Jev model selection](docs/configuration.md#typesafe-jev-model-selection) and [v3.8.0](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.8.0).
|
|
64
67
|
- **OpenAI-Compatible Audio Transcription and Live Streaming**: Added batch transcription and bidirectional WebSocket audio streaming through the local Antigravity observer model, with model aliases, transcript telemetry, CORS/preflight support, low-latency headers, and lifecycle/security coverage. ([PR #33](https://github.com/tuxevil/tuxevil-rotator/pull/33) by [@javargasm](https://github.com/javargasm))
|
|
65
68
|
- **Partial Quota Snapshot Recovery**: Reset-only Google quota entries are treated as exhausted instead of being discarded, and omitted pools remain available from the last known-good snapshot.
|
|
66
69
|
- **Independent Pool Cooldowns**: Shared Claude and Gemini pools reconcile cooldowns independently, so one exhausted pool does not block its sibling and fresh provider reset deadlines are honored. ([v3.6.1](https://github.com/tuxevil/tuxevil-rotator/releases/tag/v3.6.1))
|
|
@@ -358,6 +361,7 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
358
361
|
- **[@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, 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))
|
|
359
362
|
- **[@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))
|
|
360
363
|
- **[@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))
|
|
364
|
+
- **[@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))
|
|
361
365
|
- **[@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. ([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))
|
|
362
366
|
|
|
363
367
|
## Development
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuxevil-rotator",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.8.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",
|
|
@@ -47,6 +47,7 @@
|
|
|
47
47
|
},
|
|
48
48
|
"author": "Sebastián Real (tuxevil)",
|
|
49
49
|
"dependencies": {
|
|
50
|
+
"@typesafe-ai/sdk": "^0.6.0",
|
|
50
51
|
"pg": "^8.22.0",
|
|
51
52
|
"tsx": "^4.22.4",
|
|
52
53
|
"undici": "^7.29.0"
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { choice, TypeSafeClient } from "@typesafe-ai/sdk";
|
|
2
|
+
import type { Config } from "./types.js";
|
|
3
|
+
import { isEncryptedSecret, isRedactedSecret } from "./token-encryption.js";
|
|
4
|
+
import { rotatorEnv } from "./env.js";
|
|
5
|
+
|
|
6
|
+
export type AutoRoutingRoute =
|
|
7
|
+
| "openai-chat"
|
|
8
|
+
| "openai-responses"
|
|
9
|
+
| "anthropic"
|
|
10
|
+
| "gemini";
|
|
11
|
+
|
|
12
|
+
export interface AutoRoutingCatalogEntry {
|
|
13
|
+
providerId: string;
|
|
14
|
+
modelId: string;
|
|
15
|
+
contextWindow: number;
|
|
16
|
+
multimodal: boolean;
|
|
17
|
+
tools: boolean;
|
|
18
|
+
reasoning: boolean;
|
|
19
|
+
/** Whether this catalog entry is valid for the OpenAI Responses wire path. */
|
|
20
|
+
responses?: boolean;
|
|
21
|
+
family?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface AutoRoutingCandidateStatus {
|
|
25
|
+
available: boolean;
|
|
26
|
+
operationalScore: number;
|
|
27
|
+
poolKey?: string;
|
|
28
|
+
reason?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface AutoRoutingCandidate extends AutoRoutingCatalogEntry {
|
|
32
|
+
id: string;
|
|
33
|
+
operationalScore: number;
|
|
34
|
+
poolKey: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AutoRoutingRotator {
|
|
38
|
+
getConfig?: () => Config;
|
|
39
|
+
hasActiveProvider?: (providerId: string) => boolean;
|
|
40
|
+
getAutoRoutingCandidateStatus?: (
|
|
41
|
+
model: string,
|
|
42
|
+
providerId: string,
|
|
43
|
+
) => AutoRoutingCandidateStatus;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface AutoRoutingSelection {
|
|
47
|
+
candidate: AutoRoutingCandidate;
|
|
48
|
+
mode: "typesafe" | "deterministic";
|
|
49
|
+
confidence?: number;
|
|
50
|
+
reason: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface AutoRoutingRequest {
|
|
54
|
+
route: AutoRoutingRoute;
|
|
55
|
+
input: unknown;
|
|
56
|
+
requestedModel?: string;
|
|
57
|
+
maxContextWindow?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface RoutingRequirements {
|
|
61
|
+
hasImages: boolean;
|
|
62
|
+
hasTools: boolean;
|
|
63
|
+
requiresReasoning: boolean;
|
|
64
|
+
estimatedInputChars: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const PROVIDER_ORDER: Record<string, number> = {
|
|
68
|
+
"google-antigravity": 1,
|
|
69
|
+
ollama: 2,
|
|
70
|
+
"opencode-zen": 3,
|
|
71
|
+
"openai-codex": 4,
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const DEFAULT_MAX_CANDIDATES = 32;
|
|
75
|
+
const DEFAULT_SHORTLIST_SIZE = 12;
|
|
76
|
+
const MAX_SHORTLIST_SIZE = 32;
|
|
77
|
+
const DEFAULT_MAX_EXCERPT_CHARS = 12_000;
|
|
78
|
+
const DEFAULT_MIN_CONFIDENCE = 0.45;
|
|
79
|
+
|
|
80
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
81
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
82
|
+
? value as Record<string, unknown>
|
|
83
|
+
: null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function containsKey(value: unknown, keys: Set<string>): boolean {
|
|
87
|
+
if (Array.isArray(value)) return value.some((item) => containsKey(item, keys));
|
|
88
|
+
const record = asRecord(value);
|
|
89
|
+
if (!record) return false;
|
|
90
|
+
for (const [key, child] of Object.entries(record)) {
|
|
91
|
+
if (keys.has(key.toLowerCase())) return true;
|
|
92
|
+
if (containsKey(child, keys)) return true;
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function containsImage(value: unknown): boolean {
|
|
98
|
+
if (typeof value === "string") return value.startsWith("data:image/");
|
|
99
|
+
if (Array.isArray(value)) return value.some(containsImage);
|
|
100
|
+
const record = asRecord(value);
|
|
101
|
+
if (!record) return false;
|
|
102
|
+
for (const [key, child] of Object.entries(record)) {
|
|
103
|
+
const lower = key.toLowerCase();
|
|
104
|
+
if (lower === "image" || lower === "image_url" || lower === "input_image") return true;
|
|
105
|
+
if ((lower === "type" && typeof child === "string" && child.toLowerCase().includes("image")) || containsImage(child)) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function requiresReasoning(value: unknown): boolean {
|
|
113
|
+
const record = asRecord(value);
|
|
114
|
+
if (Array.isArray(value)) return value.some(requiresReasoning);
|
|
115
|
+
if (!record) return false;
|
|
116
|
+
const effort = record.reasoning_effort;
|
|
117
|
+
if (typeof effort === "string" && ["high", "xhigh", "max"].includes(effort.toLowerCase())) return true;
|
|
118
|
+
if (asRecord(record.reasoning)?.effort &&
|
|
119
|
+
["high", "xhigh", "max"].includes(String(asRecord(record.reasoning)?.effort).toLowerCase())) return true;
|
|
120
|
+
if (asRecord(record.thinking)?.type === "enabled") return true;
|
|
121
|
+
return Object.entries(record).some(([key, child]) =>
|
|
122
|
+
key !== "reasoning" && key !== "thinking" && requiresReasoning(child),
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function collectText(value: unknown, output: string[], seen: Set<unknown>, depth = 0): void {
|
|
127
|
+
if (depth > 8 || value === null || value === undefined) return;
|
|
128
|
+
if (typeof value === "string") {
|
|
129
|
+
const trimmed = value.trim();
|
|
130
|
+
if (!trimmed || /^data:(image|audio|video)\//i.test(trimmed) || /^https?:\/\//i.test(trimmed)) return;
|
|
131
|
+
output.push(trimmed);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (typeof value !== "object" || seen.has(value)) return;
|
|
135
|
+
seen.add(value);
|
|
136
|
+
if (Array.isArray(value)) {
|
|
137
|
+
for (const item of value) collectText(item, output, seen, depth + 1);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const record = value as Record<string, unknown>;
|
|
141
|
+
for (const [key, child] of Object.entries(record)) {
|
|
142
|
+
const lower = key.toLowerCase();
|
|
143
|
+
if (["image", "image_url", "audio", "video", "data", "url"].includes(lower)) continue;
|
|
144
|
+
collectText(child, output, seen, depth + 1);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function boundedExcerpt(input: unknown, maxChars: number): string {
|
|
149
|
+
const parts: string[] = [];
|
|
150
|
+
collectText(input, parts, new Set<unknown>());
|
|
151
|
+
const joined = parts.join("\n");
|
|
152
|
+
return joined.length > maxChars ? `${joined.slice(0, maxChars)}\n[truncated]` : joined;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function getRequirements(input: unknown): RoutingRequirements {
|
|
156
|
+
let serializedLength: number;
|
|
157
|
+
try {
|
|
158
|
+
serializedLength = JSON.stringify(input)?.length ?? 0;
|
|
159
|
+
} catch {
|
|
160
|
+
serializedLength = 0;
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
hasImages: containsImage(input),
|
|
164
|
+
hasTools: containsKey(input, new Set(["tools", "functions", "tool_choice"])),
|
|
165
|
+
requiresReasoning: requiresReasoning(input),
|
|
166
|
+
estimatedInputChars: Math.min(serializedLength, 1_000_000),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function deterministicCompare(a: AutoRoutingCandidate, b: AutoRoutingCandidate): number {
|
|
171
|
+
const score = b.operationalScore - a.operationalScore;
|
|
172
|
+
if (Math.abs(score) > 0.0001) return score;
|
|
173
|
+
const provider = (PROVIDER_ORDER[a.providerId] ?? 99) - (PROVIDER_ORDER[b.providerId] ?? 99);
|
|
174
|
+
if (provider !== 0) return provider;
|
|
175
|
+
return a.modelId.localeCompare(b.modelId);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Keep Jev's question small without allowing the best operational provider to
|
|
180
|
+
* crowd every other provider/family out of the semantic decision. Candidates
|
|
181
|
+
* arrive sorted by operational health, so round-robin buckets preserve that
|
|
182
|
+
* ordering inside each provider/family group while still showing Jev variety.
|
|
183
|
+
*/
|
|
184
|
+
function diverseShortlist(
|
|
185
|
+
candidates: AutoRoutingCandidate[],
|
|
186
|
+
limit: number,
|
|
187
|
+
): AutoRoutingCandidate[] {
|
|
188
|
+
if (candidates.length <= limit) return candidates;
|
|
189
|
+
|
|
190
|
+
const buckets = new Map<string, { items: AutoRoutingCandidate[]; index: number }>();
|
|
191
|
+
for (const candidate of candidates) {
|
|
192
|
+
const family = candidate.family?.trim() || candidate.modelId;
|
|
193
|
+
const key = `${candidate.providerId}\u0000${family}`;
|
|
194
|
+
const bucket = buckets.get(key);
|
|
195
|
+
if (bucket) {
|
|
196
|
+
bucket.items.push(candidate);
|
|
197
|
+
} else {
|
|
198
|
+
buckets.set(key, { items: [candidate], index: 0 });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const selected: AutoRoutingCandidate[] = [];
|
|
203
|
+
let progressed = true;
|
|
204
|
+
while (selected.length < limit && progressed) {
|
|
205
|
+
progressed = false;
|
|
206
|
+
for (const bucket of buckets.values()) {
|
|
207
|
+
const candidate = bucket.items[bucket.index];
|
|
208
|
+
if (!candidate) continue;
|
|
209
|
+
bucket.index += 1;
|
|
210
|
+
selected.push(candidate);
|
|
211
|
+
progressed = true;
|
|
212
|
+
if (selected.length >= limit) break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return selected;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function buildAutoRoutingCandidates(
|
|
219
|
+
rotator: AutoRoutingRotator,
|
|
220
|
+
catalog: AutoRoutingCatalogEntry[],
|
|
221
|
+
request: AutoRoutingRequest,
|
|
222
|
+
): { candidates: AutoRoutingCandidate[]; requirements: RoutingRequirements } {
|
|
223
|
+
const requirements = getRequirements(request.input);
|
|
224
|
+
const candidates: AutoRoutingCandidate[] = [];
|
|
225
|
+
for (const entry of catalog) {
|
|
226
|
+
if (request.route === "gemini" && entry.providerId !== "google-antigravity") continue;
|
|
227
|
+
if (request.route === "openai-responses" && entry.responses === false) continue;
|
|
228
|
+
if (request.maxContextWindow !== undefined && entry.contextWindow < request.maxContextWindow) continue;
|
|
229
|
+
if (requirements.hasImages && !entry.multimodal) continue;
|
|
230
|
+
if (requirements.hasTools && !entry.tools) continue;
|
|
231
|
+
if (requirements.requiresReasoning && !entry.reasoning) continue;
|
|
232
|
+
if (rotator.hasActiveProvider && !rotator.hasActiveProvider(entry.providerId)) continue;
|
|
233
|
+
|
|
234
|
+
const status = rotator.getAutoRoutingCandidateStatus?.(entry.modelId, entry.providerId) ?? {
|
|
235
|
+
available: true,
|
|
236
|
+
operationalScore: 0.5,
|
|
237
|
+
};
|
|
238
|
+
if (!status.available) continue;
|
|
239
|
+
candidates.push({
|
|
240
|
+
...entry,
|
|
241
|
+
id: `candidate_${candidates.length}`,
|
|
242
|
+
operationalScore: Math.max(0, Math.min(1, status.operationalScore)),
|
|
243
|
+
poolKey: status.poolKey ?? entry.modelId,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
candidates.sort(deterministicCompare);
|
|
247
|
+
const routingConfig = rotator.getConfig?.().typesafeRouting;
|
|
248
|
+
const maxCandidates = Math.max(
|
|
249
|
+
1,
|
|
250
|
+
Math.min(128, routingConfig?.maxCandidates ?? DEFAULT_MAX_CANDIDATES),
|
|
251
|
+
);
|
|
252
|
+
const shortlistSize = Math.max(
|
|
253
|
+
1,
|
|
254
|
+
Math.min(
|
|
255
|
+
MAX_SHORTLIST_SIZE,
|
|
256
|
+
maxCandidates,
|
|
257
|
+
routingConfig?.shortlistSize ?? DEFAULT_SHORTLIST_SIZE,
|
|
258
|
+
),
|
|
259
|
+
);
|
|
260
|
+
const candidatePool = diverseShortlist(candidates, maxCandidates);
|
|
261
|
+
return {
|
|
262
|
+
candidates: diverseShortlist(candidatePool, shortlistSize),
|
|
263
|
+
requirements,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function deterministicSelection(
|
|
268
|
+
candidates: AutoRoutingCandidate[],
|
|
269
|
+
reason: string,
|
|
270
|
+
): AutoRoutingSelection | null {
|
|
271
|
+
const candidate = candidates[0];
|
|
272
|
+
return candidate ? { candidate, mode: "deterministic", reason } : null;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export async function selectAutoRoutingTarget(
|
|
276
|
+
rotator: AutoRoutingRotator,
|
|
277
|
+
catalog: AutoRoutingCatalogEntry[],
|
|
278
|
+
request: AutoRoutingRequest,
|
|
279
|
+
): Promise<AutoRoutingSelection | null> {
|
|
280
|
+
const config = rotator.getConfig?.().typesafeRouting;
|
|
281
|
+
const excerptLimit = Math.max(256, Math.min(50_000, config?.maxExcerptChars ?? DEFAULT_MAX_EXCERPT_CHARS));
|
|
282
|
+
const { candidates, requirements } = buildAutoRoutingCandidates(rotator, catalog, request);
|
|
283
|
+
if (candidates.length === 0) return null;
|
|
284
|
+
|
|
285
|
+
const deterministic = (reason: string): AutoRoutingSelection | null =>
|
|
286
|
+
deterministicSelection(candidates, reason);
|
|
287
|
+
const environmentApiKey = rotatorEnv("TYPESAFE_API_KEY") || process.env.TYPESAFE_API_KEY;
|
|
288
|
+
const apiKey = config?.apiKey?.trim() || environmentApiKey?.trim();
|
|
289
|
+
if (config?.enabled === false || !apiKey || isEncryptedSecret(apiKey) || isRedactedSecret(apiKey)) {
|
|
290
|
+
return deterministic("typesafe-disabled");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const criteria: Record<string, string | null> = {};
|
|
294
|
+
for (const candidate of candidates) {
|
|
295
|
+
criteria[candidate.id] = `${candidate.providerId}/${candidate.modelId}; family=${candidate.family ?? "unknown"}; context=${candidate.contextWindow}; multimodal=${candidate.multimodal}; tools=${candidate.tools}; reasoning=${candidate.reasoning}; operational_score=${candidate.operationalScore.toFixed(2)}`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const state = {
|
|
299
|
+
route: request.route,
|
|
300
|
+
requested_model: request.requestedModel ?? "auto",
|
|
301
|
+
selection_policy: "Choose exactly one listed candidate. Hard capability requirements have already been filtered; use operational_score as a tie-breaker.",
|
|
302
|
+
requirements: {
|
|
303
|
+
has_images: requirements.hasImages,
|
|
304
|
+
has_tools: requirements.hasTools,
|
|
305
|
+
requires_reasoning: requirements.requiresReasoning,
|
|
306
|
+
estimated_input_chars: requirements.estimatedInputChars,
|
|
307
|
+
},
|
|
308
|
+
prompt_excerpt: boundedExcerpt(request.input, excerptLimit),
|
|
309
|
+
candidates: candidates.map((candidate) => ({
|
|
310
|
+
id: candidate.id,
|
|
311
|
+
provider: candidate.providerId,
|
|
312
|
+
model: candidate.modelId,
|
|
313
|
+
family: candidate.family ?? null,
|
|
314
|
+
context_window: candidate.contextWindow,
|
|
315
|
+
multimodal: candidate.multimodal,
|
|
316
|
+
tools: candidate.tools,
|
|
317
|
+
reasoning: candidate.reasoning,
|
|
318
|
+
operational_score: candidate.operationalScore,
|
|
319
|
+
})),
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
try {
|
|
323
|
+
const client = new TypeSafeClient({
|
|
324
|
+
apiKey,
|
|
325
|
+
baseURL: config?.baseURL,
|
|
326
|
+
defaultModel: config?.model ?? "jev-latest",
|
|
327
|
+
timeout: config?.timeoutMs ?? 3_000,
|
|
328
|
+
retry: { maxRetries: 0 },
|
|
329
|
+
logLevel: "off",
|
|
330
|
+
});
|
|
331
|
+
const answer = await client.systemOne({
|
|
332
|
+
state,
|
|
333
|
+
questions: {
|
|
334
|
+
selected_model: choice(
|
|
335
|
+
"Choose exactly one of the listed candidates for this request. Prefer the candidate that best fits the request; use operational score as a tie-breaker.",
|
|
336
|
+
criteria,
|
|
337
|
+
),
|
|
338
|
+
},
|
|
339
|
+
});
|
|
340
|
+
const selected = asRecord(answer.answers.selected_model);
|
|
341
|
+
const selectedId = typeof selected?.choice === "string" ? selected.choice : String(selected?.choice ?? "");
|
|
342
|
+
const confidence = Number(selected?.confidence);
|
|
343
|
+
const minConfidence = Math.max(0, Math.min(1, config?.minConfidence ?? DEFAULT_MIN_CONFIDENCE));
|
|
344
|
+
if (selectedId === "none") return deterministic("typesafe-no-match");
|
|
345
|
+
if (!candidates.some((candidate) => candidate.id === selectedId)) {
|
|
346
|
+
return deterministic("typesafe-invalid-choice");
|
|
347
|
+
}
|
|
348
|
+
if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1 || confidence < minConfidence) {
|
|
349
|
+
return deterministic("typesafe-low-confidence");
|
|
350
|
+
}
|
|
351
|
+
const probabilities = asRecord(selected?.probabilities) ?? {};
|
|
352
|
+
const probabilityFor = (candidate: AutoRoutingCandidate): number => {
|
|
353
|
+
const probability = Number(probabilities[candidate.id]);
|
|
354
|
+
return Number.isFinite(probability) && probability >= 0 && probability <= 1 ? probability : 0;
|
|
355
|
+
};
|
|
356
|
+
const ranked = [...candidates].sort((a, b) => {
|
|
357
|
+
const aScore = 0.7 * probabilityFor(a) + 0.3 * a.operationalScore;
|
|
358
|
+
const bScore = 0.7 * probabilityFor(b) + 0.3 * b.operationalScore;
|
|
359
|
+
return bScore - aScore || deterministicCompare(a, b);
|
|
360
|
+
});
|
|
361
|
+
const chosen = ranked[0];
|
|
362
|
+
return chosen
|
|
363
|
+
? { candidate: chosen, mode: "typesafe", confidence, reason: "typesafe-selected" }
|
|
364
|
+
: deterministic("typesafe-invalid-choice");
|
|
365
|
+
} catch {
|
|
366
|
+
// Jev is an optional semantic layer. A transport, timeout, or malformed
|
|
367
|
+
// answer must never make an otherwise routable request fail closed.
|
|
368
|
+
return deterministic("typesafe-error");
|
|
369
|
+
}
|
|
370
|
+
}
|