tuxevil-rotator 4.0.0 → 4.1.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 (44) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +6 -1
  3. package/package.json +1 -1
  4. package/src/audio-transcription.ts +44 -4
  5. package/src/compat.ts +196 -222
  6. package/src/config-defaults.ts +5 -0
  7. package/src/dashboard-live.ts +10 -8
  8. package/src/dashboard-types.ts +39 -1
  9. package/src/dashboard.ts +156 -1
  10. package/src/model-catalog-revision.ts +17 -0
  11. package/src/model-catalog.ts +302 -0
  12. package/src/providers/adapter.ts +18 -0
  13. package/src/providers/google-antigravity/catalog.ts +190 -1
  14. package/src/providers/google-antigravity/forward.ts +2 -0
  15. package/src/providers/google-antigravity/index.ts +11 -0
  16. package/src/providers/google-antigravity/translators.ts +4 -0
  17. package/src/providers/ollama/index.ts +11 -1
  18. package/src/providers/ollama/quota-poll-store.ts +22 -1
  19. package/src/providers/ollama/quota.ts +95 -23
  20. package/src/providers/openai-codex/index.ts +18 -2
  21. package/src/providers/opencode-zen/index.ts +11 -2
  22. package/src/proxy.ts +143 -28
  23. package/src/rotator.ts +219 -10
  24. package/src/settings-repository.ts +36 -5
  25. package/src/types.ts +68 -26
  26. package/src/validators.ts +35 -0
  27. package/src/web/app.tsx +4 -0
  28. package/src/web/components/icons.tsx +29 -0
  29. package/src/web/components/ui.tsx +6 -1
  30. package/src/web/lib/accounts.ts +1 -0
  31. package/src/web/lib/attention.ts +12 -0
  32. package/src/web/lib/models.ts +279 -0
  33. package/src/web/lib/pools.ts +53 -9
  34. package/src/web/lib/status.ts +13 -3
  35. package/src/web/nav.ts +1 -0
  36. package/src/web/pages/AccountDetail.tsx +16 -2
  37. package/src/web/pages/Models.tsx +852 -0
  38. package/src/web/pages/Overview.tsx +31 -15
  39. package/src/web/pages/Usage.tsx +3 -3
  40. package/src/web/state/api.ts +18 -0
  41. package/src/web/state/model-catalog.ts +103 -0
  42. package/src/web/state/router.ts +24 -16
  43. package/src/web/state/store.ts +6 -6
  44. package/src/web/styles/app.css +294 -0
