tuxevil-rotator 4.0.0 → 4.2.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 (52) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +8 -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/config-overrides.ts +16 -0
  8. package/src/dashboard-live.ts +10 -8
  9. package/src/dashboard-types.ts +94 -1
  10. package/src/dashboard.ts +194 -1
  11. package/src/effort-levels.ts +43 -0
  12. package/src/effort-routing.ts +304 -0
  13. package/src/index.ts +2 -5
  14. package/src/model-catalog-revision.ts +20 -0
  15. package/src/model-catalog.ts +304 -0
  16. package/src/providers/adapter.ts +18 -0
  17. package/src/providers/google-antigravity/catalog.ts +190 -1
  18. package/src/providers/google-antigravity/forward.ts +2 -0
  19. package/src/providers/google-antigravity/index.ts +11 -0
  20. package/src/providers/google-antigravity/translators.ts +67 -14
  21. package/src/providers/ollama/index.ts +11 -1
  22. package/src/providers/ollama/quota-poll-store.ts +22 -1
  23. package/src/providers/ollama/quota.ts +95 -23
  24. package/src/providers/openai-codex/catalog.ts +9 -4
  25. package/src/providers/openai-codex/index.ts +18 -2
  26. package/src/providers/opencode-zen/index.ts +11 -2
  27. package/src/proxy.ts +143 -28
  28. package/src/rotator.ts +296 -21
  29. package/src/settings-repository.ts +36 -5
  30. package/src/types.ts +72 -26
  31. package/src/validators.ts +37 -1
  32. package/src/web/app.tsx +6 -1
  33. package/src/web/components/icons.tsx +29 -0
  34. package/src/web/components/overlays.tsx +13 -1
  35. package/src/web/components/ui.tsx +6 -1
  36. package/src/web/lib/accounts.ts +1 -0
  37. package/src/web/lib/attention.ts +12 -0
  38. package/src/web/lib/effort.ts +407 -0
  39. package/src/web/lib/models.ts +284 -0
  40. package/src/web/lib/pools.ts +53 -9
  41. package/src/web/lib/status.ts +13 -3
  42. package/src/web/nav.ts +1 -0
  43. package/src/web/pages/AccountDetail.tsx +16 -2
  44. package/src/web/pages/EffortRouting.tsx +1130 -0
  45. package/src/web/pages/Models.tsx +888 -0
  46. package/src/web/pages/Overview.tsx +31 -15
  47. package/src/web/pages/Usage.tsx +3 -3
  48. package/src/web/state/api.ts +31 -0
  49. package/src/web/state/model-catalog.ts +103 -0
  50. package/src/web/state/router.ts +150 -19
  51. package/src/web/state/store.ts +6 -6
  52. package/src/web/styles/app.css +854 -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,93 @@ 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
