tuxevil-rotator 4.2.2 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/README.md +11 -4
  3. package/package.json +2 -1
  4. package/plugins/opencode-discovery/capabilities.d.mts +7 -0
  5. package/plugins/opencode-discovery/capabilities.mjs +54 -0
  6. package/plugins/opencode-discovery/index.d.mts +2 -1
  7. package/plugins/opencode-discovery/index.mjs +6 -1
  8. package/plugins/opencode-discovery/package.json +3 -1
  9. package/src/access-evidence.ts +153 -0
  10. package/src/access-probe.ts +85 -0
  11. package/src/admin-auth.ts +4 -1
  12. package/src/audio-transcription.ts +32 -6
  13. package/src/auto-access-shadow.ts +11 -0
  14. package/src/auto-model-access.ts +185 -0
  15. package/src/auto-output-health.ts +12 -0
  16. package/src/auto-routing-evaluation.ts +80 -0
  17. package/src/auto-routing-quality.ts +308 -0
  18. package/src/auto-routing.ts +403 -26
  19. package/src/cli.ts +3 -3
  20. package/src/compat/model-specs.ts +4 -0
  21. package/src/compat.ts +253 -37
  22. package/src/compression/index.ts +6 -6
  23. package/src/compression/lite.ts +3 -9
  24. package/src/compression/rtk/index.ts +0 -3
  25. package/src/config-defaults.ts +7 -0
  26. package/src/dashboard-app.ts +1 -0
  27. package/src/dashboard.ts +5 -0
  28. package/src/db-store.ts +10 -0
  29. package/src/index.ts +2 -0
  30. package/src/install-agent.ts +211 -129
  31. package/src/install-opencode.ts +80 -18
  32. package/src/model-access-api.ts +74 -0
  33. package/src/model-access.ts +56 -0
  34. package/src/ollama-output-gate.ts +18 -0
  35. package/src/onboarding.ts +1 -1
  36. package/src/provider-catalog-evidence.ts +26 -0
  37. package/src/providers/google-antigravity/catalog.ts +14 -6
  38. package/src/providers/google-antigravity/dynamic-catalog.ts +87 -3
  39. package/src/providers/google-antigravity/forward.ts +4 -2
  40. package/src/providers/google-antigravity/quota.ts +7 -0
  41. package/src/providers/ollama/context-window.ts +13 -0
  42. package/src/providers/ollama/forward.ts +10 -0
  43. package/src/providers/ollama/quota.ts +4 -0
  44. package/src/providers/ollama/translators.ts +19 -2
  45. package/src/providers/openai-codex/catalog.ts +157 -18
  46. package/src/providers/openai-codex/compat.ts +5 -1
  47. package/src/providers/openai-codex/credentials.ts +22 -6
  48. package/src/providers/openai-codex/index.ts +9 -1
  49. package/src/providers/openai-codex/quota.ts +19 -6
  50. package/src/providers/opencode-zen/forward.ts +1 -1
  51. package/src/providers/opencode-zen/quota.ts +2 -0
  52. package/src/proxy.ts +113 -5
  53. package/src/quota-observation.ts +26 -0
  54. package/src/quota-pools.ts +322 -0
  55. package/src/rotator.ts +167 -40
  56. package/src/settings-repository.ts +1 -0
  57. package/src/types.ts +106 -29
  58. package/src/usage-limits-auth.ts +24 -0
  59. package/src/usage-limits.ts +148 -0
  60. package/src/validators.ts +26 -0
  61. package/src/web/app.tsx +4 -0
  62. package/src/web/components/icons.tsx +15 -0
  63. package/src/web/components/overlays.tsx +4 -0
  64. package/src/web/components/ui.tsx +9 -9
  65. package/src/web/lib/audio-recorder.ts +159 -0
  66. package/src/web/lib/colors.ts +4 -0
  67. package/src/web/lib/playground-storage.ts +261 -0
  68. package/src/web/lib/playground.ts +483 -0
  69. package/src/web/lib/pool-navigation.ts +4 -0
  70. package/src/web/lib/pools.ts +2 -243
  71. package/src/web/nav.ts +1 -0
  72. package/src/web/pages/AccountDetail.tsx +2 -1
  73. package/src/web/pages/ModelAccess.tsx +88 -0
  74. package/src/web/pages/Models.tsx +2 -0
  75. package/src/web/pages/Overview.tsx +26 -9
  76. package/src/web/pages/Playground.tsx +1692 -0
  77. package/src/web/pages/Transcription.tsx +562 -0
  78. package/src/web/state/api.ts +6 -0
  79. package/src/web/state/playground-client.ts +136 -0
  80. package/src/web/state/playground.ts +69 -0
  81. package/src/web/state/router.ts +2 -2
  82. package/src/web/state/transcription-client.ts +93 -0
  83. package/src/web/styles/app.css +501 -0
  84. package/tools/telemetry-receiver/receiver.js +59 -46
