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,5 @@
1
+ import { mergeOpenCodeModels } from "../plugins/opencode-discovery/capabilities.mjs";
2
+ import type { RawRotatorModel } from "../plugins/opencode-discovery/index.mjs";
1
3
  import { execSync } from "node:child_process";
2
4
  import { readFileSync, existsSync } from "node:fs";
3
5
  import { resolve, dirname } from "node:path";
@@ -10,7 +12,11 @@ const PLUGIN_SOURCE_DIR = resolve(__dirname, "../plugins/opencode-discovery");
10
12
  * Files shipped from the repo plugin directory to the target machine.
11
13
  * Keep in sync with plugins/opencode-discovery/.
12
14
  */
13
- const PLUGIN_RUNTIME_SOURCE_FILES = ["index.mjs", "package.json"];
15
+ const PLUGIN_RUNTIME_SOURCE_FILES = [
16
+ "index.mjs",
17
+ "package.json",
18
+ "capabilities.mjs",
19
+ ];
14
20
 
15
21
  export interface InstallOptions {
16
22
  host?: string;
@@ -31,6 +37,7 @@ export interface DiscoveryConfigInput {
31
37
  providerName: string;
32
38
  baseURL: string;
33
39
  apiKey?: string;
40
+ models?: RawRotatorModel[];
34
41
  }
35
42
 
36
43
  /**
@@ -47,12 +54,21 @@ export interface DiscoveryConfigInput {
47
54
  */
48
55
  export function applyDiscoveryPluginConfig(
49
56
  config: Record<string, unknown>,
50
- { pluginDir, providerID, providerName, baseURL, apiKey }: DiscoveryConfigInput
57
+ {
58
+ pluginDir,
59
+ providerID,
60
+ providerName,
61
+ baseURL,
62
+ apiKey,
63
+ models,
64
+ }: DiscoveryConfigInput,
51
65
  ): Record<string, unknown> {
52
66
  const isDiscoveryEntry = (entry: unknown): boolean => {
53
67
  if (typeof entry === "string") return entry.includes("opencode-discovery");
54
68
  if (Array.isArray(entry)) {
55
- return typeof entry[0] === "string" && entry[0].includes("opencode-discovery");
69
+ return (
70
+ typeof entry[0] === "string" && entry[0].includes("opencode-discovery")
71
+ );
56
72
  }
57
73
  if (entry && typeof entry === "object") {
58
74
  const pkg = (entry as { package?: unknown }).package;
@@ -66,7 +82,9 @@ export function applyDiscoveryPluginConfig(
66
82
  : [];
67
83
 
68
84
  if (Array.isArray(config.plugin)) {
69
- const kept = (config.plugin as unknown[]).filter((entry) => !isDiscoveryEntry(entry));
85
+ const kept = (config.plugin as unknown[]).filter(
86
+ (entry) => !isDiscoveryEntry(entry),
87
+ );
70
88
  if (kept.length > 0) {
71
89
  config.plugin = kept;
72
90
  } else {
@@ -91,6 +109,14 @@ export function applyDiscoveryPluginConfig(
91
109
 
92
110
  provider[providerID] = {
93
111
  ...(existing as object),
112
+ ...(models?.length
113
+ ? {
114
+ models: mergeOpenCodeModels(
115
+ existing.models as Record<string, unknown>,
116
+ models,
117
+ ),
118
+ }
119
+ : {}),
94
120
  npm: "@ai-sdk/openai-compatible",
95
121
  name: providerName,
96
122
  options: {
@@ -118,10 +144,12 @@ export function buildRemoteInstallerScript(
118
144
  providerName: string;
119
145
  apiKey?: string;
120
146
  targetDir?: string;
121
- }
147
+ },
122
148
  ): string {
123
- if (!(PLUGIN_RUNTIME_SOURCE_FILES.every((name) => name in pluginFiles))) {
124
- throw new Error(`pluginFiles must include all of: ${PLUGIN_RUNTIME_SOURCE_FILES.join(", ")}`);
149
+ if (!PLUGIN_RUNTIME_SOURCE_FILES.every((name) => name in pluginFiles)) {
150
+ throw new Error(
151
+ `pluginFiles must include all of: ${PLUGIN_RUNTIME_SOURCE_FILES.join(", ")}`,
152
+ );
125
153
  }
126
154
 
127
155
  const targetDir = options.targetDir || "~/.config/opencode";
@@ -149,6 +177,7 @@ ${fileWriteLines}
149
177
 
150
178
  # Prepare node script to cleanly mutate or create opencode.json (OpenCode 2.x form)
151
179
  node -e '
180
+ (async () => {
152
181
  const fs = require("fs");
153
182
  const path = require("path");
154
183
 
@@ -224,12 +253,22 @@ if (apiKey && apiKey !== "no-key") {
224
253
  config.provider[providerID].options.apiKey = apiKey;
225
254
  }
226
255
 
256
+ const { fetchModels, mergeOpenCodeModels } = await import(require("url").pathToFileURL(path.join(pluginDir, "capabilities.mjs")).href);
257
+ try {
258
+ const live = await fetchModels(baseURL, apiKey);
259
+ config.provider[providerID].models = mergeOpenCodeModels(config.provider[providerID].models, live);
260
+ } catch {
261
+ console.warn("==> Catalog unavailable; existing models retained. Discovery will retry at startup.");
262
+ }
263
+
227
264
  if (!config.model) {
228
265
  config.model = providerID + "/gemini-3.8-flash-high";
229
266
  }
230
267
 
268
+ if (fs.existsSync(configFile)) fs.copyFileSync(configFile, configFile + ".bak." + Date.now());
231
269
  fs.writeFileSync(configFile, JSON.stringify(config, null, 2) + "\\n", "utf8");
232
270
  console.log("==> Successfully updated " + configFile);
271
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
233
272
  ' "$CONFIG_FILE" "$PLUGIN_DIR" "${providerId}" "${providerName}" "${rotatorUrl}" "${apiKey || ""}"
234
273
 
235
274
  echo "==> Installation complete! OpenCode is now configured to discover models from ${rotatorUrl}"
@@ -239,17 +278,25 @@ echo "==> Installation complete! OpenCode is now configured to discover models f
239
278
  /**
240
279
  * Installs the discovery plugin either locally or remotely via SSH.
241
280
  */
242
- export async function installOpenCodePlugin(options: InstallOptions): Promise<void> {
281
+ export async function installOpenCodePlugin(
282
+ options: InstallOptions,
283
+ ): Promise<void> {
243
284
  const pluginFiles: Record<string, string> = {};
244
285
  for (const name of PLUGIN_RUNTIME_SOURCE_FILES) {
245
286
  const filePath = resolve(PLUGIN_SOURCE_DIR, name);
246
287
  if (!existsSync(filePath)) {
247
- throw new Error(`Plugin directory ${PLUGIN_SOURCE_DIR} does not contain ${name}`);
288
+ throw new Error(
289
+ `Plugin directory ${PLUGIN_SOURCE_DIR} does not contain ${name}`,
290
+ );
248
291
  }
249
292
  pluginFiles[name] = readFileSync(filePath, "utf8");
250
293
  }
251
294
 
252
- const rotatorUrl = (options.rotatorUrl || process.env.TUXEVIL_ROTATOR_BASE_URL || "http://127.0.0.1:51200/v1").replace(/\/+$/, "");
295
+ const rotatorUrl = (
296
+ options.rotatorUrl ||
297
+ process.env.TUXEVIL_ROTATOR_BASE_URL ||
298
+ "http://127.0.0.1:51200/v1"
299
+ ).replace(/\/+$/, "");
253
300
  const providerId = options.providerId || "antigravity";
254
301
  const providerName = options.providerName || "Antigravity (rotator)";
255
302
 
@@ -268,8 +315,14 @@ export async function installOpenCodePlugin(options: InstallOptions): Promise<vo
268
315
  }
269
316
 
270
317
  // Local installation
271
- if (!options.host || options.host === "localhost" || options.host === "127.0.0.1") {
272
- console.log(`==> Installing OpenCode plugin locally for rotator: ${rotatorUrl}...`);
318
+ if (
319
+ !options.host ||
320
+ options.host === "localhost" ||
321
+ options.host === "127.0.0.1"
322
+ ) {
323
+ console.log(
324
+ `==> Installing OpenCode plugin locally for rotator: ${rotatorUrl}...`,
325
+ );
273
326
  execSync("bash -s", {
274
327
  input: script,
275
328
  stdio: ["pipe", "inherit", "inherit"],
@@ -278,11 +331,16 @@ export async function installOpenCodePlugin(options: InstallOptions): Promise<vo
278
331
  }
279
332
 
280
333
  // Remote installation via SSH
281
- const sshTarget = options.user ? `${options.user}@${options.host}` : options.host;
334
+ const sshTarget = options.user
335
+ ? `${options.user}@${options.host}`
336
+ : options.host;
282
337
  const sshArgs: string[] = [
283
- "-o", "BatchMode=yes",
284
- "-o", "ConnectTimeout=10",
285
- "-o", "StrictHostKeyChecking=accept-new",
338
+ "-o",
339
+ "BatchMode=yes",
340
+ "-o",
341
+ "ConnectTimeout=10",
342
+ "-o",
343
+ "StrictHostKeyChecking=accept-new",
286
344
  ];
287
345
 
288
346
  if (options.port) {
@@ -294,7 +352,9 @@ export async function installOpenCodePlugin(options: InstallOptions): Promise<vo
294
352
 
295
353
  const sshCmd = `ssh ${sshArgs.join(" ")} ${sshTarget} "bash -s"`;
296
354
 
297
- console.log(`==> Installing OpenCode plugin remotely on ${sshTarget} (Rotator: ${rotatorUrl})...`);
355
+ console.log(
356
+ `==> Installing OpenCode plugin remotely on ${sshTarget} (Rotator: ${rotatorUrl})...`,
357
+ );
298
358
  try {
299
359
  execSync(sshCmd, {
300
360
  input: script,
@@ -302,6 +362,8 @@ export async function installOpenCodePlugin(options: InstallOptions): Promise<vo
302
362
  });
303
363
  } catch (err: unknown) {
304
364
  const errorMsg = err instanceof Error ? err.message : String(err);
305
- throw new Error(`SSH installation failed on ${sshTarget}: ${errorMsg}`, { cause: err });
365
+ throw new Error(`SSH installation failed on ${sshTarget}: ${errorMsg}`, {
366
+ cause: err,
367
+ });
306
368
  }
307
369
  }
@@ -0,0 +1,74 @@
1
+ import { antigravityCatalogEvidence, advertisedModelState, type ProviderCatalogEvidence } from "./provider-catalog-evidence.js";
2
+ import { readLimitedBody } from "./body-limit.js";
3
+ import { isSettingsRepositoryInitialized } from "./db-store.js";
4
+ import { accessEvidenceStore, persistAccessEvidence, ACCESS_PLANS, type ProviderPlanEvidence, type AccessObservation } from "./access-evidence.js";
5
+ import type { ServerResponse, IncomingMessage } from "node:http";
6
+ import type { Config } from "./types.js";
7
+ import { getAccountIdentity } from "./account-identity.js";
8
+ import { MODEL_ACCESS_RULES, evaluateModelAccess, type AccessDecision } from "./model-access.js";
9
+
10
+ export interface AccessAccount { id: string; label: string; providers: string[]; inferredPlan: string; providerPlans: Omit<ProviderPlanEvidence, "credential">[]; observations: Omit<AccessObservation, "credential">[]; providerCatalogs: ProviderCatalogEvidence[] }
11
+ export interface AccessReport { informational: true; rules: typeof MODEL_ACCESS_RULES; accounts: AccessAccount[]; decision?: AccessDecision; accountId?: string; catalogAvailability?: { state: "advertised" | "not-advertised" | "unknown"; source: string | null; observedAt: number | null; expiresAt: number | null }; planSource?: "query-assumption" | "single-provider-account" | "provider-declaration" | "unknown" }
12
+ export function buildModelAccessReport(config: Config, params: URLSearchParams): AccessReport {
13
+ const accounts = config.accounts.map(account => {
14
+ const providers = [...new Set(account.credentials?.map(c => c.provider) ?? [account.provider ?? "google-antigravity"])];
15
+ // A shared account tier cannot establish each linked provider's subscription.
16
+ const tier = account.tier ?? account.type ?? "unknown";
17
+ const inferredPlan = providers.length === 1 && ["free", "plus", "ultra"].includes(tier) ? tier : "unknown";
18
+ const evidence = accessEvidenceStore().forAccount(account);
19
+ return { id: getAccountIdentity(account), label: account.label ?? account.email, providers, inferredPlan,
20
+ providerPlans: evidence.plans.map(({ credential: _credential, ...plan }) => plan),
21
+ providerCatalogs: providers.includes("google-antigravity") ? [antigravityCatalogEvidence(account, config.quotaPollIntervalMs)] : [],
22
+ observations: evidence.observations.map(({ credential: _credential, ...observation }) => observation) };
23
+ });
24
+ const report: AccessReport = { informational: true, rules: MODEL_ACCESS_RULES, accounts };
25
+ if (!params.has("model") && !params.has("provider") && !params.has("accountId")) return report;
26
+ const provider = params.get("provider"), model = params.get("model");
27
+ if (!provider || !model || model.length > 256) throw new Error("provider and model are required (model up to 256 characters)");
28
+ const accountId = params.get("accountId");
29
+ const account = accountId ? accounts.find(a => a.id === accountId) : undefined;
30
+ if (accountId && !account) throw new Error("Unknown account ID");
31
+ if (account && !account.providers.includes(provider)) throw new Error("Selected account does not have this provider");
32
+ const declared = account?.providerPlans.find(p => p.provider === provider);
33
+ const plan = params.get("plan") || declared?.plan || account?.inferredPlan || "unknown";
34
+ report.planSource = params.get("plan") ? "query-assumption" : declared ? "provider-declaration" : account?.inferredPlan !== "unknown" && account ? "single-provider-account" : "unknown";
35
+ report.accountId = accountId ?? undefined;
36
+ const catalog = account?.providerCatalogs.find(c => c.provider === provider);
37
+ report.catalogAvailability = { state: catalog ? advertisedModelState(catalog, model) : "unknown", source: catalog?.source ?? null, observedAt: catalog?.observedAt ?? null, expiresAt: catalog?.expiresAt ?? null };
38
+ report.decision = evaluateModelAccess({ provider, model, plan, client: params.get("client") ?? undefined, at: params.get("at") ?? undefined });
39
+ return report;
40
+ }
41
+ export function serveModelAccessApi(res: ServerResponse, config: Config, params: URLSearchParams): void {
42
+ res.setHeader("Cache-Control", "no-store");
43
+ try {
44
+ const report = buildModelAccessReport(config, params);
45
+ res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(report));
46
+ } catch {
47
+ res.writeHead(400, { "Content-Type": "application/json" });
48
+ res.end(JSON.stringify({ error: "Invalid access query. Check account, provider, model and date." }));
49
+ }
50
+ }
51
+
52
+ export function validateProviderPlanDeclaration(config: Config, value: unknown) {
53
+ const body = value as { accountId?: unknown; provider?: unknown; plan?: unknown } | null;
54
+ if (!body || typeof body.accountId !== "string" || typeof body.provider !== "string" || typeof body.plan !== "string" || !ACCESS_PLANS.includes(body.plan)) throw new Error("Invalid declaration");
55
+ const account = config.accounts.find(a => getAccountIdentity(a) === body.accountId);
56
+ const providers = account?.credentials?.map(c => c.provider) ?? [account?.provider ?? "google-antigravity"];
57
+ if (!account || !providers.includes(body.provider)) throw new Error("Account/provider mismatch");
58
+ return { account, provider: body.provider, plan: body.plan };
59
+ }
60
+
61
+ export async function serveProviderPlanApi(req: IncomingMessage, res: ServerResponse, config: Config): Promise<void> {
62
+ res.setHeader("Cache-Control", "no-store");
63
+ try {
64
+ if (!isSettingsRepositoryInitialized()) throw new Error("Store not ready");
65
+ const body = JSON.parse((await readLimitedBody(req, 4096)).toString("utf8"));
66
+ const declaration = validateProviderPlanDeclaration(config, body);
67
+ accessEvidenceStore().declarePlan(declaration.account, declaration.provider, declaration.plan);
68
+ await persistAccessEvidence();
69
+ serveModelAccessApi(res, config, new URLSearchParams());
70
+ } catch {
71
+ if (!res.headersSent) res.writeHead(400, { "Content-Type": "application/json" });
72
+ res.end(JSON.stringify({ error: "Invalid declaration or evidence persistence unavailable." }));
73
+ }
74
+ }
@@ -0,0 +1,56 @@
1
+ /** Policy data for access explanations and auto eligibility; it never authorizes explicit requests. */
2
+ export type AccessState = "allowed" | "blocked" | "conditional" | "unknown";
3
+ export interface AccessRule {
4
+ id: string;
5
+ provider: string;
6
+ plans: string[];
7
+ modelPrefix: string;
8
+ exact?: boolean;
9
+ state: AccessState;
10
+ evidence: "documented" | "operator-confirmed" | "operator-pending";
11
+ source: string;
12
+ verifiedAt: string;
13
+ validFrom: string;
14
+ reviewAfter: string;
15
+ validUntil?: string;
16
+ client?: string;
17
+ note: string;
18
+ }
19
+ const google = "https://antigravity.google/docs/models";
20
+ const rule = (id: string, provider: string, plans: string[], modelPrefix: string, state: AccessState, evidence: AccessRule["evidence"], source: string, note: string, extra: Partial<AccessRule> = {}): AccessRule => ({ id, provider, plans, modelPrefix, state, evidence, source, verifiedAt: "2026-10-30", validFrom: "2026-10-30", reviewAfter: "2026-11-29", note, ...extra });
21
+ export const MODEL_ACCESS_RULES: readonly AccessRule[] = [
22
+ rule("ag-flash-free", "google-antigravity", ["free", "plus", "pro-trial", "pro-paid", "ultra", "enterprise"], "gemini-3.8-flash", "allowed", "documented", google, "Gemini 3.8 Flash is listed for Free/Plus."),
23
+ ...["claude-sonnet-4-6", "claude-opus-4-6"].map(model => rule(`ag-legacy-${model}`, "google-antigravity", ["free", "plus"], model, "allowed", "documented", google, "Removal announced for November 2; diagnostic cutoff uses UTC, exact upstream rollout may differ.", { validUntil: "2026-11-02" })),
24
+ ...["gemini-4-argon", "claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-paid-${model}`, "google-antigravity", ["free", "plus"], model, "blocked", "documented", google, "Not included in Free/Plus.")),
25
+ ...["claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-trial-${model}`, "google-antigravity", ["pro-trial"], model, "blocked", "documented", google, "Claude 5.5 requires a non-trial Pro subscription or higher eligible plan.")),
26
+ ...["gemini-4-argon", "claude-sonnet-5-5", "claude-opus-5-5"].map(model => rule(`ag-entitled-${model}`, "google-antigravity", ["pro-paid", "ultra", "enterprise"], model, "allowed", "documented", google, "Listed for paid Pro/Ultra; account entitlement and quota still apply.")),
27
+ rule("ag-argon-trial", "google-antigravity", ["pro-trial"], "gemini-4-argon", "conditional", "documented", google, "Only eligible premium-device trials; generic trial status is insufficient."),
28
+ ...["gpt-6-luna", "gpt-5.6-terra", "gpt-5.6-luna"].map(model => rule(`codex-free-${model}`, "openai-codex", ["free"], model, "allowed", "operator-confirmed", "Operator account-access report, 2026-10-30", "Confirmed as available on Codex Free accounts; live quota and account entitlement still apply.")),
29
+ rule("codex-terra61-free", "openai-codex", ["free"], "gpt-6.1-terra", "blocked", "documented", "https://learn.chatgpt.com/docs/pricing", "Official ChatGPT Work/Codex availability lists paid plans for Terra 6.1. Free is not included; account-specific provider rejections are separate evidence.", { exact: true, verifiedAt: "2026-10-31", validFrom: "2026-10-26", reviewAfter: "2026-11-30" }),
30
+ rule("codex-terra61-plus", "openai-codex", ["plus"], "gpt-6.1-terra", "allowed", "documented", "https://learn.chatgpt.com/docs/pricing", "Terra 6.1 is listed for Plus in Work/Codex; rollout, surface access, quota and account restrictions still apply.", { exact: true, verifiedAt: "2026-10-31", validFrom: "2026-10-26", reviewAfter: "2026-11-30" }),
31
+ ...["beam", "gemma4:31b", "gpt-oss:120b", "gpt-oss:20b", "nemotron-3-nano:30b", "nemotron-3-super", "nemotron-3-ultra"].map(model => rule(`ollama-free-${model}`, "ollama", ["free"], model, "allowed", "operator-confirmed", "Operator-provided Ollama free-credit list, 2026-10-30", "Included in the supplied free-credit list; quota and live entitlement are separate.")),
32
+ rule("zen-big-pickle-client", "opencode-zen", ["*"], "big-pickle", "conditional", "documented", "https://github.com/anomalyco/opencode/issues/56702", "Free model without a -free suffix; genuine OpenCode context is required.", { client: "opencode" }),
33
+ rule("zen-free-client", "opencode-zen", ["*"], "*-free", "conditional", "documented", "https://github.com/anomalyco/opencode/issues/56702", "Free tier requires a genuine OpenCode client context. Client declaration is not authentication or proof of acceptance.", { client: "opencode" }),
34
+ ];
35
+ export interface AccessQuery { provider: string; model: string; plan?: string; client?: string; at?: string }
36
+ export interface AccessDecision { state: AccessState; reason: string; rules: AccessRule[]; informational: true; declaredPlan: string; clientVerified: false }
37
+ function matches(pattern: string, model: string): boolean {
38
+ if (pattern === "*-free") return model.endsWith("-free");
39
+ return model === pattern || model.startsWith(pattern + "-");
40
+ }
41
+ export function evaluateModelAccess(query: AccessQuery): AccessDecision {
42
+ const instant = query.at === undefined ? new Date() : new Date(query.at);
43
+ if (!Number.isFinite(instant.getTime())) throw new Error("Invalid evaluation date");
44
+ const plan = query.plan ?? "unknown";
45
+ const rules = MODEL_ACCESS_RULES.filter(r => r.provider === query.provider && (r.plans.includes(plan) || r.plans.includes("*")) && (r.exact ? r.modelPrefix === query.model : matches(r.modelPrefix, query.model)));
46
+ const decision = (state: AccessState, reason: string): AccessDecision => ({ state, reason, rules, informational: true, declaredPlan: plan, clientVerified: false });
47
+ if (!rules.length) return decision("unknown", "No verified rule for this provider, plan and model; absence is not permission.");
48
+ if (rules.some(r => instant < new Date(r.validFrom + "T00:00:00Z"))) return decision("unknown", "No historical policy evidence for the requested date.");
49
+ if (rules.some(r => instant >= new Date(r.reviewAfter + "T00:00:00Z"))) return decision("unknown", "Policy evidence needs re-verification; the review date has passed.");
50
+ if (rules.some(r => r.evidence === "operator-pending")) return decision("unknown", "Operator-reported policy pending verification; see declared states and evidence.");
51
+ if (rules.some(r => r.validUntil && instant >= new Date(r.validUntil + "T00:00:00Z"))) return decision("blocked", "Announced model availability window has ended (UTC diagnostic cutoff).");
52
+ if (rules.some(r => r.state === "blocked")) return decision("blocked", rules.find(r => r.state === "blocked")!.note);
53
+ if (rules.some(r => r.client)) return decision("conditional", query.client === "opencode" ? "OpenCode client declared; upstream acceptance still requires genuine context." : "Requires an OpenCode-originated request; origin is unknown or another client.");
54
+ if (rules.some(r => r.state === "conditional")) return decision("conditional", rules.find(r => r.state === "conditional")!.note);
55
+ return decision("allowed", "Documented plan access; not a guarantee of quota, credentials or request capability.");
56
+ }
@@ -0,0 +1,18 @@
1
+ /** Retain only the prefix before useful output. No caller-visible bytes are replayed. */
2
+ export async function gateOllamaOutput(body: ReadableStream<Uint8Array>, timeoutMs=30000, maxBytes=1048576): Promise<{body:ReadableStream<Uint8Array>; useful:boolean}> {
3
+ const reader=body.getReader(),chunks:Uint8Array[]=[];const decoder=new TextDecoder();let pending='',bytes=0;
4
+ const hasUseful=(line:string):boolean=>{try{const m=JSON.parse(line)?.message;return typeof m?.content==='string'&&m.content.trim().length>0||Array.isArray(m?.tool_calls)&&m.tool_calls.some((t:{function?:{name?:unknown}})=>typeof t?.function?.name==='string'&&t.function.name.length>0);}catch{return false;}};
5
+ const started=Date.now();
6
+ try{
7
+ while(true){
8
+ let timer:ReturnType<typeof setTimeout>|undefined;
9
+ const chunk=await Promise.race([reader.read(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new Error('Ollama useful-output deadline exceeded')),Math.max(1,timeoutMs-(Date.now()-started)))})]).finally(()=>clearTimeout(timer));
10
+ if(chunk.done){const collected=new ReadableStream<Uint8Array>({start(c){for(const x of chunks)c.enqueue(x);c.close()}});return{body:collected,useful:hasUseful(pending)};}
11
+ chunks.push(chunk.value);bytes+=chunk.value.byteLength;if(bytes>maxBytes)throw Error('Ollama useful-output prefix limit exceeded');
12
+ pending+=decoder.decode(chunk.value,{stream:true});const lines=pending.split('\n');pending=lines.pop()??'';
13
+ for(const line of lines){const useful=hasUseful(line);
14
+ if(useful){let index=0;return{useful:true,body:new ReadableStream<Uint8Array>({async pull(c){if(index<chunks.length){c.enqueue(chunks[index++]);return;}try{const next=await reader.read();if(next.done)c.close();else c.enqueue(next.value);}catch(e){c.error(e)}},cancel(reason){return reader.cancel(reason)}})};}
15
+ }
16
+ }
17
+ }catch(e){void reader.cancel().catch(()=>{});throw e;}
18
+ }
package/src/onboarding.ts CHANGED
@@ -261,7 +261,7 @@ export function serveLoginLanding(res: ServerResponse): void {
261
261
  }
262
262
 
263
263
  export function startHostedLogin(
264
- req: IncomingMessage,
264
+ _req: IncomingMessage,
265
265
  res: ServerResponse,
266
266
  ): void {
267
267
  if (!isHostedOAuthConfigured()) {
@@ -0,0 +1,26 @@
1
+ import type { AccountConfig } from "./types.js";
2
+ import { applyModelAlias } from "./types.js";
3
+ import { getAccountIdentity, getCredentialGeneration } from "./account-identity.js";
4
+ import { dynamicCatalog } from "./providers/google-antigravity/dynamic-catalog.js";
5
+
6
+ export interface ProviderCatalogEvidence {
7
+ provider: "google-antigravity";
8
+ source: "fetchAvailableModels";
9
+ freshness: "fresh" | "stale" | "unknown";
10
+ observedAt: number | null;
11
+ expiresAt: number | null;
12
+ models: string[];
13
+ }
14
+ export function antigravityCatalogEvidence(account: AccountConfig, pollIntervalMs = 300000, now = Date.now()): ProviderCatalogEvidence {
15
+ const snapshot = dynamicCatalog.getAccountSnapshot(getAccountIdentity(account), getCredentialGeneration(account, "google-antigravity"));
16
+ const base = { provider: "google-antigravity", source: "fetchAvailableModels" } as const;
17
+ if (!snapshot) return { ...base, freshness: "unknown", observedAt: null, expiresAt: null, models: [] };
18
+ const maxAge = Math.min(1800000, Math.max(60000, pollIntervalMs * 2));
19
+ const expiresAt = snapshot.observedAt + maxAge;
20
+ return { ...base, ...snapshot, expiresAt, freshness: snapshot.observedAt > now ? "unknown" : expiresAt > now ? "fresh" : "stale" };
21
+ }
22
+ export function advertisedModelState(catalog: ProviderCatalogEvidence, model: string): "advertised" | "not-advertised" | "unknown" {
23
+ if (catalog.freshness !== "fresh") return "unknown";
24
+ const target = applyModelAlias(model).trim().replace(/^models\//i, "").toLowerCase();
25
+ return catalog.models.some(id => id.toLowerCase() === target) ? "advertised" : "not-advertised";
26
+ }
@@ -39,6 +39,11 @@ export const ANTIGRAVITY_CONTEXT_WINDOWS: Record<string, number> = {
39
39
  // OpenAI gpt-oss-120b — 131,072 per platform.openai.com/docs/models/gpt-oss-120b.
40
40
  "gpt-oss-120b": 131_072,
41
41
  "gpt-oss-120b-medium": 131_072,
42
+ // Google Gemini 4 Argon family — 1M context window.
43
+ "gemini-4-argon": 1_000_000,
44
+ "gemini-4-argon-high": 1_000_000,
45
+ "gemini-4-argon-medium": 1_000_000,
46
+ "gemini-4-argon-low": 1_000_000,
42
47
  // Google Gemini 3.x — 1M context window per deepmind.google/models/gemini/*.
43
48
  "gemini-3.8-flash-high": 1_000_000,
44
49
  "gemini-3.8-flash-medium": 1_000_000,
@@ -76,8 +81,8 @@ const FALLBACK_CONTEXT_WINDOW = 128_000;
76
81
  *
77
82
  * Lookup order:
78
83
  * 1. Operator exact/substring override.
79
- * 2. Exact id match in static table (lowercased).
80
- * 3. Dynamic catalog entry from live Antigravity endpoint.
84
+ * 2. Dynamic catalog entry from an account snapshot.
85
+ * 3. Exact id match in static table (lowercased).
81
86
  * 4. Substring match across the table (longest key wins via the order here).
82
87
  * 5. Family defaults: claude -> 1M, gemini -> 1M, gpt-oss -> 131_072.
83
88
  * 6. Defensive fallback: 128_000.
@@ -90,10 +95,10 @@ export function getAntigravityContextWindow(model: string): number {
90
95
  if (typeof overrideCtx === "number" && Number.isFinite(overrideCtx) && overrideCtx > 0) {
91
96
  return overrideCtx;
92
97
  }
93
- const exact = ANTIGRAVITY_CONTEXT_WINDOWS[lower];
94
- if (typeof exact === "number") return exact;
95
98
  const dynamicCtx = dynamicCatalog.getContextWindow(lower);
96
99
  if (typeof dynamicCtx === "number") return dynamicCtx;
100
+ const exact = ANTIGRAVITY_CONTEXT_WINDOWS[lower];
101
+ if (typeof exact === "number") return exact;
97
102
  // Substring fallback: pick the longest registered key that appears in lower.
98
103
  let best: { key: string; value: number } | null = null;
99
104
  for (const [key, value] of Object.entries(ANTIGRAVITY_CONTEXT_WINDOWS)) {
@@ -155,14 +160,17 @@ export function getEffectiveAntigravityModels(): CompatModelEntry[] {
155
160
  const backingModel = byId.get(target);
156
161
  if (backingModel) result.push(toCompatModel(backingModel, "whisper-1", false));
157
162
  }
163
+
158
164
  return result;
159
165
  }
160
166
 
161
167
  /** Whether an id or configured operator alias resolves to a current snapshot model. */
162
168
  export function isDynamicallyAvailableAntigravityModel(model: string): boolean {
163
169
  const normalize = (value: string) => value.trim().replace(/^models\//i, "").toLowerCase();
170
+ const normalized = normalize(model);
171
+ const aliased = normalize(applyModelAlias(model));
164
172
  return Boolean(
165
- dynamicCatalog.getModel(normalize(model)) ??
166
- dynamicCatalog.getModel(normalize(applyModelAlias(model))),
173
+ dynamicCatalog.getModel(normalized) ??
174
+ dynamicCatalog.getModel(aliased),
167
175
  );
168
176
  }
@@ -8,6 +8,7 @@ import {
8
8
  QUOTA_MODEL_KEYS,
9
9
  type GoogleQuotaResponse,
10
10
  type PersistedDynamicModelOwnership,
11
+ type PersistedDynamicModelSnapshots,
11
12
  } from "../../types.js";
12
13
 
13
14
  export interface DynamicModelEntry {
@@ -60,8 +61,7 @@ function isDiscoverableModelId(value: string): boolean {
60
61
  return isSafeModelId(id) &&
61
62
  !RESERVED_QUOTA_MODEL_IDS.has(lower) &&
62
63
  !lower.startsWith("chat_") &&
63
- !lower.startsWith("tab_") &&
64
- (!lower.startsWith("gemini-3.5-") || lower === "gemini-3.5-flash-lite");
64
+ !lower.startsWith("tab_");
65
65
  }
66
66
 
67
67
  /** Validate and sanitize the untrusted runtime catalog response. */
@@ -213,6 +213,7 @@ function familyDefaults(
213
213
  export class DynamicModelRegistry {
214
214
  private static instance: DynamicModelRegistry | null = null;
215
215
  private accountModels = new Map<string, Map<string, DynamicModelEntry>>();
216
+ private snapshotTimes = new Map<string, number>();
216
217
  private defaultAgentModelIds = new Map<string, string>();
217
218
  private discoveredModels = new Map<
218
219
  string,
@@ -225,6 +226,7 @@ export class DynamicModelRegistry {
225
226
  ActiveAccountGeneration
226
227
  > | null = null;
227
228
  private nextAccountEpoch = 0;
229
+ snapshotRevision = 0;
228
230
 
229
231
  static getInstance(): DynamicModelRegistry {
230
232
  DynamicModelRegistry.instance ??= new DynamicModelRegistry();
@@ -234,6 +236,7 @@ export class DynamicModelRegistry {
234
236
  /** Reset dynamic account state (primarily for tests). */
235
237
  reset(): void {
236
238
  this.accountModels.clear();
239
+ this.snapshotTimes.clear();
237
240
  this.defaultAgentModelIds.clear();
238
241
  this.discoveredModels.clear();
239
242
  this.accountModelOwnership.clear();
@@ -377,6 +380,8 @@ export class DynamicModelRegistry {
377
380
  this.defaultAgentModelIds.delete(key);
378
381
  }
379
382
 
383
+ this.snapshotRevision++;
384
+ this.snapshotTimes.set(key, Date.now());
380
385
  this.accountModels.set(key, next);
381
386
  this.accountModelOwnership.set(key, new Set(next.keys()));
382
387
  return newModelsCount;
@@ -407,6 +412,7 @@ export class DynamicModelRegistry {
407
412
  (previousGeneration !== undefined && previousGeneration !== nextGeneration)
408
413
  ) {
409
414
  this.accountModels.delete(key);
415
+ this.snapshotTimes.delete(key);
410
416
  }
411
417
  }
412
418
  for (const key of this.accountModelOwnership.keys()) {
@@ -473,6 +479,14 @@ export class DynamicModelRegistry {
473
479
  return match;
474
480
  }
475
481
 
482
+ getAccountSnapshot(accountId: string, credentialGeneration: string): { observedAt: number; models: string[] } | undefined {
483
+ if (!this.isAccountGenerationActive(accountId, credentialGeneration)) return undefined;
484
+ const key = accountKey(accountId);
485
+ const models = this.accountModels.get(key), observedAt = this.snapshotTimes.get(key);
486
+ if (!models || observedAt === undefined) return undefined;
487
+ return { observedAt, models: Array.from(models.values(), model => model.id).sort() };
488
+ }
489
+
476
490
  hasModelForAccount(accountId: string, id: string): boolean {
477
491
  return this.accountModelOwnership
478
492
  .get(accountKey(accountId))
@@ -484,7 +498,8 @@ export class DynamicModelRegistry {
484
498
  }
485
499
 
486
500
  wasDiscovered(id: string): boolean {
487
- return this.discoveredModels.has(id.trim().toLowerCase());
501
+ const lower = id.trim().toLowerCase();
502
+ return this.discoveredModels.has(lower);
488
503
  }
489
504
 
490
505
  getObservedModelId(id: string): string | undefined {
@@ -500,6 +515,75 @@ export class DynamicModelRegistry {
500
515
  return pools;
501
516
  }
502
517
 
518
+ getPersistedSnapshots(accounts: Iterable<PersistedOwnershipAccount>): PersistedDynamicModelSnapshots {
519
+ const snapshots: PersistedDynamicModelSnapshots = { version: 1, accounts: Object.create(null) };
520
+ for (const account of accounts) {
521
+ const id = accountKey(account.id);
522
+ const models = this.accountModels.get(id);
523
+ if (!models) continue;
524
+ snapshots.accounts[id] = {
525
+ credentialGenerationFingerprint: account.credentialGenerationFingerprint,
526
+ capturedAt: this.snapshotTimes.get(id)!,
527
+ models: Array.from(models.values(), (model) => ({ ...model })),
528
+ defaultAgentModelId: this.defaultAgentModelIds.get(id),
529
+ };
530
+ }
531
+ return snapshots;
532
+ }
533
+
534
+ restorePersistedSnapshots(value: unknown, accounts: Iterable<PersistedOwnershipAccount>): void {
535
+ if (!isRecord(value) || value.version !== 1 || !isRecord(value.accounts)) return;
536
+ for (const account of accounts) {
537
+ const id = accountKey(account.id);
538
+ const snapshot = value.accounts[id];
539
+ if (!isRecord(snapshot) ||
540
+ snapshot.credentialGenerationFingerprint !== account.credentialGenerationFingerprint ||
541
+ typeof snapshot.capturedAt !== "number" || !Number.isFinite(snapshot.capturedAt) ||
542
+ snapshot.capturedAt <= 0 || !Array.isArray(snapshot.models)) continue;
543
+ const models = new Map<string, DynamicModelEntry>();
544
+ let valid = true;
545
+ for (const raw of snapshot.models) {
546
+ if (!isRecord(raw) || typeof raw.id !== "string" || !isDiscoverableModelId(raw.id) ||
547
+ typeof raw.family !== "string" || !isSafeModelId(raw.family) ||
548
+ typeof raw.quotaPool !== "string" || !["gemini", "claude"].includes(raw.quotaPool) ||
549
+ !["ctx", "maxOutputTokens"].every((key) => typeof raw[key] === "number" && Number.isFinite(raw[key]) && raw[key] > 0) ||
550
+ typeof raw.thinkingBudget !== "number" || !Number.isFinite(raw.thinkingBudget) || raw.thinkingBudget < -1 ||
551
+ (raw.thinkingBudget < 0 && raw.thinkingBudget !== -1) ||
552
+ (raw.minThinkingBudget !== undefined && (typeof raw.minThinkingBudget !== "number" || !Number.isFinite(raw.minThinkingBudget) || raw.minThinkingBudget < 0)) ||
553
+ !["multimodal", "tools", "isThinking", "isTiered"].every((key) => typeof raw[key] === "boolean") ||
554
+ (raw.displayName !== undefined && typeof raw.displayName !== "string")) {
555
+ valid = false;
556
+ break;
557
+ }
558
+ models.set(raw.id.trim().toLowerCase(), {
559
+ id: raw.id.trim(),
560
+ family: raw.family as string,
561
+ quotaPool: raw.quotaPool as string,
562
+ ctx: raw.ctx as number,
563
+ maxOutputTokens: raw.maxOutputTokens as number,
564
+ thinkingBudget: raw.thinkingBudget as number,
565
+ ...(raw.minThinkingBudget !== undefined ? { minThinkingBudget: raw.minThinkingBudget as number } : {}),
566
+ multimodal: raw.multimodal as boolean,
567
+ tools: raw.tools as boolean,
568
+ isThinking: raw.isThinking as boolean,
569
+ isTiered: raw.isTiered as boolean,
570
+ ...(raw.displayName !== undefined ? { displayName: raw.displayName as string } : {}),
571
+ });
572
+ }
573
+ const defaultId = snapshot.defaultAgentModelId;
574
+ if (!valid || (defaultId !== undefined && (typeof defaultId !== "string" || !isSafeModelId(defaultId)))) continue;
575
+ this.accountModels.set(id, models);
576
+ this.snapshotTimes.set(id, snapshot.capturedAt);
577
+ this.accountModelOwnership.set(id, new Set(models.keys()));
578
+ this.defaultAgentModelIds.delete(id);
579
+ if (typeof defaultId === "string") this.defaultAgentModelIds.set(id, defaultId);
580
+ for (const [key, model] of models) {
581
+ this.discoveredModels.set(key, { id: model.id, quotaPool: model.quotaPool });
582
+ this.ownershipScopedModels.add(key);
583
+ }
584
+ }
585
+ }
586
+
503
587
  getPersistedModelOwnership(
504
588
  accounts: Iterable<PersistedOwnershipAccount>,
505
589
  ): PersistedDynamicModelOwnership {
@@ -177,7 +177,7 @@ function extractTextFromSseEvent(eventText: string): string | null {
177
177
  try {
178
178
  const parsed = JSON.parse(payload);
179
179
  if (parsed && typeof parsed === "object") {
180
- const p = parsed as Record<string, unknown>;
180
+ const p = isRecord(parsed.response) ? parsed.response : parsed;
181
181
  if (
182
182
  Array.isArray(p.candidates) &&
183
183
  p.candidates[0] &&
@@ -191,6 +191,7 @@ function extractTextFromSseEvent(eventText: string): string | null {
191
191
  .map((part) =>
192
192
  part &&
193
193
  typeof part === "object" &&
194
+ (part as Record<string, unknown>).thought !== true &&
194
195
  typeof (part as Record<string, unknown>).text === "string"
195
196
  ? (part as Record<string, unknown>).text
196
197
  : "",
@@ -282,7 +283,8 @@ function benchmarkUsage(raw: string): { outputTokens: number } | null {
282
283
  for (const event of raw.split(/\r?\n\r?\n/)) {
283
284
  const usage = extractUsageFromSseEvent(event);
284
285
  if (usage) {
285
- outputTokens += usage.outputTokens;
286
+ // Antigravity repeats cumulative usage in content and final events.
287
+ outputTokens = Math.max(outputTokens, usage.outputTokens);
286
288
  }
287
289
  }
288
290
  return { outputTokens };