+ /** Set when an effort-routed model ID sends one of its effort levels here. */
221
+ effortRoute?: { alias: string; effort: string };
222
+ }
223
+
224
+ /** One effort level of an effort-routed model ID. */
225
+ export interface CatalogEffortTarget {
226
+ /** Lower-cased level name, e.g. "high". */
227
+ effort: string;
228
+ /** Google Antigravity model the level routes to. */
229
+ model: string;
230
+ /** False when no provider lists the model right now. */
231
+ known: boolean;
232
+ /** False when a request for this level would be refused (model off or waiting for review). */
233
+ served: boolean;
234
+ }
235
+
236
+ /**
237
+ * live: listed in /v1/models and every level is served.
238
+ * partial: listed, but some levels are refused.
239
+ * hidden: not listed (default model refused or missing, or another provider owns the ID).
240
+ * off: its own switch is off.
241
+ * provider-off: Google Antigravity is off.
242
+ */
243
+ export type EffortRouteStatus = "live" | "partial" | "hidden" | "off" | "provider-off";
244
+
245
+ /** A model ID clients call that picks a target from the request's effort. */
246
+ export interface CatalogEffortRoute {
247
+ alias: string;
248
+ defaultEffort: string;
249
+ /** Standard levels first (minimal to max), then custom ones. */
250
+ targets: CatalogEffortTarget[];
251
+ /** Its own switch: off rejects every request for the ID. */
252
+ enabled: boolean;
253
+ /** Clients see it in /v1/models. */
254
+ listed: boolean;
255
+ /** Another provider lists the same ID and gets its requests instead. */
256
+ shadowedBy: string | null;
257
+ status: EffortRouteStatus;
258
+ }
259
+
260
+ /** Effort variants of one model family that no effort route uses yet. */
261
+ export interface CatalogEffortSuggestion {
262
+ alias: string;
263
+ targets: Array<{ effort: string; model: string }>;
264
+ }
265
+
266
+ export interface ModelCatalogResponse {
267
+ ok: true;
268
+ /** Every provider, in routing order. */
269
+ providers: CatalogProvider[];
270
+ /** Every provider's models, in provider order. */
271
+ models: CatalogModelEntry[];
272
+ /** False when models a provider adds later stay off until turned on. */
273
+ autoEnableNewModels: boolean;
274
+ /** Configured effort routes, in config order. */
275
+ effortRoutes: CatalogEffortRoute[];
276
+ /** Model families that could become effort routes. */
277
+ effortSuggestions: CatalogEffortSuggestion[];
278
+ }
279
+
280
+ /** Body of a refused effort route change; field keys are "alias", "defaultEffort", "targets" or "targets.<level>". */
281
+ export interface EffortRouteErrorResponse {
282
+ ok: false;
283
+ error: string;
284
+ fieldErrors?: Record<string, string>;
285
+ }
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,9 @@ 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 { describeEffortRoutes, effortRouteTargets, suggestEffortRoutes, type EffortRoutePlan } from "./effort-routing.js";
39
+ import { getProviderAdapter } from "./providers/registry.js";
37
40
  import { logger } from "./logger.js";
38
41
 
39
42
  const dashboardLogger = logger.child("dashboard");
@@ -257,6 +260,196 @@ export async function serveAutoWarmupApi(
257
260
  res.end(JSON.stringify({ ok: true, changed, autoWarmupEnabled: enabled }));
258
261
  }
259
262
 
