tuxevil-rotator 3.7.2 → 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 +10 -0
- package/README.md +3 -1
- package/package.json +2 -1
- package/src/auto-routing.ts +370 -0
- package/src/compat.ts +292 -44
- package/src/config-defaults.ts +13 -0
- package/src/dashboard.ts +2 -2
- package/src/db-store.ts +9 -3
- package/src/key-auth.ts +15 -15
- package/src/onboarding.ts +174 -2
- package/src/providers/google-antigravity/forward.ts +8 -1
- package/src/providers/openai-codex/compat.ts +33 -5
- package/src/providers/registry.ts +12 -1
- package/src/proxy.ts +98 -19
- package/src/response-headers.ts +21 -0
- package/src/rotator.ts +108 -33
- package/src/token-encryption.ts +91 -0
- package/src/types.ts +23 -0
- package/src/validators.ts +38 -0
package/src/response-headers.ts
CHANGED
|
@@ -28,6 +28,11 @@ export interface CompressionHeaderOptions {
|
|
|
28
28
|
export interface RotatorResponseHeaderOptions {
|
|
29
29
|
accountLabel?: string;
|
|
30
30
|
model?: string;
|
|
31
|
+
requestedModel?: string;
|
|
32
|
+
selectedProvider?: string;
|
|
33
|
+
modelSelection?: "typesafe" | "deterministic" | "disabled";
|
|
34
|
+
selectionConfidence?: number;
|
|
35
|
+
selectionReason?: string;
|
|
31
36
|
latencyMs?: number;
|
|
32
37
|
ttfbMs?: number;
|
|
33
38
|
inputTokens?: number;
|
|
@@ -61,6 +66,22 @@ export function buildRotatorResponseHeaders(
|
|
|
61
66
|
if (opts.model) {
|
|
62
67
|
headers["X-Rotator-Model"] = opts.model;
|
|
63
68
|
}
|
|
69
|
+
if (opts.requestedModel && opts.requestedModel !== opts.model) {
|
|
70
|
+
headers["X-Rotator-Requested-Model"] = opts.requestedModel;
|
|
71
|
+
}
|
|
72
|
+
if (opts.selectedProvider) {
|
|
73
|
+
headers["X-Rotator-Selected-Provider"] = opts.selectedProvider;
|
|
74
|
+
}
|
|
75
|
+
if (opts.modelSelection) {
|
|
76
|
+
headers["X-Rotator-Model-Selection"] = opts.modelSelection;
|
|
77
|
+
}
|
|
78
|
+
if (opts.selectionConfidence !== undefined && Number.isFinite(opts.selectionConfidence)) {
|
|
79
|
+
headers["X-Rotator-Selection-Confidence"] = opts.selectionConfidence.toFixed(3);
|
|
80
|
+
}
|
|
81
|
+
if (opts.selectionReason) {
|
|
82
|
+
const reason = opts.selectionReason.replace(/[^a-zA-Z0-9._-]/g, "").slice(0, 64);
|
|
83
|
+
if (reason) headers["X-Rotator-Selection-Reason"] = reason;
|
|
84
|
+
}
|
|
64
85
|
if (opts.latencyMs !== undefined && opts.latencyMs >= 0) {
|
|
65
86
|
headers["X-Rotator-Latency-Ms"] = String(Math.round(opts.latencyMs));
|
|
66
87
|
}
|
package/src/rotator.ts
CHANGED
|
@@ -84,6 +84,7 @@ import {
|
|
|
84
84
|
getCachedTokenUsage,
|
|
85
85
|
setCachedTokenUsage,
|
|
86
86
|
} from "./db-store.js";
|
|
87
|
+
import { isRedactedSecret, redactTypeSafeRoutingInConfig } from "./token-encryption.js";
|
|
87
88
|
import {
|
|
88
89
|
classifyRateLimitReason,
|
|
89
90
|
parseRetryAfterMs,
|
|
@@ -186,6 +187,7 @@ const MAX_NODE_TIMEOUT_MS = 2_147_483_647;
|
|
|
186
187
|
interface AccountRequestWaiter {
|
|
187
188
|
queueKey: string;
|
|
188
189
|
model?: string;
|
|
190
|
+
providerId?: string;
|
|
189
191
|
signal?: AbortSignal;
|
|
190
192
|
timer: ReturnType<typeof setTimeout>;
|
|
191
193
|
onAbort?: () => void;
|
|
@@ -260,6 +262,50 @@ export class AccountRotator {
|
|
|
260
262
|
);
|
|
261
263
|
}
|
|
262
264
|
|
|
265
|
+
/**
|
|
266
|
+
* Exposes only aggregate routing health to the optional Jev selector.
|
|
267
|
+
* Account identities and credentials stay inside the rotator.
|
|
268
|
+
*/
|
|
269
|
+
getAutoRoutingCandidateStatus(
|
|
270
|
+
model: string,
|
|
271
|
+
providerId: string,
|
|
272
|
+
): {
|
|
273
|
+
available: boolean;
|
|
274
|
+
operationalScore: number;
|
|
275
|
+
poolKey: string;
|
|
276
|
+
reason?: string;
|
|
277
|
+
} {
|
|
278
|
+
const poolKey = this.resolvePoolKeyForModel(model, providerId);
|
|
279
|
+
if (!poolKey) {
|
|
280
|
+
return { available: false, operationalScore: 0, poolKey: model, reason: "unknown-provider" };
|
|
281
|
+
}
|
|
282
|
+
const now = Date.now();
|
|
283
|
+
const policy = this.config.routingPolicy || "timer-first";
|
|
284
|
+
let bestScore = 0;
|
|
285
|
+
let available = false;
|
|
286
|
+
let firstReason: string | undefined;
|
|
287
|
+
for (const account of this.accounts) {
|
|
288
|
+
const rejection = this.getRoutingRejectionForModel(account, poolKey, now, policy);
|
|
289
|
+
if (rejection) {
|
|
290
|
+
firstReason ??= rejection.detail;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
available = true;
|
|
294
|
+
const quota = this.getModelQuota(account, poolKey);
|
|
295
|
+
const quotaScore = quota < 0 ? 0.5 : Math.max(0, Math.min(1, quota / 100));
|
|
296
|
+
const capacity = Math.max(1, this.config.maxConcurrentRequestsPerAccount ?? 5);
|
|
297
|
+
const loadScore = Math.max(0, Math.min(1, 1 - account.inFlightRequests / capacity));
|
|
298
|
+
const healthScore = this.getHealthScoreBreakdown(account).score;
|
|
299
|
+
bestScore = Math.max(bestScore, 0.55 * healthScore + 0.3 * quotaScore + 0.15 * loadScore);
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
available,
|
|
303
|
+
operationalScore: bestScore,
|
|
304
|
+
poolKey,
|
|
305
|
+
...(available ? {} : { reason: firstReason ?? "no-routable-account" }),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
263
309
|
setCodexModels(models: string[]): void {
|
|
264
310
|
this.codexModels = new Set(
|
|
265
311
|
models
|
|
@@ -1867,25 +1913,26 @@ export class AccountRotator {
|
|
|
1867
1913
|
async getActiveAccount(
|
|
1868
1914
|
model?: string,
|
|
1869
1915
|
signal?: AbortSignal,
|
|
1916
|
+
providerId?: string,
|
|
1870
1917
|
): Promise<AccountRuntime | null> {
|
|
1871
1918
|
if (signal?.aborted) return null;
|
|
1872
|
-
const queueKey = this.getRequestQueueKey(model);
|
|
1919
|
+
const queueKey = this.getRequestQueueKey(model, providerId);
|
|
1873
1920
|
if (
|
|
1874
1921
|
this.hasQueuedRequest(queueKey) ||
|
|
1875
|
-
this.isConcurrencySaturated(model)
|
|
1922
|
+
this.isConcurrencySaturated(model, providerId)
|
|
1876
1923
|
) {
|
|
1877
|
-
return this.enqueueAccountRequest(model, signal, queueKey);
|
|
1924
|
+
return this.enqueueAccountRequest(model, signal, queueKey, providerId);
|
|
1878
1925
|
}
|
|
1879
1926
|
|
|
1880
|
-
const account = await this.tryGetActiveAccount(model);
|
|
1881
|
-
if (account || !this.isConcurrencySaturated(model)) return account;
|
|
1882
|
-
return this.enqueueAccountRequest(model, signal, queueKey);
|
|
1927
|
+
const account = await this.tryGetActiveAccount(model, providerId);
|
|
1928
|
+
if (account || !this.isConcurrencySaturated(model, providerId)) return account;
|
|
1929
|
+
return this.enqueueAccountRequest(model, signal, queueKey, providerId);
|
|
1883
1930
|
}
|
|
1884
1931
|
|
|
1885
1932
|
/** Keep fairness within a provider pool without making unrelated providers wait. */
|
|
1886
|
-
private getRequestQueueKey(model?: string): string {
|
|
1933
|
+
private getRequestQueueKey(model?: string, providerId?: string): string {
|
|
1887
1934
|
if (!model) return DEFAULT_PROVIDER;
|
|
1888
|
-
return getProviderIdForPoolKey(this.resolveRequestPoolKey(model));
|
|
1935
|
+
return providerId ?? getProviderIdForPoolKey(this.resolveRequestPoolKey(model, providerId));
|
|
1889
1936
|
}
|
|
1890
1937
|
|
|
1891
1938
|
private hasQueuedRequest(queueKey: string): boolean {
|
|
@@ -1896,6 +1943,7 @@ export class AccountRotator {
|
|
|
1896
1943
|
model?: string,
|
|
1897
1944
|
signal?: AbortSignal,
|
|
1898
1945
|
queueKey = this.getRequestQueueKey(model),
|
|
1946
|
+
providerId?: string,
|
|
1899
1947
|
): Promise<AccountRuntime | null> {
|
|
1900
1948
|
if (signal?.aborted) return Promise.resolve(null);
|
|
1901
1949
|
|
|
@@ -1903,6 +1951,7 @@ export class AccountRotator {
|
|
|
1903
1951
|
const waiter = {} as AccountRequestWaiter;
|
|
1904
1952
|
waiter.queueKey = queueKey;
|
|
1905
1953
|
waiter.model = model;
|
|
1954
|
+
waiter.providerId = providerId;
|
|
1906
1955
|
waiter.signal = signal;
|
|
1907
1956
|
waiter.resolve = resolve;
|
|
1908
1957
|
waiter.reject = reject;
|
|
@@ -2016,7 +2065,7 @@ export class AccountRotator {
|
|
|
2016
2065
|
|
|
2017
2066
|
let account: AccountRuntime | null;
|
|
2018
2067
|
try {
|
|
2019
|
-
account = await this.tryGetActiveAccount(waiter.model);
|
|
2068
|
+
account = await this.tryGetActiveAccount(waiter.model, waiter.providerId);
|
|
2020
2069
|
} catch (error) {
|
|
2021
2070
|
this.rejectAccountRequestWaiter(waiter, error);
|
|
2022
2071
|
progressed = true;
|
|
@@ -2028,7 +2077,7 @@ export class AccountRotator {
|
|
|
2028
2077
|
this.finishRequest(
|
|
2029
2078
|
account,
|
|
2030
2079
|
waiter.model
|
|
2031
|
-
? this.resolveRequestPoolKey(waiter.model)
|
|
2080
|
+
? this.resolveRequestPoolKey(waiter.model, waiter.providerId)
|
|
2032
2081
|
: undefined,
|
|
2033
2082
|
);
|
|
2034
2083
|
}
|
|
@@ -2044,9 +2093,9 @@ export class AccountRotator {
|
|
|
2044
2093
|
progressed = true;
|
|
2045
2094
|
continue;
|
|
2046
2095
|
}
|
|
2047
|
-
const wakeAt = this.getNextRequestAvailabilityAt(waiter.model);
|
|
2096
|
+
const wakeAt = this.getNextRequestAvailabilityAt(waiter.model, waiter.providerId);
|
|
2048
2097
|
if (wakeAt !== null) this.scheduleRequestWaiterWake(wakeAt);
|
|
2049
|
-
if (!this.isConcurrencySaturated(waiter.model) && wakeAt === null) {
|
|
2098
|
+
if (!this.isConcurrencySaturated(waiter.model, waiter.providerId) && wakeAt === null) {
|
|
2050
2099
|
this.settleAccountRequestWaiter(waiter, null);
|
|
2051
2100
|
progressed = true;
|
|
2052
2101
|
}
|
|
@@ -2058,10 +2107,10 @@ export class AccountRotator {
|
|
|
2058
2107
|
}
|
|
2059
2108
|
}
|
|
2060
2109
|
|
|
2061
|
-
private isConcurrencySaturated(model?: string): boolean {
|
|
2110
|
+
private isConcurrencySaturated(model?: string, providerId?: string): boolean {
|
|
2062
2111
|
const now = Date.now();
|
|
2063
2112
|
if (this.isProtectivePauseActive(now)) return false;
|
|
2064
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2113
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2065
2114
|
if (!modelKey) return false;
|
|
2066
2115
|
const policy = this.config.routingPolicy || "timer-first";
|
|
2067
2116
|
|
|
@@ -2097,12 +2146,12 @@ export class AccountRotator {
|
|
|
2097
2146
|
|
|
2098
2147
|
// Try to reserve an account immediately. The public method queues only
|
|
2099
2148
|
// when every otherwise-eligible account is blocked by concurrency.
|
|
2100
|
-
private async tryGetActiveAccount(model?: string): Promise<AccountRuntime | null> {
|
|
2149
|
+
private async tryGetActiveAccount(model?: string, providerId?: string): Promise<AccountRuntime | null> {
|
|
2101
2150
|
const now = Date.now();
|
|
2102
2151
|
if (this.accounts.length === 0) return null;
|
|
2103
2152
|
if (this.isProtectivePauseActive(now)) return null;
|
|
2104
2153
|
|
|
2105
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2154
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2106
2155
|
const state = modelKey ? this.modelState.get(modelKey) : null;
|
|
2107
2156
|
const idx = state?.activeAccountIndex ?? this.defaultIndex;
|
|
2108
2157
|
const current = this.accounts[idx];
|
|
@@ -2518,9 +2567,10 @@ export class AccountRotator {
|
|
|
2518
2567
|
async rotateToNext(
|
|
2519
2568
|
model?: string,
|
|
2520
2569
|
failedAccount?: AccountRuntime | number | string,
|
|
2570
|
+
providerId?: string,
|
|
2521
2571
|
): Promise<AccountRuntime | null> {
|
|
2522
2572
|
if (this.isProtectivePauseActive(Date.now())) return null;
|
|
2523
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2573
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2524
2574
|
let excludeIdx: number;
|
|
2525
2575
|
if (typeof failedAccount === "number") {
|
|
2526
2576
|
excludeIdx = failedAccount;
|
|
@@ -2543,14 +2593,14 @@ export class AccountRotator {
|
|
|
2543
2593
|
}
|
|
2544
2594
|
|
|
2545
2595
|
// Record a successful request. Returns true if rotation is needed.
|
|
2546
|
-
recordRequest(account: AccountRuntime, model?: string): boolean {
|
|
2596
|
+
recordRequest(account: AccountRuntime, model?: string, providerId?: string): boolean {
|
|
2547
2597
|
account.requestsSinceRotation++;
|
|
2548
2598
|
account.totalRequests++;
|
|
2549
2599
|
account.lastUsed = Date.now();
|
|
2550
2600
|
account.consecutiveErrors = 0;
|
|
2551
2601
|
account.lastError = null;
|
|
2552
2602
|
|
|
2553
|
-
const modelKey = model ? this.resolveRequestPoolKey(model) : null;
|
|
2603
|
+
const modelKey = model ? this.resolveRequestPoolKey(model, providerId) : null;
|
|
2554
2604
|
const state = modelKey ? this.modelState.get(modelKey) : null;
|
|
2555
2605
|
const shouldRotate =
|
|
2556
2606
|
!!modelKey &&
|
|
@@ -3733,8 +3783,8 @@ export class AccountRotator {
|
|
|
3733
3783
|
}
|
|
3734
3784
|
|
|
3735
3785
|
/** Public pool-key resolution for quota routing display/logging. */
|
|
3736
|
-
resolveQuotaModelKeyForDisplay(model: string): string {
|
|
3737
|
-
return this.resolveRequestPoolKey(model);
|
|
3786
|
+
resolveQuotaModelKeyForDisplay(model: string, providerId?: string): string {
|
|
3787
|
+
return this.resolveRequestPoolKey(model, providerId);
|
|
3738
3788
|
}
|
|
3739
3789
|
|
|
3740
3790
|
/** Preserve the exact identity of models learned from the runtime catalog. */
|
|
@@ -3742,11 +3792,11 @@ export class AccountRotator {
|
|
|
3742
3792
|
return dynamicCatalog.getObservedModelId(model) ?? resolveDisplayModelKey(model);
|
|
3743
3793
|
}
|
|
3744
3794
|
|
|
3745
|
-
private resolveRequestPoolKey(model: string): string {
|
|
3746
|
-
return this.resolvePoolKeyForModel(model) ?? "__default__";
|
|
3795
|
+
private resolveRequestPoolKey(model: string, providerId?: string): string {
|
|
3796
|
+
return this.resolvePoolKeyForModel(model, providerId) ?? "__default__";
|
|
3747
3797
|
}
|
|
3748
3798
|
|
|
3749
|
-
private resolvePoolKeyForModel(model: string): string | null {
|
|
3799
|
+
private resolvePoolKeyForModel(model: string, providerId?: string): string | null {
|
|
3750
3800
|
const normalizedModel = model.trim().toLowerCase();
|
|
3751
3801
|
if (
|
|
3752
3802
|
!isStaticAntigravityModel(model) &&
|
|
@@ -3758,6 +3808,7 @@ export class AccountRotator {
|
|
|
3758
3808
|
const context = {
|
|
3759
3809
|
ollamaModels: this.ollamaModels,
|
|
3760
3810
|
codexModels: this.codexModels,
|
|
3811
|
+
providerId,
|
|
3761
3812
|
};
|
|
3762
3813
|
const adapter = findProviderForModel(model, context);
|
|
3763
3814
|
if (adapter?.getPoolKey) {
|
|
@@ -3839,12 +3890,13 @@ export class AccountRotator {
|
|
|
3839
3890
|
private getRequestAvailabilityTimes(
|
|
3840
3891
|
model: string | undefined,
|
|
3841
3892
|
now: number,
|
|
3893
|
+
providerId?: string,
|
|
3842
3894
|
): number[] {
|
|
3843
3895
|
const retryTimes: number[] = [];
|
|
3844
3896
|
if (this.protectivePauseUntil > now)
|
|
3845
3897
|
retryTimes.push(this.protectivePauseUntil);
|
|
3846
3898
|
const modelKey = model
|
|
3847
|
-
? (this.resolvePoolKeyForModel(model) ?? resolveQuotaModelKey(model) ?? "__default__")
|
|
3899
|
+
? (this.resolvePoolKeyForModel(model, providerId) ?? resolveQuotaModelKey(model) ?? "__default__")
|
|
3848
3900
|
: "__default__";
|
|
3849
3901
|
const quotaStateKey = this.resolveQuotaStateKey(modelKey);
|
|
3850
3902
|
const dailyResetAt = nextUtcDayStartMs(now);
|
|
@@ -3852,14 +3904,14 @@ export class AccountRotator {
|
|
|
3852
3904
|
if (modelBreaker > now) retryTimes.push(modelBreaker);
|
|
3853
3905
|
for (const account of this.accounts) {
|
|
3854
3906
|
if (account.disabled || account.flagged) continue;
|
|
3855
|
-
const
|
|
3907
|
+
const candidateProviderId = providerId ?? getProviderIdForPoolKey(modelKey);
|
|
3856
3908
|
if (
|
|
3857
|
-
!hasCredential(account.config,
|
|
3858
|
-
account.invalidProviders?.[
|
|
3909
|
+
!hasCredential(account.config, candidateProviderId) ||
|
|
3910
|
+
account.invalidProviders?.[candidateProviderId]
|
|
3859
3911
|
) {
|
|
3860
3912
|
continue;
|
|
3861
3913
|
}
|
|
3862
|
-
const providerCooldown = account.providerCooldowns?.[
|
|
3914
|
+
const providerCooldown = account.providerCooldowns?.[candidateProviderId] ?? 0;
|
|
3863
3915
|
if (providerCooldown > now) retryTimes.push(providerCooldown);
|
|
3864
3916
|
if (this.isDailySafetyStopped(account, now))
|
|
3865
3917
|
retryTimes.push(dailyResetAt);
|
|
@@ -3888,15 +3940,15 @@ export class AccountRotator {
|
|
|
3888
3940
|
return retryTimes;
|
|
3889
3941
|
}
|
|
3890
3942
|
|
|
3891
|
-
private getNextRequestAvailabilityAt(model?: string): number | null {
|
|
3943
|
+
private getNextRequestAvailabilityAt(model?: string, providerId?: string): number | null {
|
|
3892
3944
|
const now = Date.now();
|
|
3893
|
-
const retryTimes = this.getRequestAvailabilityTimes(model, now);
|
|
3945
|
+
const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId);
|
|
3894
3946
|
return retryTimes.length > 0 ? Math.min(...retryTimes) : null;
|
|
3895
3947
|
}
|
|
3896
3948
|
|
|
3897
|
-
getRetryAfterMs(model?: string): number {
|
|
3949
|
+
getRetryAfterMs(model?: string, providerId?: string): number {
|
|
3898
3950
|
const now = Date.now();
|
|
3899
|
-
const retryTimes = this.getRequestAvailabilityTimes(model, now);
|
|
3951
|
+
const retryTimes = this.getRequestAvailabilityTimes(model, now, providerId);
|
|
3900
3952
|
if (retryTimes.length === 0) return 0;
|
|
3901
3953
|
return Math.max(1000, Math.min(...retryTimes) - now);
|
|
3902
3954
|
}
|
|
@@ -4070,8 +4122,31 @@ export class AccountRotator {
|
|
|
4070
4122
|
return applyConfigDefaults(structuredClone(this.config));
|
|
4071
4123
|
}
|
|
4072
4124
|
|
|
4125
|
+
getPublicConfig(): Config {
|
|
4126
|
+
return redactTypeSafeRoutingInConfig(this.getConfig());
|
|
4127
|
+
}
|
|
4128
|
+
|
|
4073
4129
|
async replaceConfig(nextConfig: Config): Promise<void> {
|
|
4074
4130
|
const normalized = applyConfigDefaults(nextConfig);
|
|
4131
|
+
const incomingTypeSafe = normalized.typesafeRouting;
|
|
4132
|
+
const existingTypeSafe = this.config.typesafeRouting;
|
|
4133
|
+
if (existingTypeSafe && incomingTypeSafe) {
|
|
4134
|
+
const incomingKey = incomingTypeSafe.apiKey;
|
|
4135
|
+
normalized.typesafeRouting = {
|
|
4136
|
+
...existingTypeSafe,
|
|
4137
|
+
...incomingTypeSafe,
|
|
4138
|
+
apiKey:
|
|
4139
|
+
!incomingKey || isRedactedSecret(incomingKey)
|
|
4140
|
+
? existingTypeSafe.apiKey
|
|
4141
|
+
: incomingKey,
|
|
4142
|
+
};
|
|
4143
|
+
} else if (existingTypeSafe && !incomingTypeSafe) {
|
|
4144
|
+
// Public dashboard exports omit the secret; preserve it on unrelated
|
|
4145
|
+
// config edits instead of disabling Jev unexpectedly.
|
|
4146
|
+
normalized.typesafeRouting = existingTypeSafe;
|
|
4147
|
+
} else if (incomingTypeSafe && isRedactedSecret(incomingTypeSafe.apiKey)) {
|
|
4148
|
+
normalized.typesafeRouting = { ...incomingTypeSafe, apiKey: undefined };
|
|
4149
|
+
}
|
|
4075
4150
|
const unmatchedExisting = [...this.accounts];
|
|
4076
4151
|
const matchAndReuseAccount = (config: AccountConfig): AccountRuntime => {
|
|
4077
4152
|
const targetId = getAccountIdentity(config);
|
package/src/token-encryption.ts
CHANGED
|
@@ -65,6 +65,13 @@ export function isEncryptedToken(token: string): boolean {
|
|
|
65
65
|
);
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
/** Checks whether any persisted secret uses one of the encrypted formats. */
|
|
69
|
+
export const isEncryptedSecret = isEncryptedToken;
|
|
70
|
+
|
|
71
|
+
export function isRedactedSecret(value: string | undefined): boolean {
|
|
72
|
+
return value === "[configured]";
|
|
73
|
+
}
|
|
74
|
+
|
|
68
75
|
/**
|
|
69
76
|
* Encrypts a plain-text OAuth refresh token using AES-256-GCM.
|
|
70
77
|
* Format: enc:v2:<salt_hex>:<iv_hex>:<tag_hex>:<ciphertext_hex>
|
|
@@ -119,6 +126,90 @@ export function decryptRefreshToken(
|
|
|
119
126
|
return decrypted;
|
|
120
127
|
}
|
|
121
128
|
|
|
129
|
+
/** Encrypts a non-OAuth secret using the same authenticated format. */
|
|
130
|
+
export function encryptSecret(secret: string, keyInput: string): string {
|
|
131
|
+
return encryptRefreshToken(secret, keyInput);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Decrypts a non-OAuth secret using the same authenticated format. */
|
|
135
|
+
export function decryptSecret(secret: string, keyInput: string): string {
|
|
136
|
+
return decryptRefreshToken(secret, keyInput);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Encrypts the optional TypeSafe credential before it reaches persistence.
|
|
141
|
+
* A newly supplied API key must never be silently written in plaintext.
|
|
142
|
+
*/
|
|
143
|
+
export function encryptTypeSafeRoutingInConfig(
|
|
144
|
+
config: Config,
|
|
145
|
+
keyInput?: string,
|
|
146
|
+
): Config {
|
|
147
|
+
const routing = config.typesafeRouting;
|
|
148
|
+
if (!routing?.apiKey || isEncryptedSecret(routing.apiKey) || isRedactedSecret(routing.apiKey)) return config;
|
|
149
|
+
const key = keyInput || getEncryptionKey();
|
|
150
|
+
if (!key) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
"TypeSafe API key cannot be persisted without ENCRYPTION_KEY",
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
...config,
|
|
157
|
+
typesafeRouting: {
|
|
158
|
+
...routing,
|
|
159
|
+
apiKey: encryptSecret(routing.apiKey, key),
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Decrypts the persisted TypeSafe credential for runtime use. If the
|
|
166
|
+
* encryption key is unavailable, the ciphertext remains in place and Jev is
|
|
167
|
+
* treated as unavailable by the routing layer.
|
|
168
|
+
*/
|
|
169
|
+
export function decryptTypeSafeRoutingInConfig(
|
|
170
|
+
config: Config,
|
|
171
|
+
keyInput?: string,
|
|
172
|
+
): { config: Config; migrated: boolean } {
|
|
173
|
+
const routing = config.typesafeRouting;
|
|
174
|
+
if (!routing?.apiKey || !isEncryptedSecret(routing.apiKey)) {
|
|
175
|
+
return { config, migrated: Boolean(routing?.apiKey && (keyInput || getEncryptionKey())) };
|
|
176
|
+
}
|
|
177
|
+
const key = keyInput || getEncryptionKey();
|
|
178
|
+
if (!key) {
|
|
179
|
+
if (!missingKeyWarned) {
|
|
180
|
+
tokenLog.warn(
|
|
181
|
+
"Found encrypted TypeSafe API key but ENCRYPTION_KEY is not set; Jev auto-routing is disabled until it is configured.",
|
|
182
|
+
);
|
|
183
|
+
missingKeyWarned = true;
|
|
184
|
+
}
|
|
185
|
+
return { config, migrated: false };
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
return {
|
|
189
|
+
config: {
|
|
190
|
+
...config,
|
|
191
|
+
typesafeRouting: { ...routing, apiKey: decryptSecret(routing.apiKey, key) },
|
|
192
|
+
},
|
|
193
|
+
migrated: false,
|
|
194
|
+
};
|
|
195
|
+
} catch (err) {
|
|
196
|
+
tokenLog.error(`Failed to decrypt TypeSafe API key: ${err}`);
|
|
197
|
+
return { config, migrated: false };
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Returns a config safe for the admin UI/export surface. */
|
|
202
|
+
export function redactTypeSafeRoutingInConfig(config: Config): Config {
|
|
203
|
+
if (!config.typesafeRouting?.apiKey) return structuredClone(config);
|
|
204
|
+
return {
|
|
205
|
+
...structuredClone(config),
|
|
206
|
+
typesafeRouting: {
|
|
207
|
+
...config.typesafeRouting,
|
|
208
|
+
apiKey: "[configured]",
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
122
213
|
/**
|
|
123
214
|
* Transforms a Config object by encrypting all plain account refresh tokens
|
|
124
215
|
* if an encryption key is present.
|
package/src/types.ts
CHANGED
|
@@ -152,6 +152,29 @@ export interface Config {
|
|
|
152
152
|
// Config-driven alias routing based on reasoning_effort.
|
|
153
153
|
// Absent, null, or empty object = disabled.
|
|
154
154
|
effortRouting?: Record<string, EffortRoutingRule> | null;
|
|
155
|
+
/** Optional semantic model routing through TypeSafe Jev. */
|
|
156
|
+
typesafeRouting?: TypeSafeRoutingConfig;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface TypeSafeRoutingConfig {
|
|
160
|
+
/** Explicit opt-in. When omitted, a configured apiKey enables the feature. */
|
|
161
|
+
enabled?: boolean;
|
|
162
|
+
/** TypeSafe API key. Persisted encrypted by the settings layer. */
|
|
163
|
+
apiKey?: string;
|
|
164
|
+
/** Jev model alias. Defaults to the provider's stable latest alias. */
|
|
165
|
+
model?: string;
|
|
166
|
+
/** Optional API root override for self-hosted/test environments. */
|
|
167
|
+
baseURL?: string;
|
|
168
|
+
/** Per-attempt timeout for the routing decision. */
|
|
169
|
+
timeoutMs?: number;
|
|
170
|
+
/** Minimum accepted Jev confidence before deterministic fallback. */
|
|
171
|
+
minConfidence?: number;
|
|
172
|
+
/** Maximum candidate models sent to Jev per request. */
|
|
173
|
+
maxCandidates?: number;
|
|
174
|
+
/** Maximum diverse candidate models included in Jev's final decision. */
|
|
175
|
+
shortlistSize?: number;
|
|
176
|
+
/** Maximum prompt excerpt characters sent to Jev. */
|
|
177
|
+
maxExcerptChars?: number;
|
|
155
178
|
}
|
|
156
179
|
|
|
157
180
|
export interface EffortRoutingRule {
|
package/src/validators.ts
CHANGED
|
@@ -304,6 +304,44 @@ export function validateConfig(value: unknown): ValidationResult<Config> {
|
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
}
|
|
307
|
+
if (value.typesafeRouting !== undefined) {
|
|
308
|
+
if (!isRecord(value.typesafeRouting)) {
|
|
309
|
+
errors.push("config.typesafeRouting must be an object when provided");
|
|
310
|
+
} else {
|
|
311
|
+
const routing = value.typesafeRouting;
|
|
312
|
+
if (routing.enabled !== undefined && typeof routing.enabled !== "boolean") {
|
|
313
|
+
errors.push("config.typesafeRouting.enabled must be a boolean");
|
|
314
|
+
}
|
|
315
|
+
if (routing.apiKey !== undefined && !isNonEmptyString(routing.apiKey)) {
|
|
316
|
+
errors.push("config.typesafeRouting.apiKey must be a non-empty string when provided");
|
|
317
|
+
}
|
|
318
|
+
if (routing.model !== undefined && !isNonEmptyString(routing.model)) {
|
|
319
|
+
errors.push("config.typesafeRouting.model must be a non-empty string when provided");
|
|
320
|
+
}
|
|
321
|
+
if (routing.baseURL !== undefined && !isNonEmptyString(routing.baseURL)) {
|
|
322
|
+
errors.push("config.typesafeRouting.baseURL must be a non-empty string when provided");
|
|
323
|
+
}
|
|
324
|
+
if (routing.timeoutMs !== undefined && !isPositiveNumber(routing.timeoutMs)) {
|
|
325
|
+
errors.push("config.typesafeRouting.timeoutMs must be a positive number");
|
|
326
|
+
}
|
|
327
|
+
if (routing.minConfidence !== undefined &&
|
|
328
|
+
(typeof routing.minConfidence !== "number" || !Number.isFinite(routing.minConfidence) || routing.minConfidence < 0 || routing.minConfidence > 1)) {
|
|
329
|
+
errors.push("config.typesafeRouting.minConfidence must be between 0 and 1");
|
|
330
|
+
}
|
|
331
|
+
if (routing.maxCandidates !== undefined &&
|
|
332
|
+
(!isNonNegativeInteger(routing.maxCandidates) || routing.maxCandidates < 1 || routing.maxCandidates > 128)) {
|
|
333
|
+
errors.push("config.typesafeRouting.maxCandidates must be an integer between 1 and 128");
|
|
334
|
+
}
|
|
335
|
+
if (routing.shortlistSize !== undefined &&
|
|
336
|
+
(!isNonNegativeInteger(routing.shortlistSize) || routing.shortlistSize < 1 || routing.shortlistSize > 32)) {
|
|
337
|
+
errors.push("config.typesafeRouting.shortlistSize must be an integer between 1 and 32");
|
|
338
|
+
}
|
|
339
|
+
if (routing.maxExcerptChars !== undefined &&
|
|
340
|
+
(!isNonNegativeInteger(routing.maxExcerptChars) || routing.maxExcerptChars < 256 || routing.maxExcerptChars > 50_000)) {
|
|
341
|
+
errors.push("config.typesafeRouting.maxExcerptChars must be an integer between 256 and 50000");
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
307
345
|
|
|
308
346
|
return errors.length > 0 ? fail(errors) : ok(value as unknown as Config);
|
|
309
347
|
}
|