@@ -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
 
@@ -10,6 +11,8 @@ import {
10
11
  QUOTA_API_URL,
11
12
  QUOTA_USER_AGENT,
12
13
  QUOTA_MODEL_KEYS,
14
+ REQUEST_CLIENT_METADATA,
15
+ REQUEST_GOOG_API_CLIENT,
13
16
  } from "../../types.js";
14
17
  import { fetchWithRetry } from "../../fetch-with-retry.js";
15
18
  import {
@@ -155,6 +158,8 @@ export function extractQuotas(
155
158
  quotas.push({
156
159
  modelKey: config.key,
157
160
  displayName: config.display,
161
+ observation: observeQuota({ percentRemaining: Math.round(remainingFraction * 100), resetTime },
162
+ now, modelInfo.quotaInfo.remainingFraction === undefined ? "unknown" : "derived", "reported"),
158
163
  percentRemaining: Math.round(remainingFraction * 100),
159
164
  resetTime,
160
165
  timerType,
@@ -200,6 +205,8 @@ export async function fetchProviderQuota(
200
205
  "Content-Type": "application/json",
201
206
  Authorization: `Bearer ${account.accessToken}`,
202
207
  "User-Agent": QUOTA_USER_AGENT,
208
+ "X-Goog-Api-Client": REQUEST_GOOG_API_CLIENT,
209
+ "Client-Metadata": REQUEST_CLIENT_METADATA,
203
210
  },
204
211
  body: JSON.stringify({
205
212
  project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
@@ -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
+ }
@@ -86,6 +86,16 @@ export function buildOllamaPayload(body: RequestBody): Record<string, unknown> {
86
86
  if (!isRecord(msg)) return msg;
87
87
  const normalized = { ...msg };
88
88
  normalizeOllamaMessageContent(normalized);
89
+ // Ollama decodes images[] directly as base64. OpenAI/Anthropic image
90
+ // blocks use data URLs, whose prefix fails decoding at the ':' byte.
91
+ // Normalize after merging so native images and content blocks both work.
92
+ if (Array.isArray(normalized.images)) {
93
+ normalized.images = normalized.images.map((image: unknown) =>
94
+ typeof image === "string"
95
+ ? image.replace(/^data:[^,]*;base64,/i, "")
96
+ : image,
97
+ );
98
+ }
89
99
  return normalized;
90
100
  });
91
101
  const payload: Record<string, unknown> = {
@@ -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
- for (const chunk of raw.split(/\r?\n/)) {
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
- // Ignore malformed NDJSON lines
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,
@@ -8,6 +8,8 @@ export interface CodexModel {
8
8
  id: string;
9
9
  contextWindow: number;
10
10
  reasoning: boolean;
11
+ reasoningEfforts?: string[];
12
+ defaultReasoningEffort?: string;
11
13
  multimodal: boolean;
12
14
  tools: boolean;
13
15
  source: "allowlist" | "discovered";
@@ -29,12 +31,66 @@ const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
29
31
  const DEFAULT_CODEX_CLIENT_VERSION = "0.162.1";
30
32
  const CODEX_DISCOVERED_ID_PATTERN = /^gpt-\d+(?:\.\d+)*(?:-[a-z0-9]+)+$/i;
31
33
  export const CODEX_BASE_MODELS: readonly CodexModel[] = [
32
- { id: "gpt-6-astra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
33
- { id: "gpt-6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
34
- { id: "gpt-6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
35
- { id: "gpt-5.6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
36
- { id: "gpt-5.6-terra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
37
- { id: "gpt-5.6-luna", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
34
+ {
35
+ id: "gpt-6-astra",
36
+ contextWindow: CODEX_CONTEXT_WINDOW,
37
+ reasoning: true,
38
+ multimodal: true,
39
+ tools: true,
40
+ source: "allowlist",
41
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
42
+ defaultReasoningEffort: "medium",
43
+ },
44
+ {
45
+ id: "gpt-6-sol",
46
+ contextWindow: CODEX_CONTEXT_WINDOW,
47
+ reasoning: true,
48
+ multimodal: true,
49
+ tools: true,
50
+ source: "allowlist",
51
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
52
+ defaultReasoningEffort: "medium",
53
+ },
54
+ {
55
+ id: "gpt-6-luna",
56
+ contextWindow: CODEX_CONTEXT_WINDOW,
57
+ reasoning: true,
58
+ multimodal: true,
59
+ tools: true,
60
+ source: "allowlist",
61
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
62
+ defaultReasoningEffort: "medium",
63
+ },
64
+ {
65
+ id: "gpt-5.6-sol",
66
+ contextWindow: CODEX_CONTEXT_WINDOW,
67
+ reasoning: true,
68
+ multimodal: true,
69
+ tools: true,
70
+ source: "allowlist",
71
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
72
+ defaultReasoningEffort: "medium",
73
+ },
74
+ {
75
+ id: "gpt-5.6-terra",
76
+ contextWindow: CODEX_CONTEXT_WINDOW,
77
+ reasoning: true,
78
+ multimodal: true,
79
+ tools: true,
80
+ source: "allowlist",
81
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
82
+ defaultReasoningEffort: "medium",
83
+ },
84
+ {
85
+ id: "gpt-5.6-luna",
86
+ contextWindow: CODEX_CONTEXT_WINDOW,
87
+ reasoning: true,
88
+ multimodal: true,
89
+ tools: true,
90
+ source: "allowlist",
91
+ reasoningEfforts: ["low", "medium", "high", "xhigh", "max"],
92
+ defaultReasoningEffort: "medium",
93
+ },
38
94
  ];
39
95
 
40
96
  let discoveredModels: CodexModel[] = [];
@@ -56,14 +112,17 @@ export function getCodexModel(model: string): CodexModel | undefined {
56
112
 
57
113
  export function getCodexModels(): CodexModel[] {
58
114
  const merged = new Map<string, CodexModel>();
59
- for (const entry of [...CODEX_BASE_MODELS, ...discoveredModels]) merged.set(entry.id, entry);
115
+ for (const entry of [...CODEX_BASE_MODELS, ...discoveredModels])
116
+ merged.set(entry.id, entry);
60
117
  return [...merged.values()];
61
118
  }
62
119
 
63
120
  export function isCodexProviderModelId(value: unknown): value is string {
64
- return typeof value === "string" &&
121
+ return (
122
+ typeof value === "string" &&
65
123
  isSafeModelId(value) &&
66
- CODEX_DISCOVERED_ID_PATTERN.test(value);
124
+ CODEX_DISCOVERED_ID_PATTERN.test(value)
125
+ );
67
126
  }
68
127
 
69
128
  export function setDiscoveredCodexModels(models: CodexModel[]): void {
@@ -71,28 +130,99 @@ export function setDiscoveredCodexModels(models: CodexModel[]): void {
71
130
  }
72
131
 
73
132
  function isSafeModelId(value: unknown): value is string {
74
- return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value);
133
+ return (
134
+ typeof value === "string" &&
135
+ /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value)
136
+ );
137
+ }
138
+
139
+ const REASONING_EFFORTS = new Set([
140
+ "none",
141
+ "minimal",
142
+ "low",
143
+ "medium",
144
+ "high",
145
+ "xhigh",
146
+ "max",
147
+ ]);
148
+ function reasoningMetadata(
149
+ record: Record<string, unknown>,
150
+ id: string,
151
+ ): Pick<CodexModel, "reasoningEfforts" | "defaultReasoningEffort"> {
152
+ if (record.reasoning === false) return { reasoningEfforts: [] };
153
+ const known = CODEX_BASE_MODELS.find((model) => model.id === id);
154
+ const raw =
155
+ record.supported_reasoning_levels ??
156
+ record.supported_reasoning_efforts ??
157
+ record.reasoning_efforts;
158
+ const efforts = Array.isArray(raw)
159
+ ? [
160
+ ...new Set(
161
+ raw.flatMap((value) => {
162
+ const effort =
163
+ typeof value === "string"
164
+ ? value
165
+ : value && typeof value === "object"
166
+ ? (value as Record<string, unknown>).effort
167
+ : null;
168
+ return typeof effort === "string" && REASONING_EFFORTS.has(effort)
169
+ ? [effort]
170
+ : [];
171
+ }),
172
+ ),
173
+ ]
174
+ : known?.reasoningEfforts;
175
+ const defaultEffort =
176
+ record.default_reasoning_level ??
177
+ record.default_reasoning_effort ??
178
+ known?.defaultReasoningEffort;
179
+ return {
180
+ ...(efforts ? { reasoningEfforts: efforts } : {}),
181
+ ...(typeof defaultEffort === "string" && efforts?.includes(defaultEffort)
182
+ ? { defaultReasoningEffort: defaultEffort }
183
+ : {}),
184
+ };
75
185
  }
76
186
 
77
187
  function parseModel(value: unknown): CodexModel | null {
78
188
  if (typeof value === "string") {
79
189
  return isCodexProviderModelId(value)
80
- ? { id: value, contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "discovered" }
190
+ ? {
191
+ id: value,
192
+ contextWindow: CODEX_CONTEXT_WINDOW,
193
+ reasoning: true,
194
+ multimodal: true,
195
+ tools: true,
196
+ source: "discovered",
197
+ ...reasoningMetadata({}, value),
198
+ }
81
199
  : null;
82
200
  }
83
201
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
84
202
  const record = value as Record<string, unknown>;
85
203
  const id = record.id ?? record.slug ?? record.model ?? record.name;
86
204
  if (!isCodexProviderModelId(id)) return null;
87
- const contextWindow = [record.context_window, record.contextWindow, record.context_length]
88
- .find((candidate) => typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0);
205
+ const contextWindow = [
206
+ record.context_window,
207
+ record.contextWindow,
208
+ record.context_length,
209
+ ].find(
210
+ (candidate) =>
211
+ typeof candidate === "number" &&
212
+ Number.isFinite(candidate) &&
213
+ candidate > 0,
214
+ );
89
215
  return {
90
216
  id,
91
- contextWindow: typeof contextWindow === "number" ? Math.min(contextWindow, CODEX_DISCOVERED_MAX_CONTEXT_WINDOW) : CODEX_CONTEXT_WINDOW,
217
+ contextWindow:
218
+ typeof contextWindow === "number"
219
+ ? Math.min(contextWindow, CODEX_DISCOVERED_MAX_CONTEXT_WINDOW)
220
+ : CODEX_CONTEXT_WINDOW,
92
221
  reasoning: record.reasoning !== false,
93
222
  multimodal: record.multimodal !== false && record.vision !== false,
94
223
  tools: record.tools !== false && record.tool_calling !== false,
95
224
  source: "discovered",
225
+ ...reasoningMetadata(record, id),
96
226
  };
97
227
  }
98
228
 
@@ -106,7 +236,10 @@ export async function fetchCodexCatalog(
106
236
  const endpoint = base.endsWith("/models") ? base : `${base}/models`;
107
237
  try {
108
238
  const url = new URL(endpoint);
109
- url.searchParams.set("client_version", process.env.CODEX_CLIENT_VERSION?.trim() || DEFAULT_CODEX_CLIENT_VERSION);
239
+ url.searchParams.set(
240
+ "client_version",
241
+ process.env.CODEX_CLIENT_VERSION?.trim() || DEFAULT_CODEX_CLIENT_VERSION,
242
+ );
110
243
  const headers: Record<string, string> = {
111
244
  Authorization: `Bearer ${token}`,
112
245
  Accept: "application/json",
@@ -119,9 +252,15 @@ export async function fetchCodexCatalog(
119
252
  dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
120
253
  } as RequestInit & { dispatcher?: unknown });
121
254
  if (!response.ok) return getCodexModels();
122
- const data = await response.json() as Record<string, unknown>;
123
- const raw = Array.isArray(data.data) ? data.data : Array.isArray(data.models) ? data.models : [];
124
- const parsed = raw.map(parseModel).filter((model): model is CodexModel => model !== null);
255
+ const data = (await response.json()) as Record<string, unknown>;
256
+ const raw = Array.isArray(data.data)
257
+ ? data.data
258
+ : Array.isArray(data.models)
259
+ ? data.models
260
+ : [];
261
+ const parsed = raw
262
+ .map(parseModel)
263
+ .filter((model): model is CodexModel => model !== null);
125
264
  if (parsed.length > 0) setDiscoveredCodexModels(parsed);
126
265
  } catch {
127
266
  // Discovery is optional; the safe allowlist remains available.
@@ -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(), account, refreshToken);
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
- config: Parameters<typeof saveAccountsConfig>[0],
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 accountConfig = config.accounts.find(
61
- (entry) => entry.email.toLowerCase() === email,
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
- quotaCache.set(key, { fetchedAt: Date.now(), snapshot });
234
- applyQuotaRows(account, snapshot);
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
- body: RequestBody,
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