263
+ // ── Models page: providers, provider order and model switches ─────────
264
+
265
+ export function buildModelCatalogResponse(rotator: AccountRotator): ModelCatalogResponse {
266
+ const config = rotator.getConfig();
267
+ const models = rotator.getModelCatalog();
268
+ const routedTo = new Map<string, string | null>();
269
+ for (const model of models) {
270
+ const id = model.id.toLowerCase();
271
+ if (routedTo.has(id)) continue;
272
+ const route = resolveModelRoute(rotator, model.id);
273
+ routedTo.set(id, route.kind === "provider" ? route.providerId : null);
274
+ }
275
+ const effortTargets = effortRouteTargets(config);
276
+ const listed = config.effortRouting
277
+ ? new Set(buildOpenAIModelCatalog(rotator).map((entry) => entry.id.toLowerCase()))
278
+ : new Set<string>();
279
+ return {
280
+ ok: true,
281
+ providers: getProviderOrder(rotator).map((id) => {
282
+ const adapter = getProviderAdapter(id);
283
+ return {
284
+ id,
285
+ name: adapter.displayName,
286
+ credentialKind: adapter.credentialKind,
287
+ enabled: !isProviderTurnedOff(config, id),
288
+ };
289
+ }),
290
+ models: models.map((model) => ({
291
+ providerId: model.providerId,
292
+ id: model.id,
293
+ contextWindow: model.contextWindow,
294
+ quotaPool: model.quotaPool,
295
+ source: model.source,
296
+ offReason: model.offReason,
297
+ modelSwitch: model.modelSwitch,
298
+ routed: routedTo.get(model.id.toLowerCase()) === model.providerId,
299
+ ...(model.providerId === "google-antigravity" && effortTargets.has(model.id.toLowerCase())
300
+ ? { effortRoute: effortTargets.get(model.id.toLowerCase()) }
301
+ : {}),
302
+ })),
303
+ autoEnableNewModels: config.autoEnableNewModels ?? true,
304
+ effortRoutes: describeEffortRoutes(rotator, (alias) => listed.has(alias.toLowerCase())),
305
+ effortSuggestions: suggestEffortRoutes(rotator),
306
+ };
307
+ }
308
+
309
+ function sendCatalogJson(res: ServerResponse, status: number, body: unknown): void {
310
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
311
+ res.end(JSON.stringify(body));
312
+ }
313
+
314
+ async function readJsonObject(req: IncomingMessage): Promise<Record<string, unknown> | null> {
315
+ try {
316
+ const raw = await readLimitedBody(req, 256 * 1024);
317
+ const parsed: unknown = raw.length > 0 ? JSON.parse(raw.toString("utf-8")) : {};
318
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
319
+ ? (parsed as Record<string, unknown>)
320
+ : null;
321
+ } catch {
322
+ return null;
323
+ }
324
+ }
325
+
326
+ const isStringList = (value: unknown): value is string[] =>
327
+ Array.isArray(value) && value.every((item) => typeof item === "string" && item.length > 0);
328
+
329
+ /** The method a known /api/catalog path takes, for 405 answers. */
330
+ function catalogMethodFor(rest: string[]): string | null {
331
+ const toggle = rest.at(-1) === "on" || rest.at(-1) === "off";
332
+ if (rest.length === 0) return "GET";
333
+ if (rest.length === 1 && rest[0] === "refresh") return "POST";
334
+ if (rest.length === 1 && rest[0] === "provider-order") return "PUT";
335
+ if (toggle && ((rest[0] === "providers" && rest.length === 3) || (rest[0] === "models" && rest.length === 2) ||
336
+ (rest[0] === "new-models" && rest.length === 2) || (rest[0] === "accounts" && rest.length === 4))) return "POST";
337
+ if (rest[0] === "effort-routes" && rest.length === 1) return "POST";
338
+ if (rest[0] === "effort-routes" && rest.length === 2) return "PUT, DELETE";
339
+ return null;
340
+ }
341
+
342
+ /**
343
+ * /api/catalog routes. Every change answers with the updated catalog.
344
+ *
345
+ * GET /api/catalog
346
+ * POST /api/catalog/refresh
347
+ * POST /api/catalog/providers/:id/on|off
348
+ * PUT /api/catalog/provider-order { "order": ["ollama", ...] }
349
+ * POST /api/catalog/models/on|off { "models": ["ollama/gpt-oss:20b"] }
350
+ * POST /api/catalog/new-models/on|off
351
+ * POST /api/catalog/accounts/:accountId/:provider/on|off
352
+ * accountId is dashboard account.id; an unambiguous legacy email also works.
353
+ * POST /api/catalog/effort-routes { "alias", "defaultEffort", "targets": { "<level>": "<model>" } }
354
+ * PUT /api/catalog/effort-routes/:alias same body; "alias" renames the route
355
+ * DELETE /api/catalog/effort-routes/:alias
356
+ * A refused change answers { ok: false, error, fieldErrors? } (EffortRouteErrorResponse).
357
+ */
358
+ export async function serveCatalogApi(
359
+ req: IncomingMessage,
360
+ res: ServerResponse,
361
+ rotator: AccountRotator,
362
+ method: string,
363
+ pathname: string,
364
+ ): Promise<void> {
365
+ const rest = pathname.slice("/api/catalog".length).split("/").filter(Boolean).map((part) => {
366
+ try {
367
+ return decodeURIComponent(part);
368
+ } catch {
369
+ return part;
370
+ }
371
+ });
372
+ const toggle = rest.at(-1) === "on" ? true : rest.at(-1) === "off" ? false : null;
373
+ const done = () => sendCatalogJson(res, 200, buildModelCatalogResponse(rotator));
374
+ const fail = (status: number, error: string) => sendCatalogJson(res, status, { ok: false, error });
375
+
376
+ try {
377
+ if (method === "GET" && rest.length === 0) return done();
378
+
379
+ if (method === "POST" && rest.length === 1 && rest[0] === "refresh") {
380
+ await rotator.refreshModelCatalogs();
381
+ return done();
382
+ }
383
+
384
+ if (method === "POST" && rest[0] === "providers" && rest.length === 3 && toggle !== null) {
385
+ if (!(await rotator.setProviderEnabled(rest[1], toggle))) return fail(404, `Unknown provider "${rest[1]}"`);
386
+ return done();
387
+ }
388
+
389
+ if (method === "PUT" && rest.length === 1 && rest[0] === "provider-order") {
390
+ const body = await readJsonObject(req);
391
+ if (!body || !isStringList(body.order)) return fail(400, 'Send { "order": ["<provider id>", ...] }');
392
+ if (!(await rotator.setProviderOrder(body.order))) return fail(400, "The order names an unknown provider");
393
+ return done();
394
+ }
395
+
396
+ if (method === "POST" && rest[0] === "models" && rest.length === 2 && toggle !== null) {
397
+ const body = await readJsonObject(req);
398
+ if (!body || !isStringList(body.models) || body.models.length === 0) {
399
+ return fail(400, 'Send { "models": ["<provider>/<model>", ...] }');
400
+ }
401
+ if (!(await rotator.setModelsEnabled(body.models, toggle))) {
402
+ return fail(400, 'Each model must be "<provider>/<model>" with a known provider');
403
+ }
404
+ return done();
405
+ }
406
+
407
+ if (method === "POST" && rest[0] === "new-models" && rest.length === 2 && toggle !== null) {
408
+ await rotator.setAutoEnableNewModels(toggle);
409
+ return done();
410
+ }
411
+
412
+ if (rest[0] === "effort-routes") {
413
+ const answer = (plan: EffortRoutePlan) =>
414
+ plan.ok
415
+ ? done()
416
+ : sendCatalogJson(res, plan.status, {
417
+ ok: false,
418
+ error: plan.error,
419
+ ...(plan.fieldErrors ? { fieldErrors: plan.fieldErrors } : {}),
420
+ });
421
+ if (method === "POST" && rest.length === 1) {
422
+ const body = await readJsonObject(req);
423
+ return answer(await rotator.saveEffortRoute(null, body));
424
+ }
425
+ if (method === "PUT" && rest.length === 2) {
426
+ const body = await readJsonObject(req);
427
+ return answer(await rotator.saveEffortRoute(rest[1], body));
428
+ }
429
+ if (method === "DELETE" && rest.length === 2) {
430
+ return answer(await rotator.deleteEffortRoute(rest[1]));
431
+ }
432
+ }
433
+
434
+ if (method === "POST" && rest[0] === "accounts" && rest.length === 4 && toggle !== null) {
435
+ if (!(await rotator.setAccountProviderEnabled(rest[1], rest[2], toggle))) {
436
+ return fail(404, `No unique account with a ${rest[2]} credential matches ${rest[1]}`);
437
+ }
438
+ return done();
439
+ }
440
+
441
+ const allowed = catalogMethodFor(rest);
442
+ if (allowed) {
443
+ res.setHeader("Allow", allowed);
444
+ return fail(405, `Use ${allowed} for this path`);
445
+ }
446
+ return fail(404, "Not found");
447
+ } catch (err) {
448
+ dashboardLogger.error(`Catalog request failed: ${err}`);
449
+ return fail(500, "Internal server error");
450
+ }
451
+ }
452
+
260
453
  // ── Virtual Keys & Spend Logging REST API ────────────────────────────
