tuxevil-rotator 4.3.0 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +4 -2
- package/package.json +2 -1
- package/src/access-evidence.ts +153 -0
- package/src/access-probe.ts +85 -0
- package/src/admin-auth.ts +4 -1
- package/src/auto-access-shadow.ts +11 -0
- package/src/auto-model-access.ts +185 -0
- package/src/auto-output-health.ts +12 -0
- package/src/auto-routing-evaluation.ts +80 -0
- package/src/auto-routing-quality.ts +308 -0
- package/src/auto-routing.ts +403 -26
- package/src/compat.ts +223 -36
- package/src/compression/index.ts +6 -6
- package/src/compression/lite.ts +3 -9
- package/src/compression/rtk/index.ts +0 -3
- package/src/config-defaults.ts +7 -0
- package/src/dashboard.ts +5 -0
- package/src/db-store.ts +10 -0
- package/src/index.ts +2 -0
- package/src/model-access-api.ts +74 -0
- package/src/model-access.ts +56 -0
- package/src/ollama-output-gate.ts +18 -0
- package/src/onboarding.ts +1 -1
- package/src/provider-catalog-evidence.ts +26 -0
- package/src/providers/google-antigravity/dynamic-catalog.ts +8 -0
- package/src/providers/google-antigravity/quota.ts +3 -0
- package/src/providers/ollama/context-window.ts +13 -0
- package/src/providers/ollama/quota.ts +4 -0
- package/src/providers/ollama/translators.ts +19 -2
- package/src/providers/openai-codex/compat.ts +5 -1
- package/src/providers/openai-codex/credentials.ts +22 -6
- package/src/providers/openai-codex/index.ts +9 -1
- package/src/providers/openai-codex/quota.ts +19 -6
- package/src/providers/opencode-zen/forward.ts +1 -1
- package/src/providers/opencode-zen/quota.ts +2 -0
- package/src/proxy.ts +78 -3
- package/src/quota-observation.ts +26 -0
- package/src/quota-pools.ts +322 -0
- package/src/rotator.ts +151 -38
- package/src/settings-repository.ts +1 -0
- package/src/types.ts +28 -0
- package/src/usage-limits-auth.ts +24 -0
- package/src/usage-limits.ts +148 -0
- package/src/validators.ts +26 -0
- package/src/web/components/icons.tsx +15 -0
- package/src/web/components/overlays.tsx +4 -0
- package/src/web/components/ui.tsx +9 -9
- package/src/web/lib/playground.ts +35 -0
- package/src/web/lib/pool-navigation.ts +4 -0
- package/src/web/lib/pools.ts +2 -243
- package/src/web/pages/AccountDetail.tsx +2 -1
- package/src/web/pages/ModelAccess.tsx +88 -0
- package/src/web/pages/Models.tsx +2 -0
- package/src/web/pages/Overview.tsx +26 -9
- package/src/web/pages/Playground.tsx +1132 -551
- package/src/web/pages/Transcription.tsx +304 -170
- package/src/web/state/api.ts +3 -0
- package/src/web/styles/app.css +501 -45
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Policy data for access explanations and auto eligibility; it never authorizes explicit requests. */
|
|
2
|
+
export type AccessState = "allowed" | "blocked" | "conditional" | "unknown";
|
|
3
|
+
export interface AccessRule {
|
|
4
|
+
id: string;
|
|
5
|
+
provider: string;
|
|
6
|
+
plans: string[];
|
|
7
|
+
modelPrefix: string;
|
|
8
|
+
exact?: boolean;
|
|
9
|
+
state: AccessState;
|
|
10
|
+
evidence: "documented" | "operator-confirmed" | "operator-pending";
|
|
11
|
+
source: string;
|
|
12
|
+
verifiedAt: string;
|
|
13
|
+
validFrom: string;
|
|
14
|
+
reviewAfter: string;
|
|
15
|
+
validUntil?: string;
|
|
16
|
+
client?: string;
|
|
17
|
+
note: string;
|
|
18
|
+
}
|
|
19
|
+
const google = "https://antigravity.google/docs/models";
|
|
20
|
+
const rule = (id: string, provider: string, plans: string[], modelPrefix: string, state: AccessState, evidence: AccessRule["evidence"], source: string, note: string, extra: Partial<AccessRule> = {}): AccessRule => ({ id, provider, plans, modelPrefix, state, evidence, source, verifiedAt: "2026-10-30", validFrom: "2026-10-30", reviewAfter: "2026-11-29", note, ...extra });
|
|
21
|
+
export const MODEL_ACCESS_RULES: readonly AccessRule[] = [
|
|
22
|
+
rule("ag-flash-free", "google-antigravity", ["free", "plus", "pro-trial", "pro-paid", "ultra", "enterprise"], "gemini-3.8-flash", "allowed", "documented", google, "Gemini 3.8 Flash is listed for Free/Plus."),
|
|
23
|
+
...["claude-sonnet-4-6", "claude-opus-4-6"].map(model => rule(`ag-legacy-${model}`, "google-antigravity", ["free", "plus"], model, "allowed", "documented", google, "Removal announced for November 2; diagnostic cutoff uses UTC, exact upstream rollout may differ.", { validUntil: "2026-11-02" })),
|
|
24
|
+
...["gemini-4-argon", "claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-paid-${model}`, "google-antigravity", ["free", "plus"], model, "blocked", "documented", google, "Not included in Free/Plus.")),
|
|
25
|
+
...["claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-trial-${model}`, "google-antigravity", ["pro-trial"], model, "blocked", "documented", google, "Claude 5.5 requires a non-trial Pro subscription or higher eligible plan.")),
|
|
26
|
+
...["gemini-4-argon", "claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-entitled-${model}`, "google-antigravity", ["pro-paid", "ultra", "enterprise"], model, "allowed", "documented", google, "Listed for paid Pro/Ultra; account entitlement and quota still apply.")),
|
|
27
|
+
rule("ag-argon-trial", "google-antigravity", ["pro-trial"], "gemini-4-argon", "conditional", "documented", google, "Only eligible premium-device trials; generic trial status is insufficient."),
|
|
28
|
+
...["gpt-6-luna", "gpt-5.6-terra", "gpt-5.6-luna"].map(model => rule(`codex-free-${model}`, "openai-codex", ["free"], model, "allowed", "operator-confirmed", "Operator account-access report, 2026-10-30", "Confirmed as available on Codex Free accounts; live quota and account entitlement still apply.")),
|
|
29
|
+
rule("codex-terra61-free", "openai-codex", ["free"], "gpt-6.1-terra", "blocked", "documented", "https://learn.chatgpt.com/docs/pricing", "Official ChatGPT Work/Codex availability lists paid plans for Terra 6.1. Free is not included; account-specific provider rejections are separate evidence.", { exact: true, verifiedAt: "2026-10-31", validFrom: "2026-10-26", reviewAfter: "2026-11-30" }),
|
|
30
|
+
rule("codex-terra61-plus", "openai-codex", ["plus"], "gpt-6.1-terra", "allowed", "documented", "https://learn.chatgpt.com/docs/pricing", "Terra 6.1 is listed for Plus in Work/Codex; rollout, surface access, quota and account restrictions still apply.", { exact: true, verifiedAt: "2026-10-31", validFrom: "2026-10-26", reviewAfter: "2026-11-30" }),
|
|
31
|
+
...["beam", "gemma4:31b", "gpt-oss:120b", "gpt-oss:20b", "nemotron-3-nano:30b", "nemotron-3-super", "nemotron-3-ultra"].map(model => rule(`ollama-free-${model}`, "ollama", ["free"], model, "allowed", "operator-confirmed", "Operator-provided Ollama free-credit list, 2026-10-30", "Included in the supplied free-credit list; quota and live entitlement are separate.")),
|
|
32
|
+
rule("zen-big-pickle-client", "opencode-zen", ["*"], "big-pickle", "conditional", "documented", "https://github.com/anomalyco/opencode/issues/56702", "Free model without a -free suffix; genuine OpenCode context is required.", { client: "opencode" }),
|
|
33
|
+
rule("zen-free-client", "opencode-zen", ["*"], "*-free", "conditional", "documented", "https://github.com/anomalyco/opencode/issues/56702", "Free tier requires a genuine OpenCode client context. Client declaration is not authentication or proof of acceptance.", { client: "opencode" }),
|
|
34
|
+
];
|
|
35
|
+
export interface AccessQuery { provider: string; model: string; plan?: string; client?: string; at?: string }
|
|
36
|
+
export interface AccessDecision { state: AccessState; reason: string; rules: AccessRule[]; informational: true; declaredPlan: string; clientVerified: false }
|
|
37
|
+
function matches(pattern: string, model: string): boolean {
|
|
38
|
+
if (pattern === "*-free") return model.endsWith("-free");
|
|
39
|
+
return model === pattern || model.startsWith(pattern + "-");
|
|
40
|
+
}
|
|
41
|
+
export function evaluateModelAccess(query: AccessQuery): AccessDecision {
|
|
42
|
+
const instant = query.at === undefined ? new Date() : new Date(query.at);
|
|
43
|
+
if (!Number.isFinite(instant.getTime())) throw new Error("Invalid evaluation date");
|
|
44
|
+
const plan = query.plan ?? "unknown";
|
|
45
|
+
const rules = MODEL_ACCESS_RULES.filter(r => r.provider === query.provider && (r.plans.includes(plan) || r.plans.includes("*")) && (r.exact ? r.modelPrefix === query.model : matches(r.modelPrefix, query.model)));
|
|
46
|
+
const decision = (state: AccessState, reason: string): AccessDecision => ({ state, reason, rules, informational: true, declaredPlan: plan, clientVerified: false });
|
|
47
|
+
if (!rules.length) return decision("unknown", "No verified rule for this provider, plan and model; absence is not permission.");
|
|
48
|
+
if (rules.some(r => instant < new Date(r.validFrom + "T00:00:00Z"))) return decision("unknown", "No historical policy evidence for the requested date.");
|
|
49
|
+
if (rules.some(r => instant >= new Date(r.reviewAfter + "T00:00:00Z"))) return decision("unknown", "Policy evidence needs re-verification; the review date has passed.");
|
|
50
|
+
if (rules.some(r => r.evidence === "operator-pending")) return decision("unknown", "Operator-reported policy pending verification; see declared states and evidence.");
|
|
51
|
+
if (rules.some(r => r.validUntil && instant >= new Date(r.validUntil + "T00:00:00Z"))) return decision("blocked", "Announced model availability window has ended (UTC diagnostic cutoff).");
|
|
52
|
+
if (rules.some(r => r.state === "blocked")) return decision("blocked", rules.find(r => r.state === "blocked")!.note);
|
|
53
|
+
if (rules.some(r => r.client)) return decision("conditional", query.client === "opencode" ? "OpenCode client declared; upstream acceptance still requires genuine context." : "Requires an OpenCode-originated request; origin is unknown or another client.");
|
|
54
|
+
if (rules.some(r => r.state === "conditional")) return decision("conditional", rules.find(r => r.state === "conditional")!.note);
|
|
55
|
+
return decision("allowed", "Documented plan access; not a guarantee of quota, credentials or request capability.");
|
|
56
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Retain only the prefix before useful output. No caller-visible bytes are replayed. */
|
|
2
|
+
export async function gateOllamaOutput(body: ReadableStream<Uint8Array>, timeoutMs=30000, maxBytes=1048576): Promise<{body:ReadableStream<Uint8Array>; useful:boolean}> {
|
|
3
|
+
const reader=body.getReader(),chunks:Uint8Array[]=[];const decoder=new TextDecoder();let pending='',bytes=0;
|
|
4
|
+
const hasUseful=(line:string):boolean=>{try{const m=JSON.parse(line)?.message;return typeof m?.content==='string'&&m.content.trim().length>0||Array.isArray(m?.tool_calls)&&m.tool_calls.some((t:{function?:{name?:unknown}})=>typeof t?.function?.name==='string'&&t.function.name.length>0);}catch{return false;}};
|
|
5
|
+
const started=Date.now();
|
|
6
|
+
try{
|
|
7
|
+
while(true){
|
|
8
|
+
let timer:ReturnType<typeof setTimeout>|undefined;
|
|
9
|
+
const chunk=await Promise.race([reader.read(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new Error('Ollama useful-output deadline exceeded')),Math.max(1,timeoutMs-(Date.now()-started)))})]).finally(()=>clearTimeout(timer));
|
|
10
|
+
if(chunk.done){const collected=new ReadableStream<Uint8Array>({start(c){for(const x of chunks)c.enqueue(x);c.close()}});return{body:collected,useful:hasUseful(pending)};}
|
|
11
|
+
chunks.push(chunk.value);bytes+=chunk.value.byteLength;if(bytes>maxBytes)throw Error('Ollama useful-output prefix limit exceeded');
|
|
12
|
+
pending+=decoder.decode(chunk.value,{stream:true});const lines=pending.split('\n');pending=lines.pop()??'';
|
|
13
|
+
for(const line of lines){const useful=hasUseful(line);
|
|
14
|
+
if(useful){let index=0;return{useful:true,body:new ReadableStream<Uint8Array>({async pull(c){if(index<chunks.length){c.enqueue(chunks[index++]);return;}try{const next=await reader.read();if(next.done)c.close();else c.enqueue(next.value);}catch(e){c.error(e)}},cancel(reason){return reader.cancel(reason)}})};}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}catch(e){void reader.cancel().catch(()=>{});throw e;}
|
|
18
|
+
}
|
package/src/onboarding.ts
CHANGED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AccountConfig } from "./types.js";
|
|
2
|
+
import { applyModelAlias } from "./types.js";
|
|
3
|
+
import { getAccountIdentity, getCredentialGeneration } from "./account-identity.js";
|
|
4
|
+
import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
|
|
5
|
+
|
|
6
|
+
export interface ProviderCatalogEvidence {
|
|
7
|
+
provider: "google-antigravity";
|
|
8
|
+
source: "fetchAvailableModels";
|
|
9
|
+
freshness: "fresh" | "stale" | "unknown";
|
|
10
|
+
observedAt: number | null;
|
|
11
|
+
expiresAt: number | null;
|
|
12
|
+
models: string[];
|
|
13
|
+
}
|
|
14
|
+
export function antigravityCatalogEvidence(account: AccountConfig, pollIntervalMs = 300000, now = Date.now()): ProviderCatalogEvidence {
|
|
15
|
+
const snapshot = dynamicCatalog.getAccountSnapshot(getAccountIdentity(account), getCredentialGeneration(account, "google-antigravity"));
|
|
16
|
+
const base = { provider: "google-antigravity", source: "fetchAvailableModels" } as const;
|
|
17
|
+
if (!snapshot) return { ...base, freshness: "unknown", observedAt: null, expiresAt: null, models: [] };
|
|
18
|
+
const maxAge = Math.min(1800000, Math.max(60000, pollIntervalMs * 2));
|
|
19
|
+
const expiresAt = snapshot.observedAt + maxAge;
|
|
20
|
+
return { ...base, ...snapshot, expiresAt, freshness: snapshot.observedAt > now ? "unknown" : expiresAt > now ? "fresh" : "stale" };
|
|
21
|
+
}
|
|
22
|
+
export function advertisedModelState(catalog: ProviderCatalogEvidence, model: string): "advertised" | "not-advertised" | "unknown" {
|
|
23
|
+
if (catalog.freshness !== "fresh") return "unknown";
|
|
24
|
+
const target = applyModelAlias(model).trim().replace(/^models\//i, "").toLowerCase();
|
|
25
|
+
return catalog.models.some(id => id.toLowerCase() === target) ? "advertised" : "not-advertised";
|
|
26
|
+
}
|
|
@@ -479,6 +479,14 @@ export class DynamicModelRegistry {
|
|
|
479
479
|
return match;
|
|
480
480
|
}
|
|
481
481
|
|
|
482
|
+
getAccountSnapshot(accountId: string, credentialGeneration: string): { observedAt: number; models: string[] } | undefined {
|
|
483
|
+
if (!this.isAccountGenerationActive(accountId, credentialGeneration)) return undefined;
|
|
484
|
+
const key = accountKey(accountId);
|
|
485
|
+
const models = this.accountModels.get(key), observedAt = this.snapshotTimes.get(key);
|
|
486
|
+
if (!models || observedAt === undefined) return undefined;
|
|
487
|
+
return { observedAt, models: Array.from(models.values(), model => model.id).sort() };
|
|
488
|
+
}
|
|
489
|
+
|
|
482
490
|
hasModelForAccount(accountId: string, id: string): boolean {
|
|
483
491
|
return this.accountModelOwnership
|
|
484
492
|
.get(accountKey(accountId))
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { observeQuota } from "../../quota-observation.js";
|
|
1
2
|
// Google Antigravity quota polling: fetch per-model quota from the internal
|
|
2
3
|
// fetchAvailableModels endpoint and classify timer windows.
|
|
3
4
|
|
|
@@ -157,6 +158,8 @@ export function extractQuotas(
|
|
|
157
158
|
quotas.push({
|
|
158
159
|
modelKey: config.key,
|
|
159
160
|
displayName: config.display,
|
|
161
|
+
observation: observeQuota({ percentRemaining: Math.round(remainingFraction * 100), resetTime },
|
|
162
|
+
now, modelInfo.quotaInfo.remainingFraction === undefined ? "unknown" : "derived", "reported"),
|
|
160
163
|
percentRemaining: Math.round(remainingFraction * 100),
|
|
161
164
|
resetTime,
|
|
162
165
|
timerType,
|
|
@@ -115,3 +115,16 @@ export async function getOllamaContextWindow(
|
|
|
115
115
|
export function clearOllamaContextCache(): void {
|
|
116
116
|
cache.clear();
|
|
117
117
|
}
|
|
118
|
+
|
|
119
|
+
/** Read without network I/O on the routing path. Expired discoveries are not trusted. */
|
|
120
|
+
export function getCachedOllamaContextWindow(model: string): number {
|
|
121
|
+
const entry = cache.get(model);
|
|
122
|
+
return entry && entry.expiresAt > Date.now() ? entry.contextWindow : defaultNumCtx();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Bounded discovery outside request selection. Failures retain the safe fallback. */
|
|
126
|
+
export async function primeOllamaContextWindows(models: string[], account: AccountRuntime): Promise<void> {
|
|
127
|
+
for (let index = 0; index < models.length; index += 4) {
|
|
128
|
+
await Promise.allSettled(models.slice(index, index + 4).map(model => getOllamaContextWindow(model, account)));
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { observeQuota } from "../../quota-observation.js";
|
|
1
2
|
// Ollama Cloud quota polling: `GET /api/balance` → included credits/windows.
|
|
2
3
|
//
|
|
3
4
|
// Ported from the ollama-rotator project (same author) into the
|
|
@@ -80,6 +81,9 @@ export async function fetchProviderUsage(
|
|
|
80
81
|
fresh.forEach(
|
|
81
82
|
(q) => (q.providerId = "ollama"),
|
|
82
83
|
);
|
|
84
|
+
const observedAt = Date.now();
|
|
85
|
+
for (const quota of fresh) quota.observation = observeQuota(quota, observedAt,
|
|
86
|
+
!legacy && !quota.credits ? "reported" : "derived", legacy ? "estimated" : "reported");
|
|
83
87
|
account.quota = sortQuotaPools([...otherProviders, ...fresh]);
|
|
84
88
|
account.lastQuotaPoll = Date.now();
|
|
85
89
|
const polledAt = new Date(account.lastQuotaPoll).toISOString();
|
|
@@ -211,18 +211,30 @@ export function parseOllamaNdjson(raw: string): CompatCompletion {
|
|
|
211
211
|
let inputTokens = 0;
|
|
212
212
|
let outputTokens = 0;
|
|
213
213
|
let text = "";
|
|
214
|
+
let thinkingText = "";
|
|
215
|
+
let streamError: string | undefined;
|
|
216
|
+
let finishReason: string | undefined;
|
|
217
|
+
let terminal = false;
|
|
214
218
|
const toolCalls: OpenAIToolCall[] = [];
|
|
215
|
-
|
|
219
|
+
let chunks = raw.split(/\r?\n/);
|
|
220
|
+
// Nonstreaming Ollama may return one pretty-printed JSON object.
|
|
221
|
+
try { const single: unknown = JSON.parse(raw); if (isRecord(single)) chunks = [JSON.stringify(single)]; } catch { /* NDJSON */ }
|
|
222
|
+
for (const chunk of chunks) {
|
|
216
223
|
const line = chunk.trim();
|
|
217
224
|
if (!line) continue;
|
|
218
225
|
try {
|
|
219
226
|
const parsed = JSON.parse(line) as Record<string, unknown>;
|
|
227
|
+
if (!isRecord(parsed)) { streamError = "Invalid Ollama response"; continue; }
|
|
228
|
+
if (parsed.error !== undefined) { streamError = "Ollama returned an upstream error"; continue; }
|
|
220
229
|
if (parsed.done === true) {
|
|
230
|
+
terminal = true;
|
|
231
|
+
if (parsed.done_reason === "length") finishReason = "MAX_TOKENS";
|
|
221
232
|
inputTokens = (parsed.prompt_eval_count as number) ?? 0;
|
|
222
233
|
outputTokens = (parsed.eval_count as number) ?? 0;
|
|
223
234
|
}
|
|
224
235
|
const msg = isRecord(parsed.message) ? parsed.message : null;
|
|
225
236
|
if (msg) {
|
|
237
|
+
if (typeof msg.thinking === "string") thinkingText += msg.thinking;
|
|
226
238
|
if (typeof msg.content === "string" && msg.content) {
|
|
227
239
|
text += msg.content;
|
|
228
240
|
}
|
|
@@ -244,10 +256,15 @@ export function parseOllamaNdjson(raw: string): CompatCompletion {
|
|
|
244
256
|
}
|
|
245
257
|
}
|
|
246
258
|
} catch {
|
|
247
|
-
|
|
259
|
+
streamError = "Malformed Ollama response";
|
|
248
260
|
}
|
|
249
261
|
}
|
|
262
|
+
if (!terminal) streamError ??= "Ollama response ended without a completion record";
|
|
263
|
+
if (!text.trim() && toolCalls.length === 0) streamError ??= "Ollama returned no completion content";
|
|
250
264
|
return {
|
|
265
|
+
...(thinkingText ? { thinkingText } : {}),
|
|
266
|
+
...(streamError ? { streamError } : {}),
|
|
267
|
+
...(finishReason ? { finishReason } : {}),
|
|
251
268
|
text,
|
|
252
269
|
inputTokens,
|
|
253
270
|
outputTokens,
|
|
@@ -42,6 +42,7 @@ export interface CodexCompatOptions {
|
|
|
42
42
|
selectionMode?: "typesafe" | "deterministic" | "shadow" | "disabled";
|
|
43
43
|
selectionConfidence?: number;
|
|
44
44
|
selectionReason?: string;
|
|
45
|
+
autoRecovery?: (status: number, context: RotationAttemptContext | undefined, errorText: string) => Promise<boolean>;
|
|
45
46
|
}
|
|
46
47
|
|
|
47
48
|
function recordCodexTokenUsage(
|
|
@@ -629,8 +630,11 @@ export async function serveCodexChat(
|
|
|
629
630
|
recordCodexTokenUsage(rotator, request.model, completion);
|
|
630
631
|
recordCodexOutcome(rotator, body, context, response.status, completion, options);
|
|
631
632
|
return completion;
|
|
632
|
-
}, controller.signal);
|
|
633
|
+
}, controller.signal, { autoRecovery: options?.autoRecovery !== undefined });
|
|
633
634
|
recordCodexFailure(rotator, body, outcome, options);
|
|
635
|
+
if (!outcome.ok && !res.headersSent && options?.autoRecovery) {
|
|
636
|
+
if (await options.autoRecovery(outcome.status, outcome.context, outcome.errorText)) return;
|
|
637
|
+
}
|
|
634
638
|
if (!outcome.ok && !res.headersSent) writeJson(res, outcome.status, { error: { message: outcome.errorText, type: "upstream_error" } });
|
|
635
639
|
} finally {
|
|
636
640
|
req.off("aborted", abort);
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import type { AccountConfig, AccountRuntime, ProviderCredential } from "../../types.js";
|
|
2
2
|
import { loadConfig, saveAccountsConfig } from "../../config-storage.js";
|
|
3
3
|
import { getCredential } from "../credential-helpers.js";
|
|
4
|
-
import { CODEX_PROVIDER_ID } from "./oauth.js";
|
|
4
|
+
import { CODEX_PROVIDER_ID, type CodexIdentity } from "./oauth.js";
|
|
5
|
+
import { getAccountIdentity, getCredentialGenerationFingerprint } from "../../account-identity.js";
|
|
6
|
+
import { accessEvidenceStore, persistAccessEvidence } from "../../access-evidence.js";
|
|
7
|
+
import { isSettingsRepositoryInitialized } from "../../db-store.js";
|
|
8
|
+
import { logger } from "../../logger.js";
|
|
5
9
|
|
|
6
10
|
export interface ProviderTokenState {
|
|
7
11
|
accessToken: string | null;
|
|
@@ -44,23 +48,26 @@ const persistenceLocks = new Map<string, Promise<void>>();
|
|
|
44
48
|
export async function persistCodexRefreshToken(
|
|
45
49
|
account: AccountRuntime,
|
|
46
50
|
refreshToken: string,
|
|
51
|
+
verifiedIdentity?: CodexIdentity,
|
|
47
52
|
): Promise<void> {
|
|
48
|
-
await persistCodexCredentialRefresh(loadConfig
|
|
53
|
+
await persistCodexCredentialRefresh(loadConfig, account, refreshToken, verifiedIdentity);
|
|
49
54
|
}
|
|
50
55
|
|
|
51
56
|
/** Persist one credential while preserving every sibling account/provider. */
|
|
52
57
|
export async function persistCodexCredentialRefresh(
|
|
53
|
-
|
|
58
|
+
configOrLoad: Parameters<typeof saveAccountsConfig>[0] | (() => Parameters<typeof saveAccountsConfig>[0]),
|
|
54
59
|
account: AccountRuntime,
|
|
55
60
|
refreshToken: string,
|
|
61
|
+
verifiedIdentity?: CodexIdentity,
|
|
56
62
|
): Promise<void> {
|
|
57
63
|
const email = account.config.email.toLowerCase();
|
|
58
64
|
const previous = persistenceLocks.get(email) ?? Promise.resolve();
|
|
59
65
|
const next = previous.catch(() => undefined).then(async () => {
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
);
|
|
66
|
+
const config = typeof configOrLoad === "function" ? configOrLoad() : configOrLoad;
|
|
67
|
+
const before = structuredClone(account.config);
|
|
68
|
+
const accountConfig = config.accounts.find(entry => getAccountIdentity(entry) === getAccountIdentity(before));
|
|
63
69
|
if (!accountConfig) throw new Error("Codex account disappeared while refreshing");
|
|
70
|
+
if (getCredentialGenerationFingerprint(accountConfig, CODEX_PROVIDER_ID) !== getCredentialGenerationFingerprint(before, CODEX_PROVIDER_ID)) throw new Error("Codex credential changed during refresh; retry with current credentials");
|
|
64
71
|
const credentials = [...(accountConfig.credentials ?? account.config.credentials ?? [])];
|
|
65
72
|
const index = credentials.findIndex((entry) => entry.provider === CODEX_PROVIDER_ID);
|
|
66
73
|
if (index < 0) throw new Error("Codex credential is no longer present; re-authenticate");
|
|
@@ -68,6 +75,15 @@ export async function persistCodexCredentialRefresh(
|
|
|
68
75
|
accountConfig.credentials = credentials;
|
|
69
76
|
account.config.credentials = credentials;
|
|
70
77
|
await saveAccountsConfig(config);
|
|
78
|
+
// No historical rebinding: transfer only the exact generation used by this
|
|
79
|
+
// successful provider exchange, after the replacement credential is durable.
|
|
80
|
+
if (verifiedIdentity?.providerAccountId && isSettingsRepositoryInitialized()) {
|
|
81
|
+
const changed = accessEvidenceStore().continueCodexRefresh(before, account.config, verifiedIdentity.providerAccountId);
|
|
82
|
+
if (changed) {
|
|
83
|
+
try { await persistAccessEvidence(); }
|
|
84
|
+
catch { logger.child("provider/openai-codex").warn("Codex credential saved; access evidence persistence needs retry"); }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
71
87
|
});
|
|
72
88
|
persistenceLocks.set(email, next);
|
|
73
89
|
try {
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import {
|
|
12
12
|
CodexOAuthError,
|
|
13
13
|
refreshCodexToken,
|
|
14
|
+
parseCodexIdentity,
|
|
14
15
|
} from "./oauth.js";
|
|
15
16
|
import { runCodexLogin } from "./login.js";
|
|
16
17
|
import {
|
|
@@ -53,6 +54,13 @@ async function ensureCodexToken(account: AccountRuntime): Promise<void> {
|
|
|
53
54
|
);
|
|
54
55
|
}
|
|
55
56
|
const refreshed = await refreshCodexToken(refreshToken);
|
|
57
|
+
const identity = parseCodexIdentity(refreshed.accessToken, refreshed.idToken);
|
|
58
|
+
const expectedId = getCodexAccountId(account.config);
|
|
59
|
+
const returnedIdentities = [parseCodexIdentity(refreshed.accessToken), parseCodexIdentity(refreshed.idToken)];
|
|
60
|
+
if (returnedIdentities.some(candidate => (expectedId && candidate.providerAccountId && candidate.providerAccountId !== expectedId) || (candidate.email && candidate.email.trim().toLowerCase() !== account.config.email.trim().toLowerCase()))) {
|
|
61
|
+
throw new CodexOAuthError("Codex OAuth refresh returned a different account identity", { code: "refresh_identity_mismatch", reloginRequired: true });
|
|
62
|
+
}
|
|
63
|
+
const verifiedIdentity = expectedId && identity.providerAccountId === expectedId ? identity : undefined;
|
|
56
64
|
setCodexTokenState(account, {
|
|
57
65
|
accessToken: refreshed.accessToken,
|
|
58
66
|
tokenExpires: refreshed.expiresAt,
|
|
@@ -60,7 +68,7 @@ async function ensureCodexToken(account: AccountRuntime): Promise<void> {
|
|
|
60
68
|
// Rotating refresh tokens are one-time credentials. Persist the returned
|
|
61
69
|
// generation before allowing another request to use this account.
|
|
62
70
|
try {
|
|
63
|
-
await persistCodexRefreshToken(account, refreshed.refreshToken);
|
|
71
|
+
await persistCodexRefreshToken(account, refreshed.refreshToken, verifiedIdentity);
|
|
64
72
|
} catch (error) {
|
|
65
73
|
setCodexTokenState(account, { accessToken: null, tokenExpires: 0 });
|
|
66
74
|
throw new Error("Could not persist the rotated Codex refresh token", { cause: error });
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { observeQuota } from "../../quota-observation.js";
|
|
1
2
|
import type { AccountRuntime, ModelQuota } from "../../types.js";
|
|
2
3
|
import type { QuotaFetchContext } from "../adapter.js";
|
|
3
4
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
@@ -17,6 +18,8 @@ export const CODEX_UNSTARTED_TIMER_THRESHOLD_SECONDS =
|
|
|
17
18
|
30 * 24 * 60 * 60 - 5 * 60;
|
|
18
19
|
|
|
19
20
|
export interface CodexQuotaWindow {
|
|
21
|
+
/** False/absent for compatibility defaults, never evidence of measured usage. */
|
|
22
|
+
usageReported?: boolean;
|
|
20
23
|
usedPercent: number;
|
|
21
24
|
percentRemaining: number;
|
|
22
25
|
resetAt: string | null;
|
|
@@ -66,6 +69,7 @@ export function parseCodexQuotaWindow(value: unknown): CodexQuotaWindow | null {
|
|
|
66
69
|
const reset = resetAt(window);
|
|
67
70
|
const usedPercent = Math.max(0, Math.min(100, used ?? 0));
|
|
68
71
|
return {
|
|
72
|
+
usageReported: used !== null && used >= 0 && used <= 100,
|
|
69
73
|
usedPercent,
|
|
70
74
|
percentRemaining: Math.max(0, Math.min(100, 100 - usedPercent)),
|
|
71
75
|
resetAt: reset.at,
|
|
@@ -136,7 +140,7 @@ function visibleResetTime(window: CodexQuotaWindow): string | null {
|
|
|
136
140
|
return timerType(window) === "fresh" ? null : window.resetAt;
|
|
137
141
|
}
|
|
138
142
|
|
|
139
|
-
export function codexQuotaRows(snapshot: CodexQuotaSnapshot): ModelQuota[] {
|
|
143
|
+
export function codexQuotaRows(snapshot: CodexQuotaSnapshot, observedAt?: number): ModelQuota[] {
|
|
140
144
|
const dominant = dominantWindow(snapshot);
|
|
141
145
|
const rows: ModelQuota[] = [{
|
|
142
146
|
modelKey: CODEX_QUOTA_MODEL_KEY,
|
|
@@ -159,6 +163,14 @@ export function codexQuotaRows(snapshot: CodexQuotaSnapshot): ModelQuota[] {
|
|
|
159
163
|
timerType: timerType(spark),
|
|
160
164
|
});
|
|
161
165
|
}
|
|
166
|
+
if (observedAt !== undefined) {
|
|
167
|
+
for (const row of rows) {
|
|
168
|
+
const windows = row.modelKey === CODEX_QUOTA_MODEL_KEY ? [dominant] :
|
|
169
|
+
[snapshot.spark?.primary, snapshot.spark?.secondary].filter((window): window is CodexQuotaWindow => Boolean(window));
|
|
170
|
+
const selected = windows.reduce((a, b) => a.usedPercent >= b.usedPercent ? a : b);
|
|
171
|
+
row.observation = observeQuota(row, observedAt, selected.usageReported === true ? "derived" : "unknown", "reported");
|
|
172
|
+
}
|
|
173
|
+
}
|
|
162
174
|
return rows;
|
|
163
175
|
}
|
|
164
176
|
|
|
@@ -196,7 +208,7 @@ export async function fetchCodexQuota(
|
|
|
196
208
|
const key = cacheKey(account);
|
|
197
209
|
const cached = quotaCache.get(key);
|
|
198
210
|
if (cached && Date.now() - cached.fetchedAt < CODEX_QUOTA_CACHE_TTL_MS) {
|
|
199
|
-
applyQuotaRows(account, cached.snapshot);
|
|
211
|
+
applyQuotaRows(account, cached.snapshot, cached.fetchedAt);
|
|
200
212
|
return;
|
|
201
213
|
}
|
|
202
214
|
const token = getCodexTokenState(account).accessToken;
|
|
@@ -230,19 +242,20 @@ export async function fetchCodexQuota(
|
|
|
230
242
|
if (!response.ok) return;
|
|
231
243
|
const snapshot = parseCodexUsageResponse(await response.json());
|
|
232
244
|
if (!snapshot) return;
|
|
233
|
-
|
|
234
|
-
|
|
245
|
+
const fetchedAt = Date.now();
|
|
246
|
+
quotaCache.set(key, { fetchedAt, snapshot });
|
|
247
|
+
applyQuotaRows(account, snapshot, fetchedAt);
|
|
235
248
|
account.lastQuotaPoll = Date.now();
|
|
236
249
|
} catch {
|
|
237
250
|
// Quota is best-effort and never blocks a generation request.
|
|
238
251
|
}
|
|
239
252
|
}
|
|
240
253
|
|
|
241
|
-
function applyQuotaRows(account: AccountRuntime, snapshot: CodexQuotaSnapshot): void {
|
|
254
|
+
function applyQuotaRows(account: AccountRuntime, snapshot: CodexQuotaSnapshot, observedAt: number): void {
|
|
242
255
|
const other = (account.quota ?? []).filter(
|
|
243
256
|
(quota) => quota.providerId !== CODEX_PROVIDER_ID,
|
|
244
257
|
);
|
|
245
|
-
const codexRows = codexQuotaRows(snapshot);
|
|
258
|
+
const codexRows = codexQuotaRows(snapshot, observedAt);
|
|
246
259
|
account.quota = sortQuotaPools([...other, ...codexRows]);
|
|
247
260
|
|
|
248
261
|
account.lastPollByProvider ??= {};
|
|
@@ -235,7 +235,7 @@ function headerValue(headers: Record<string, string>, name: string): string | un
|
|
|
235
235
|
|
|
236
236
|
function buildOpenCodeZenHeaders(
|
|
237
237
|
originalHeaders: Record<string, string>,
|
|
238
|
-
|
|
238
|
+
_body: RequestBody,
|
|
239
239
|
account: AccountRuntime,
|
|
240
240
|
): Record<string, string> {
|
|
241
241
|
const headers: Record<string, string> = {};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { observeQuota } from "../../quota-observation.js";
|
|
1
2
|
// OpenCode Zen quota polling.
|
|
2
3
|
|
|
3
4
|
import { fetchWithRetry } from "../../fetch-with-retry.js";
|
|
@@ -58,6 +59,7 @@ export async function fetchOpenCodeZenQuota(
|
|
|
58
59
|
timerType: "fresh",
|
|
59
60
|
};
|
|
60
61
|
|
|
62
|
+
freshQuota.observation = { ...observeQuota(freshQuota, Date.now(), "unknown", "unknown"), catalogAccessible: true };
|
|
61
63
|
account.quota = sortQuotaPools([...otherProviders, freshQuota]);
|
|
62
64
|
account.lastQuotaPoll = Date.now();
|
|
63
65
|
|