@@ -66,6 +66,8 @@ export interface TrafficMinute {
66
66
  export interface DashboardOverview {
67
67
  generatedAt: number;
68
68
  version: string;
69
+ /** Catalog/configuration changes are streamed independently of traffic. */
70
+ modelCatalogRevision?: string;
69
71
  proxyPort: number;
70
72
  startedAt: number;
71
73
  requestsPerRotation: number;
@@ -121,8 +123,9 @@ export interface DashboardSnapshot {
121
123
 
122
124
  export interface AccountsPatch {
123
125
  upsert: DashboardAccount[];
126
+ /** Account IDs (legacy producers without id use email). */
124
127
  remove: string[];
125
- /** Full email order, sent only when it changed. */
128
+ /** Full account-ID order, sent only when it changed. */
126
129
  order?: string[];
127
130
  }
128
131
 
@@ -190,3 +193,38 @@ export interface SessionInfo {
190
193
  authenticated: boolean;
191
194
  authRequired: boolean;
192
195
  }
196
+
197
+ // ── Models page (/api/catalog) ──────────────────────────────────────────
198
+
199
+ export interface CatalogProvider {
200
+ id: string;
201
+ name: string;
202
+ credentialKind: "oauth" | "api-key";
203
+ /** False when the operator turned the provider off. */
204
+ enabled: boolean;
205
+ }
206
+
207
+ export interface CatalogModelEntry {
208
+ providerId: string;
209
+ id: string;
210
+ contextWindow: number | null;
211
+ /** Quota row the model draws from (`account.quota[].modelKey`). */
212
+ quotaPool: string;
213
+ source: "catalog" | "discovered";
214
+ /** Why the model is off: its provider, its own switch, or waiting for review. */
215
+ offReason: "provider" | "model" | "review" | null;
216
+ /** The model's own switch, whatever its provider's switch says. */
217
+ modelSwitch: "on" | "off" | "review";
218
+ /** Requests for this id go to this provider. */
219
+ routed: boolean;
220
+ }
221
+
222
+ export interface ModelCatalogResponse {
223
+ ok: true;
224
+ /** Every provider, in routing order. */
225
+ providers: CatalogProvider[];
226
+ /** Every provider's models, in provider order. */
227
+ models: CatalogModelEntry[];
228
+ /** False when models a provider adds later stay off until turned on. */
229
+ autoEnableNewModels: boolean;
230
+ }
package/src/dashboard.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import type { IncomingMessage, ServerResponse } from "node:http";
5
5
  import type { Config } from "./types.js";
6
6
  import type { AccountRotator } from "./rotator.js";
7
- import type { SessionInfo } from "./dashboard-types.js";
7
+ import type { ModelCatalogResponse, SessionInfo } from "./dashboard-types.js";
8
8
  import { readLimitedBody } from "./body-limit.js";
9
9
  import {
10
10
  clearDashboardSessionCookie,
@@ -34,6 +34,8 @@ import {
34
34
  } from "./virtual-keys.js";
35
35
  import { getSpendLogs, getDailySpendSummary, getSpendByKey } from "./spend-logger.js";
36
36
  import { buildOpenAIModelCatalog } from "./compat.js";
37
+ import { getProviderOrder, isProviderTurnedOff, resolveModelRoute } from "./model-catalog.js";
38
+ import { getProviderAdapter } from "./providers/registry.js";
37
39
  import { logger } from "./logger.js";
38
40
 
39
41
  const dashboardLogger = logger.child("dashboard");
@@ -257,6 +259,159 @@ export async function serveAutoWarmupApi(
257
259
  res.end(JSON.stringify({ ok: true, changed, autoWarmupEnabled: enabled }));
258
260
  }
259
261
 
262
+ // ── Models page: providers, provider order and model switches ─────────
263
+
264
+ export function buildModelCatalogResponse(rotator: AccountRotator): ModelCatalogResponse {
265
+ const config = rotator.getConfig();
266
+ const models = rotator.getModelCatalog();
267
+ const routedTo = new Map<string, string | null>();
268
+ for (const model of models) {
269
+ const id = model.id.toLowerCase();
270
+ if (routedTo.has(id)) continue;
271
+ const route = resolveModelRoute(rotator, model.id);
272
+ routedTo.set(id, route.kind === "provider" ? route.providerId : null);
273
+ }
274
+ return {
275
+ ok: true,
276
+ providers: getProviderOrder(rotator).map((id) => {
277
+ const adapter = getProviderAdapter(id);
278
+ return {
279
+ id,
280
+ name: adapter.displayName,
281
+ credentialKind: adapter.credentialKind,
282
+ enabled: !isProviderTurnedOff(config, id),
283
+ };
284
+ }),
285
+ models: models.map((model) => ({
286
+ providerId: model.providerId,
287
+ id: model.id,
288
+ contextWindow: model.contextWindow,
289
+ quotaPool: model.quotaPool,
290
+ source: model.source,
291
+ offReason: model.offReason,
292
+ modelSwitch: model.modelSwitch,
293
+ routed: routedTo.get(model.id.toLowerCase()) === model.providerId,
294
+ })),
295
+ autoEnableNewModels: config.autoEnableNewModels ?? true,
296
+ };
297
+ }
298
+
299
+ function sendCatalogJson(res: ServerResponse, status: number, body: unknown): void {
300
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
301
+ res.end(JSON.stringify(body));
302
+ }
303
+
304
+ async function readJsonObject(req: IncomingMessage): Promise<Record<string, unknown> | null> {
305
+ try {
306
+ const raw = await readLimitedBody(req, 256 * 1024);
307
+ const parsed: unknown = raw.length > 0 ? JSON.parse(raw.toString("utf-8")) : {};
308
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
309
+ ? (parsed as Record<string, unknown>)
310
+ : null;
311
+ } catch {
312
+ return null;
313
+ }
314
+ }
315
+
316
+ const isStringList = (value: unknown): value is string[] =>
317
+ Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0);
318
+
319
+ /** The method a known /api/catalog path takes, for 405 answers. */
320
+ function catalogMethodFor(rest: string[]): string | null {
321
+ const toggle = rest.at(-1) === "on" || rest.at(-1) === "off";
322
+ if (rest.length === 0) return "GET";
323
+ if (rest.length === 1 && rest[0] === "refresh") return "POST";
324
+ if (rest.length === 1 && rest[0] === "provider-order") return "PUT";
325
+ if (toggle && ((rest[0] === "providers" && rest.length === 3) || (rest[0] === "models" && rest.length === 2) ||
326
+ (rest[0] === "new-models" && rest.length === 2) || (rest[0] === "accounts" && rest.length === 4))) return "POST";
327
+ return null;
328
+ }
329
+
330
+ /**
331
+ * /api/catalog routes. Every change answers with the updated catalog.
332
+ *
333
+ * GET /api/catalog
334
+ * POST /api/catalog/refresh
335
+ * POST /api/catalog/providers/:id/on|off
336
+ * PUT /api/catalog/provider-order { "order": ["ollama", ...] }
337
+ * POST /api/catalog/models/on|off { "models": ["ollama/gpt-oss:20b"] }
338
+ * POST /api/catalog/new-models/on|off
339
+ * POST /api/catalog/accounts/:accountId/:provider/on|off
340
+ * accountId is dashboard account.id; an unambiguous legacy email also works.
341
+ */
342
+ export async function serveCatalogApi(
343
+ req: IncomingMessage,
344
+ res: ServerResponse,
345
+ rotator: AccountRotator,
346
+ method: string,
347
+ pathname: string,
348
+ ): Promise<void> {
349
+ const rest = pathname.slice("/api/catalog".length).split("/").filter(Boolean).map((part) => {
350
+ try {
351
+ return decodeURIComponent(part);
352
+ } catch {
353
+ return part;
354
+ }
355
+ });
356
+ const toggle = rest.at(-1) === "on" ? true : rest.at(-1) === "off" ? false : null;
357
+ const done = () => sendCatalogJson(res, 200, buildModelCatalogResponse(rotator));
358
+ const fail = (status: number, error: string) => sendCatalogJson(res, status, { ok: false, error });
359
+
360
+ try {
361
+ if (method === "GET" && rest.length === 0) return done();
362
+
363
+ if (method === "POST" && rest.length === 1 && rest[0] === "refresh") {
364
+ await rotator.refreshModelCatalogs();
365
+ return done();
366
+ }
367
+
368
+ if (method === "POST" && rest[0] === "providers" && rest.length === 3 && toggle !== null) {
369
+ if (!(await rotator.setProviderEnabled(rest[1], toggle))) return fail(404, `Unknown provider "${rest[1]}"`);
370
+ return done();
371
+ }
372
+
373
+ if (method === "PUT" && rest.length === 1 && rest[0] === "provider-order") {
374
+ const body = await readJsonObject(req);
375
+ if (!body || !isStringList(body.order)) return fail(400, 'Send { "order": ["<provider id>", ...] }');
376
+ if (!(await rotator.setProviderOrder(body.order))) return fail(400, "The order names an unknown provider");
377
+ return done();
378
+ }
379
+
380
+ if (method === "POST" && rest[0] === "models" && rest.length === 2 && toggle !== null) {
381
+ const body = await readJsonObject(req);
382
+ if (!body || !isStringList(body.models) || body.models.length === 0) {
383
+ return fail(400, 'Send { "models": ["<provider>/<model>", ...] }');
384
+ }
385
+ if (!(await rotator.setModelsEnabled(body.models, toggle))) {
386
+ return fail(400, 'Each model must be "<provider>/<model>" with a known provider');
387
+ }
388
+ return done();
389
+ }
390
+
391
+ if (method === "POST" && rest[0] === "new-models" && rest.length === 2 && toggle !== null) {
392
+ await rotator.setAutoEnableNewModels(toggle);
393
+ return done();
394
+ }
395
+
396
+ if (method === "POST" && rest[0] === "accounts" && rest.length === 4 && toggle !== null) {
397
+ if (!(await rotator.setAccountProviderEnabled(rest[1], rest[2], toggle))) {
398
+ return fail(404, `No unique account with a ${rest[2]} credential matches ${rest[1]}`);
399
+ }
400
+ return done();
401
+ }
402
+
403
+ const allowed = catalogMethodFor(rest);
404
+ if (allowed) {
405
+ res.setHeader("Allow", allowed);
406
+ return fail(405, `Use ${allowed} for this path`);
407
+ }
408
+ return fail(404, "Not found");
409
+ } catch (err) {
410
+ dashboardLogger.error(`Catalog request failed: ${err}`);
411
+ return fail(500, "Internal server error");
412
+ }
413
+ }
414
+
260
415
  // ── Virtual Keys & Spend Logging REST API ────────────────────────────
261
416
 
262
417
  export async function serveGenerateVirtualKeyApi(
@@ -0,0 +1,17 @@
1
+ import { createHash } from "node:crypto";
2
+ import { getProviderOrder, isProviderTurnedOff, listCatalogModels, type ModelCatalogSource } from "./model-catalog.js";
3
+
4
+ /** A stable revision of the public catalog, independent of traffic and timers. */
5
+ export function getModelCatalogRevision(source: ModelCatalogSource): string {
6
+ const config = source.getConfig?.();
7
+ const state = {
8
+ providers: getProviderOrder(source).map((id) => ({
9
+ id,
10
+ enabled: !isProviderTurnedOff(config, id),
11
+ active: source.hasActiveProvider?.(id) ?? true,
12
+ })),
13
+ models: listCatalogModels(source),
14
+ autoEnableNewModels: config?.autoEnableNewModels ?? true,
15
+ };
16
+ return createHash("sha256").update(JSON.stringify(state)).digest("hex").slice(0, 32);
17
+ }
@@ -0,0 +1,302 @@
1
+ // Which provider serves a model, and which providers and models the operator
2
+ // turned off on the dashboard's Models page.
3
+ //
4
+ // Every provider lists the models it serves (ProviderAdapter.listModels). When
5
+ // more than one provider lists the same id, `providerOrder` decides which one
6
+ // gets the request. Ids no provider lists (aliases, upstream names, ids a
7
+ // provider claims by pattern) keep the fixed ownership checks in
8
+ // providers/registry.ts, so routing for them is unchanged.
9
+
10
+ import type { Config } from "./types.js";
11
+ import { applyModelAlias } from "./types.js";
12
+ import type { ProviderModel } from "./providers/adapter.js";
13
+ import {
14
+ findProviderForModel,
15
+ getProviderAdapter,
16
+ isKnownProvider,
17
+ } from "./providers/registry.js";
18
+
19
+ /**
20
+ * Priority for ids more than one provider lists, before the operator changes
21
+ * it. Matches the historical ownership order in findProviderForModel, so
22
+ * upgrading changes no routing.
23
+ */
24
+ export const DEFAULT_PROVIDER_ORDER: readonly string[] = [
25
+ "opencode-zen",
26
+ "openai-codex",
27
+ "ollama",
28
+ "google-antigravity",
29
+ ];
30
+
31
+ /** The rotator state the catalog reads. Test stubs may omit any of it. */
32
+ export interface ModelCatalogSource {
33
+ getConfig?(): Config;
34
+ getOllamaModels?(): string[];
35
+ getCodexModels?(): string[];
36
+ /** Whether an in-service account can use the provider right now. */
37
+ hasActiveProvider?(providerId: string): boolean;
38
+ }
39
+
40
+ export type ModelOffReason = "provider" | "model" | "review";
41
+
42
+ /** The model's own switch, regardless of its provider's switch. */
43
+ export type ModelSwitch = "on" | "off" | "review";
44
+
45
+ export interface CatalogModel extends ProviderModel {
46
+ providerId: string;
47
+ /** Why the model is off, or null when it is served. */
48
+ offReason: ModelOffReason | null;
49
+ modelSwitch: ModelSwitch;
50
+ }
51
+
52
+ export type ModelRoute =
53
+ /** Send the request to this provider. */
54
+ | { kind: "provider"; providerId: string; modelId: string }
55
+ /** Every provider that serves the model is turned off for it. */
56
+ | { kind: "off"; providerIds: string[] }
57
+ /** No provider lists the id; callers keep their own provider checks. */
58
+ | { kind: "unlisted" };
59
+
60
+ interface ModelSettings {
61
+ order: string[];
62
+ disabledProviders: Set<string>;
63
+ disabledModels: Set<string>;
64
+ autoEnableNewModels: boolean;
65
+ reviewedModels: Set<string>;
66
+ }
67
+
68
+ /** Config key for one provider's copy of a model: "ollama/gpt-oss:120b". */
69
+ export function modelKey(providerId: string, modelId: string): string {
70
+ return `${providerId}/${modelId}`;
71
+ }
72
+
73
+ /** Splits "provider/model"; model ids may themselves contain slashes. */
74
+ export function parseModelKey(key: string): { providerId: string; modelId: string } | null {
75
+ const slash = key.indexOf("/");
76
+ if (slash <= 0 || slash === key.length - 1) return null;
77
+ const providerId = key.slice(0, slash);
78
+ if (!isKnownProvider(providerId)) return null;
79
+ return { providerId, modelId: key.slice(slash + 1) };
80
+ }
81
+
82
+ const fold = (value: string) => value.trim().toLowerCase();
83
+
84
+ /** Configured order, limited to known providers, with any missing ones appended in default order. */
85
+ export function resolveProviderOrder(order: readonly string[] | undefined): string[] {
86
+ const out: string[] = [];
87
+ for (const id of [...(order ?? []), ...DEFAULT_PROVIDER_ORDER]) {
88
+ if (isKnownProvider(id) && !out.includes(id)) out.push(id);
89
+ }
90
+ return out;
91
+ }
92
+
93
+ function readSettings(config: Partial<Config> | undefined): ModelSettings {
94
+ return {
95
+ order: resolveProviderOrder(config?.providerOrder),
96
+ disabledProviders: new Set(config?.disabledProviders ?? []),
97
+ disabledModels: new Set((config?.disabledModels ?? []).map(fold)),
98
+ autoEnableNewModels: config?.autoEnableNewModels ?? true,
99
+ reviewedModels: new Set((config?.reviewedModels ?? []).map(fold)),
100
+ };
101
+ }
102
+
103
+ function modelSwitchFor(settings: ModelSettings, providerId: string, modelId: string): ModelSwitch {
104
+ const key = fold(modelKey(providerId, modelId));
105
+ if (settings.disabledModels.has(key)) return "off";
106
+ if (!settings.autoEnableNewModels && !settings.reviewedModels.has(key)) return "review";
107
+ return "on";
108
+ }
109
+
110
+ function offReasonFor(settings: ModelSettings, providerId: string, modelId: string): ModelOffReason | null {
111
+ if (settings.disabledProviders.has(providerId)) return "provider";
112
+ const own = modelSwitchFor(settings, providerId, modelId);
113
+ return own === "off" ? "model" : own === "review" ? "review" : null;
114
+ }
115
+
116
+ function listFor(source: ModelCatalogSource, settings: ModelSettings): CatalogModel[] {
117
+ const context = {
118
+ ollamaModels: source.getOllamaModels?.() ?? [],
119
+ codexModels: source.getCodexModels?.() ?? [],
120
+ };
121
+ const out: CatalogModel[] = [];
122
+ for (const providerId of settings.order) {
123
+ for (const model of getProviderAdapter(providerId).listModels(context)) {
124
+ out.push({
125
+ ...model,
126
+ providerId,
127
+ offReason: offReasonFor(settings, providerId, model.id),
128
+ modelSwitch: modelSwitchFor(settings, providerId, model.id),
129
+ });
130
+ }
131
+ }
132
+ return out;
133
+ }
134
+
135
+ /** Every provider's models, in provider order, with whether each is off. */
136
+ export function listCatalogModels(source: ModelCatalogSource): CatalogModel[] {
137
+ return listFor(source, readSettings(source.getConfig?.()));
138
+ }
139
+
140
+ /** Provider ids in routing order. */
141
+ export function getProviderOrder(source: ModelCatalogSource): string[] {
142
+ return resolveProviderOrder(source.getConfig?.()?.providerOrder);
143
+ }
144
+
145
+ export function isProviderTurnedOff(config: Partial<Config> | undefined, providerId: string): boolean {
146
+ return (config?.disabledProviders ?? []).includes(providerId);
147
+ }
148
+
149
+ /** Whether one provider's copy of a model may be listed and served. */
150
+ export function isModelServed(source: ModelCatalogSource, providerId: string, modelId: string): boolean {
151
+ return offReasonFor(readSettings(source.getConfig?.()), providerId, modelId) === null;
152
+ }
153
+
154
+ /**
155
+ * Decide which provider serves a requested model id.
156
+ *
157
+ * Exact ids a provider lists win. When several providers list it, the first
158
+ * one in provider order that is on and has a usable account gets it; if none
159
+ * has an account, the first one that is on still gets it so the request fails
160
+ * the usual way ("no account available") instead of with a different error.
161
+ */
162
+ export function resolveModelRoute(source: ModelCatalogSource, model: string): ModelRoute {
163
+ const settings = readSettings(source.getConfig?.());
164
+ const catalog = listFor(source, settings);
165
+ const lookup = (id: string) => {
166
+ const wanted = fold(id);
167
+ return catalog.filter((entry) => fold(entry.id) === wanted);
168
+ };
169
+
170
+ let listed = lookup(model);
171
+ if (listed.length === 0) {
172
+ // Operator-facing aliases ("gpt-oss-120b") stand for a listed upstream id.
173
+ const alias = applyModelAlias(model);
174
+ if (fold(alias) !== fold(model)) listed = lookup(alias);
175
+ }
176
+
177
+ if (listed.length === 0) {
178
+ const owner = findProviderForModel(model, {
179
+ ollamaModels: new Set(source.getOllamaModels?.() ?? []),
180
+ codexModels: new Set(source.getCodexModels?.() ?? []),
181
+ });
182
+ if (owner && isTurnedOff(settings, catalog, owner.id, model)) {
183
+ return { kind: "off", providerIds: [owner.id] };
184
+ }
185
+ return { kind: "unlisted" };
186
+ }
187
+
188
+ const on = listed.filter((entry) => entry.offReason === null);
189
+ if (on.length === 0) {
190
+ return { kind: "off", providerIds: [...new Set(listed.map((entry) => entry.providerId))] };
191
+ }
192
+ const chosen = on.find((entry) => source.hasActiveProvider?.(entry.providerId) ?? true) ?? on[0];
193
+ return { kind: "provider", providerId: chosen.providerId, modelId: chosen.id };
194
+ }
195
+
196
+ /**
197
+ * Whether `providerId` may not serve `model`: the provider is off, the model's
198
+ * key is turned off, or the provider lists it and it waits for review. Unlisted
199
+ * ids are checked against explicit keys only, since review applies to listed
200
+ * models.
201
+ */
202
+ function isTurnedOff(settings: ModelSettings, catalog: CatalogModel[], providerId: string, model: string): boolean {
203
+ if (settings.disabledProviders.has(providerId)) return true;
204
+ const wanted = fold(model);
205
+ const listed = catalog.find((entry) => entry.providerId === providerId && fold(entry.id) === wanted);
206
+ if (listed) return listed.offReason !== null;
207
+ return settings.disabledModels.has(fold(modelKey(providerId, model)));
208
+ }
209
+
210
+ /** The parts of a request the switches are checked against. */
211
+ export interface RequestModels {
212
+ /** Id sent upstream (after aliasing). */
213
+ model: string;
214
+ /** Concrete model or effort alias requested before target selection. */
215
+ requestedModel?: string;
216
+ /** Catalog id the request resolved to before upstream aliasing, if different. */
217
+ catalogModel?: string;
218
+ /** Provider already chosen for the request. */
219
+ providerId?: string;
220
+ }
221
+
222
+ /**
223
+ * Whether a request about to be sent targets a model or provider that is
224
+ * turned off. Checks the requested id, selected catalog id, and upstream id
225
+ * (plus their upstream aliases), against the pinned provider when there is
226
+ * one and against routing otherwise.
227
+ */
228
+ export function isRequestOff(source: ModelCatalogSource, request: RequestModels): boolean {
229
+ const ids = new Set<string>();
230
+ for (const id of [request.requestedModel, request.catalogModel, request.model]) {
231
+ if (!id) continue;
232
+ ids.add(id);
233
+ ids.add(applyModelAlias(id));
234
+ }
235
+ if (request.providerId) {
236
+ const settings = readSettings(source.getConfig?.());
237
+ const catalog = listFor(source, settings);
238
+ return [...ids].some((id) => isTurnedOff(settings, catalog, request.providerId!, id));
239
+ }
240
+ return [...ids].some((id) => resolveModelRoute(source, id).kind === "off");
241
+ }
242
+
243
+ /** Whether one provider may send this model upstream (benchmarks, kickstarts). */
244
+ export function isProviderModelOff(source: ModelCatalogSource, providerId: string, model: string): boolean {
245
+ return isRequestOff(source, { model, providerId });
246
+ }
247
+
248
+ /** Provider that serves a model, or null to fall back to the caller's own checks. */
249
+ export function routedProviderId(source: ModelCatalogSource, model: string): string | null {
250
+ const route = resolveModelRoute(source, model);
251
+ return route.kind === "provider" ? route.providerId : null;
252
+ }
253
+
254
+ /** Client-facing explanation for a request to a model that is turned off. */
255
+ export function modelOffMessage(model: string): string {
256
+ return `The model '${model}' is turned off on this rotator. Turn it back on from the dashboard's Models page.`;
257
+ }
258
+
259
+ // ── Settings updates ─────────────────────────────────────────────────────
260
+ // Each returns only the config fields it changes.
261
+
262
+ type ModelConfigPatch = Pick<
263
+ Config,
264
+ "providerOrder" | "disabledProviders" | "disabledModels" | "autoEnableNewModels" | "reviewedModels"
265
+ >;
266
+
267
+ export function setProviderTurnedOff(config: Config, providerId: string, off: boolean): Partial<ModelConfigPatch> {
268
+ const rest = (config.disabledProviders ?? []).filter((id) => id !== providerId);
269
+ return { disabledProviders: off ? [...rest, providerId] : rest };
270
+ }
271
+
272
+ export function setModelsTurnedOff(config: Config, keys: string[], off: boolean): Partial<ModelConfigPatch> {
273
+ const folded = new Set(keys.map(fold));
274
+ const disabled = (config.disabledModels ?? []).filter((key) => !folded.has(fold(key)));
275
+ const patch: Partial<ModelConfigPatch> = { disabledModels: off ? [...disabled, ...keys] : disabled };
276
+ if (config.autoEnableNewModels === false) {
277
+ // A decision either way means the model has been reviewed.
278
+ const reviewed = config.reviewedModels ?? [];
279
+ const known = new Set(reviewed.map(fold));
280
+ patch.reviewedModels = [...reviewed, ...keys.filter((key) => !known.has(fold(key)))];
281
+ }
282
+ return patch;
283
+ }
284
+
285
+ /**
286
+ * Turning automatic enabling off records every model listed now as reviewed,
287
+ * so only models found later wait for review. Turning it back on forgets the
288
+ * list, and anything waiting is served.
289
+ */
290
+ export function setAutoEnableNewModels(
291
+ source: ModelCatalogSource,
292
+ on: boolean,
293
+ ): Partial<ModelConfigPatch> {
294
+ if (on) return { autoEnableNewModels: true, reviewedModels: undefined };
295
+ const config = source.getConfig?.();
296
+ if (config?.autoEnableNewModels === false) return {};
297
+ const current = listFor(source, readSettings({ ...config, autoEnableNewModels: true }));
298
+ return {
299
+ autoEnableNewModels: false,
300
+ reviewedModels: current.map((entry) => modelKey(entry.providerId, entry.id)),
301
+ };
302
+ }
@@ -65,6 +65,22 @@ export interface TierRanking {
65
65
  [tier: string]: number;
66
66
  }
67
67
 
68
+ /** One model a provider can serve, as listed on the dashboard's Models page. */
69
+ export interface ProviderModel {
70
+ id: string;
71
+ contextWindow: number | null;
72
+ /** Quota row the model draws from (`account.quota[].modelKey`). */
73
+ quotaPool: string;
74
+ /** Built into the rotator, or found at runtime from the provider. */
75
+ source: "catalog" | "discovered";
76
+ }
77
+
78
+ /** Model ids the rotator discovers at runtime for providers without a fixed list. */
79
+ export interface ModelListContext {
80
+ ollamaModels: readonly string[];
81
+ codexModels: readonly string[];
82
+ }
83
+
68
84
  export interface ProviderFeatures {
69
85
  /** Project/model circuit breakers on repeated 429s (opt-in via config). */
70
86
  circuitBreakers: boolean;
@@ -141,6 +157,8 @@ export interface ProviderAdapter {
141
157
  clearQuotaCache?(account: AccountRuntime): void;
142
158
 
143
159
  // --- Catalog / helpers ---
160
+ /** Every model this provider can serve right now. */
161
+ listModels(context: ModelListContext): ProviderModel[];
144
162
  /** Whether a model belongs to this provider. */
145
163
  ownsModel?(
146
164
  model: string,