261
454
 
262
455
  export async function serveGenerateVirtualKeyApi(
@@ -0,0 +1,43 @@
1
+ // Effort levels and alias rules shared by the effort router and the dashboard's editor.
2
+ // Keep this module free of imports: the browser bundle uses it too.
3
+
4
+ /** Standard effort levels, lowest first. Custom level names sort after these. */
5
+ export const EFFORT_LEVELS = ["minimal", "low", "medium", "high", "xhigh", "max"] as const;
6
+
7
+ /**
8
+ * How an Anthropic Messages request without `output_config.effort` picks a
9
+ * level from `thinking.budget_tokens`: the first bucket whose bound the budget
10
+ * is below. Claude Code's "think" (4,000) lands on medium and "ultrathink"
11
+ * (31,999) on high.
12
+ */
13
+ export const CLAUDE_THINKING_BUDGET_EFFORTS: ReadonlyArray<{ below: number; effort: string }> = [
14
+ { below: 4_000, effort: "low" },
15
+ { below: 16_000, effort: "medium" },
16
+ { below: Number.POSITIVE_INFINITY, effort: "high" },
17
+ ];
18
+
19
+ /** Level an Anthropic Messages request with `thinking: { type: "disabled" }` asks for. */
20
+ export const CLAUDE_THINKING_DISABLED_EFFORT = "low";
21
+
22
+ /** Standard levels first, in order, then custom names in their given order. */
23
+ export function orderEffortLevels(levels: Iterable<string>): string[] {
24
+ const all = [...levels];
25
+ const standard: readonly string[] = EFFORT_LEVELS;
26
+ return [
27
+ ...EFFORT_LEVELS.filter((level) => all.includes(level)),
28
+ ...all.filter((level) => !standard.includes(level)),
29
+ ];
30
+ }
31
+
32
+ /**
33
+ * Why `alias` can never name an effort route, or null. The compatibility
34
+ * endpoints answer `auto` with automatic model selection before effort routing
35
+ * runs, and browsers resolve `.` and `..` out of the dashboard's URLs, so such
36
+ * a route could neither serve requests nor be edited.
37
+ */
38
+ export function reservedEffortAlias(alias: string): string | null {
39
+ const id = alias.trim();
40
+ if (id.toLowerCase() === "auto") return `${id} is reserved for automatic model selection. Pick another ID.`;
41
+ if (id === "." || id === "..") return `“${id}” can't be a model ID. Pick another one.`;
42
+ return null;
43
+ }
@@ -0,0 +1,304 @@
1
+ // Effort routing as the dashboard's Models page sees it: which effort-routed
2
+ // model IDs exist and whether clients can use them, which model families
3
+ // could become one, and edits checked so the stored config always loads.
4
+ //
5
+ // Each planner returns a config patch instead of saving it, so the rotator
6
+ // and test stubs apply edits the same way as the other Models page switches.
7
+
8
+ import type {
9
+ CatalogEffortRoute,
10
+ CatalogEffortSuggestion,
11
+ CatalogEffortTarget,
12
+ EffortRouteStatus,
13
+ } from "./dashboard-types.js";
14
+ import { EFFORT_LEVELS, orderEffortLevels, reservedEffortAlias } from "./effort-levels.js";
15
+ import {
16
+ isProviderTurnedOff,
17
+ isRequestOff,
18
+ listCatalogModels,
19
+ modelKey,
20
+ resolveModelRoute,
21
+ type ModelCatalogSource,
22
+ } from "./model-catalog.js";
23
+ import { getProviderAdapter, isKnownProvider } from "./providers/registry.js";
24
+ import type { Config, EffortRoutingRule } from "./types.js";
25
+ import { applyModelAlias } from "./types.js";
26
+ import { isKnownNonGoogleModel, validateConfig } from "./validators.js";
27
+
28
+ const ANTIGRAVITY = "google-antigravity";
29
+ const EFFORT_SUFFIX = new RegExp(`^(.+)-(${EFFORT_LEVELS.join("|")})$`, "i");
30
+
31
+ const fold = (value: string) => value.trim().toLowerCase();
32
+
33
+ function providerName(providerId: string): string {
34
+ return isKnownProvider(providerId) ? getProviderAdapter(providerId).displayName : providerId;
35
+ }
36
+
37
+ function antigravityModels(source: ModelCatalogSource) {
38
+ return listCatalogModels(source).filter((model) => model.providerId === ANTIGRAVITY);
39
+ }
40
+
41
+ /** Targets with lower-cased levels, standard levels first. */
42
+ function orderedTargets(rule: EffortRoutingRule): Array<{ effort: string; model: string }> {
43
+ const byLevel = new Map<string, string>();
44
+ for (const [level, model] of Object.entries(rule.targets ?? {})) {
45
+ if (typeof model === "string") byLevel.set(fold(level), model.trim());
46
+ }
47
+ return orderEffortLevels(byLevel.keys()).map((effort) => ({ effort, model: byLevel.get(effort)! }));
48
+ }
49
+
50
+ /** The key that turns an effort-routed ID off, as the Models page switches store it. */
51
+ export function effortRouteKey(alias: string): string {
52
+ return modelKey(ANTIGRAVITY, alias);
53
+ }
54
+
55
+ /**
56
+ * Configured effort routes with what clients get from each. `isListed` says
57
+ * whether /v1/models shows the ID; the caller passes it so the answer comes
58
+ * from the same code that builds that list.
59
+ */
60
+ export function describeEffortRoutes(
61
+ source: ModelCatalogSource,
62
+ isListed: (alias: string) => boolean,
63
+ ): CatalogEffortRoute[] {
64
+ const config = source.getConfig?.();
65
+ const rules = config?.effortRouting ?? {};
66
+ const known = new Set(antigravityModels(source).map((model) => fold(model.id)));
67
+ const disabled = new Set((config?.disabledModels ?? []).map(fold));
68
+ const providerOff = isProviderTurnedOff(config, ANTIGRAVITY);
69
+
70
+ return Object.entries(rules).map(([rawAlias, rule]) => {
71
+ const alias = rawAlias.trim();
72
+ const targets: CatalogEffortTarget[] = orderedTargets(rule).map(({ effort, model }) => ({
73
+ effort,
74
+ model,
75
+ known: known.has(fold(model)),
76
+ served:
77
+ known.has(fold(model)) &&
78
+ !isRequestOff(source, { catalogModel: model, model: applyModelAlias(model), providerId: ANTIGRAVITY }),
79
+ }));
80
+ const route = resolveModelRoute(source, alias);
81
+ const shadowedBy = route.kind === "provider" && route.providerId !== ANTIGRAVITY ? route.providerId : null;
82
+ const enabled = !disabled.has(fold(effortRouteKey(alias)));
83
+ // When another provider owns the ID, /v1/models lists that provider's model instead.
84
+ const listed = shadowedBy === null && isListed(alias);
85
+ let status: EffortRouteStatus = "live";
86
+ if (providerOff) status = "provider-off";
87
+ else if (!enabled) status = "off";
88
+ else if (!listed) status = "hidden";
89
+ else if (targets.some((target) => !target.served)) status = "partial";
90
+ return {
91
+ alias,
92
+ defaultEffort: fold(rule.defaultEffort || "medium"),
93
+ targets,
94
+ enabled,
95
+ listed,
96
+ shadowedBy,
97
+ status,
98
+ };
99
+ });
100
+ }
101
+
102
+ /** Lower-cased target id to the effort route and level that use it. */
103
+ export function effortRouteTargets(config: Partial<Config> | undefined): Map<string, { alias: string; effort: string }> {
104
+ const out = new Map<string, { alias: string; effort: string }>();
105
+ for (const [alias, rule] of Object.entries(config?.effortRouting ?? {})) {
106
+ for (const { effort, model } of orderedTargets(rule)) {
107
+ const key = fold(model);
108
+ if (!out.has(key)) out.set(key, { alias: alias.trim(), effort });
109
+ }
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /**
115
+ * Why `alias` cannot name an effort route, or null when it is free. A route
116
+ * keeping its current name skips the model checks, so a route older configs
117
+ * allowed to share a model's ID can still be edited.
118
+ */
119
+ function aliasConflict(source: ModelCatalogSource, alias: string, previousAlias: string | null): string | null {
120
+ const config = source.getConfig?.();
121
+ const wanted = fold(alias);
122
+ const others = Object.keys(config?.effortRouting ?? {}).filter(
123
+ (key) => previousAlias === null || fold(key) !== fold(previousAlias),
124
+ );
125
+ if (others.some((key) => fold(key) === wanted)) return `Another effort model already uses ${alias}.`;
126
+ if (previousAlias !== null && fold(previousAlias) === wanted) return null;
127
+ const listed = listCatalogModels(source).find((model) => fold(model.id) === wanted);
128
+ if (listed) return `${listed.id} is already a model from ${providerName(listed.providerId)}. Pick an ID that isn't in use.`;
129
+ // The startup validator refuses IDs other providers claim statically even
130
+ // while no account lists them; say so beside the field instead of in a toast.
131
+ if (isKnownNonGoogleModel(alias)) return `${alias} is a model ID of another provider. Pick an ID that isn't in use.`;
132
+ if (fold(applyModelAlias(alias)) !== wanted) {
133
+ return `${alias} is already a model alias for ${applyModelAlias(alias)}. Pick an ID that isn't in use.`;
134
+ }
135
+ return null;
136
+ }
137
+
138
+ /**
139
+ * Antigravity model families with at least two effort-suffixed variants
140
+ * (`gemini-3.8-flash-low`, `-medium`, `-high`) that no effort route uses yet
141
+ * and whose base ID is free to become one.
142
+ */
143
+ export function suggestEffortRoutes(source: ModelCatalogSource): CatalogEffortSuggestion[] {
144
+ const config = source.getConfig?.();
145
+ const used = effortRouteTargets(config);
146
+ const families = new Map<string, { alias: string; targets: Map<string, string> }>();
147
+ for (const model of antigravityModels(source)) {
148
+ const hit = EFFORT_SUFFIX.exec(model.id.trim());
149
+ if (!hit) continue;
150
+ const base = hit[1];
151
+ const family = families.get(fold(base)) ?? { alias: base, targets: new Map<string, string>() };
152
+ const level = hit[2].toLowerCase();
153
+ if (!family.targets.has(level)) family.targets.set(level, model.id);
154
+ families.set(fold(base), family);
155
+ }
156
+ return [...families.values()]
157
+ .filter(
158
+ (family) =>
159
+ family.targets.size >= 2 &&
160
+ ![...family.targets.values()].some((id) => used.has(fold(id))) &&
161
+ aliasConflict(source, family.alias, null) === null,
162
+ )
163
+ .map((family) => ({
164
+ alias: family.alias,
165
+ targets: orderEffortLevels(family.targets.keys()).map((effort) => ({ effort, model: family.targets.get(effort)! })),
166
+ }));
167
+ }
168
+
169
+ export type EffortRoutePlan =
170
+ | { ok: true; alias: string; patch: Partial<Config> }
171
+ | { ok: false; status: 400 | 404; error: string; fieldErrors?: Record<string, string> };
172
+
173
+ function findAlias(config: Partial<Config> | undefined, alias: string): string | null {
174
+ return Object.keys(config?.effortRouting ?? {}).find((key) => fold(key) === fold(alias)) ?? null;
175
+ }
176
+
177
+ /** Replaces one "<provider>/<model>" entry (any case) in a switch list, or drops it when `next` is null. */
178
+ function renameKey(list: string[] | undefined, previous: string, next: string | null): string[] | undefined {
179
+ if (!list) return list;
180
+ const wanted = fold(previous);
181
+ if (!list.some((key) => fold(key) === wanted)) return list;
182
+ const out = list.filter((key) => fold(key) !== wanted);
183
+ return next === null ? out : [...out, next];
184
+ }
185
+
186
+ function invalid(error: string, fieldErrors?: Record<string, string>): EffortRoutePlan {
187
+ return { ok: false, status: 400, error, ...(fieldErrors ? { fieldErrors } : {}) };
188
+ }
189
+
190
+ /**
191
+ * Plans creating (`previousAlias` null) or replacing an effort route from a
192
+ * request body `{ alias, defaultEffort, targets: { <level>: <model> } }`. On
193
+ * replace, `alias` may be omitted to keep the name, or changed to rename the
194
+ * route; its switch moves with it.
195
+ */
196
+ export function planEffortRouteSave(
197
+ source: ModelCatalogSource,
198
+ previousAlias: string | null,
199
+ body: unknown,
200
+ ): EffortRoutePlan {
201
+ const config = source.getConfig?.() ?? ({ accounts: [] } as unknown as Config);
202
+ const existing = previousAlias === null ? null : findAlias(config, previousAlias);
203
+ if (previousAlias !== null && existing === null) {
204
+ return { ok: false, status: 404, error: `No effort model is called ${previousAlias}` };
205
+ }
206
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
207
+ return invalid('Send { "alias": "<model id>", "defaultEffort": "<level>", "targets": { "<level>": "<model id>" } }');
208
+ }
209
+ const input = body as Record<string, unknown>;
210
+ const fieldErrors: Record<string, string> = {};
211
+
212
+ const rawAlias = input.alias === undefined && existing !== null ? existing : input.alias;
213
+ const alias = typeof rawAlias === "string" ? rawAlias.trim() : "";
214
+ if (!alias) fieldErrors.alias = "Enter the model ID clients will call.";
215
+ else if (/\s/.test(alias)) fieldErrors.alias = "Model IDs can't contain spaces.";
216
+ else {
217
+ // Reserved IDs are refused even for a route that keeps its name: it can't work.
218
+ const conflict = reservedEffortAlias(alias) ?? aliasConflict(source, alias, existing);
219
+ if (conflict) fieldErrors.alias = conflict;
220
+ }
221
+
222
+ const catalog = new Map(antigravityModels(source).map((model) => [fold(model.id), model.id]));
223
+ const targets: Record<string, string> = {};
224
+ if (!input.targets || typeof input.targets !== "object" || Array.isArray(input.targets)) {
225
+ fieldErrors.targets = "Choose a model for at least one effort level.";
226
+ } else {
227
+ for (const [rawLevel, rawModel] of Object.entries(input.targets as Record<string, unknown>)) {
228
+ const level = fold(rawLevel);
229
+ const field = `targets.${level || rawLevel}`;
230
+ if (!level) {
231
+ fieldErrors[field] = "Name this level.";
232
+ continue;
233
+ }
234
+ if (/\s/.test(level)) {
235
+ fieldErrors[field] = "Level names can't contain spaces.";
236
+ continue;
237
+ }
238
+ if (Object.hasOwn(targets, level)) {
239
+ fieldErrors[field] = `There's already a ${level} level.`;
240
+ continue;
241
+ }
242
+ const model = typeof rawModel === "string" ? catalog.get(fold(rawModel)) : undefined;
243
+ if (!model) {
244
+ fieldErrors[field] = typeof rawModel === "string" && rawModel.trim()
245
+ ? `${rawModel.trim()} isn't a Google Antigravity model.`
246
+ : "Choose a model for this level.";
247
+ continue;
248
+ }
249
+ targets[level] = model;
250
+ }
251
+ if (Object.keys(targets).length === 0 && !Object.keys(fieldErrors).some((key) => key.startsWith("targets"))) {
252
+ fieldErrors.targets = "Choose a model for at least one effort level.";
253
+ }
254
+ }
255
+
256
+ // A default whose own target is refused is already reported on that target.
257
+ const defaultEffort = typeof input.defaultEffort === "string" ? fold(input.defaultEffort) : "";
258
+ const levels = new Set(
259
+ input.targets && typeof input.targets === "object" ? Object.keys(input.targets).map(fold) : [],
260
+ );
261
+ if (!defaultEffort) fieldErrors.defaultEffort = "Pick the level requests without an effort use.";
262
+ else if (!levels.has(defaultEffort)) fieldErrors.defaultEffort = `The default level ${defaultEffort} has no model.`;
263
+
264
+ const problems = Object.values(fieldErrors);
265
+ if (problems.length > 0) return invalid(problems.join(" "), fieldErrors);
266
+
267
+ const rule: EffortRoutingRule = {
268
+ defaultEffort,
269
+ targets: Object.fromEntries(orderEffortLevels(Object.keys(targets)).map((level) => [level, targets[level]])),
270
+ };
271
+ // Replace in place so the routes keep their order in the config file.
272
+ const entries = Object.entries(config.effortRouting ?? {});
273
+ const at = existing === null ? -1 : entries.findIndex(([key]) => key === existing);
274
+ if (at >= 0) entries[at] = [alias, rule];
275
+ else entries.push([alias, rule]);
276
+ const effortRouting = Object.fromEntries(entries);
277
+
278
+ const patch: Partial<Config> = { effortRouting };
279
+ if (existing !== null && existing !== alias) {
280
+ patch.disabledModels = renameKey(config.disabledModels, effortRouteKey(existing), effortRouteKey(alias));
281
+ patch.reviewedModels = renameKey(config.reviewedModels, effortRouteKey(existing), effortRouteKey(alias));
282
+ }
283
+
284
+ // The stored config must keep loading: run the same checks startup does.
285
+ const check = validateConfig({ accounts: [], modelAliases: config.modelAliases, effortRouting });
286
+ if (!check.ok) return invalid(check.errors.join("; "));
287
+ return { ok: true, alias, patch };
288
+ }
289
+
290
+ /** Plans removing an effort route and its switch. */
291
+ export function planEffortRouteDelete(config: Partial<Config> | undefined, alias: string): EffortRoutePlan {
292
+ const existing = findAlias(config, alias);
293
+ if (existing === null) return { ok: false, status: 404, error: `No effort model is called ${alias}` };
294
+ const rest = Object.entries(config?.effortRouting ?? {}).filter(([key]) => key !== existing);
295
+ return {
296
+ ok: true,
297
+ alias: existing,
298
+ patch: {
299
+ effortRouting: rest.length > 0 ? Object.fromEntries(rest) : undefined,
300
+ disabledModels: renameKey(config?.disabledModels, effortRouteKey(existing), null),
301
+ reviewedModels: renameKey(config?.reviewedModels, effortRouteKey(existing), null),
302
+ },
303
+ };
304
+ }