anygate 0.5.11 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -69,8 +69,6 @@ import {
69
69
  getValidationStatus,
70
70
  grabRoundTripSignature,
71
71
  hasApplicationDefaultCredentials,
72
- init_config,
73
- init_paths,
74
72
  injectClaudeIdentity,
75
73
  isClaudeAppRunning,
76
74
  isCodexAppRunning,
@@ -173,7 +171,7 @@ import {
173
171
  validateModels,
174
172
  writeSecureLogLine,
175
173
  zenRegistryStub
176
- } from "./chunk-55RHVPE4.js";
174
+ } from "./chunk-CRK6YGKY.js";
177
175
  import {
178
176
  BACKENDS,
179
177
  CONFLICTING_ENV_VARS,
@@ -181,15 +179,15 @@ import {
181
179
  MAX_MODEL_CATALOG,
182
180
  VERSION,
183
181
  VERTEX_ANTHROPIC_NPM
184
- } from "./chunk-5UF4TVCM.js";
182
+ } from "./chunk-QLHVQYQN.js";
185
183
  import {
186
184
  filterTemplates,
187
185
  getTemplateById,
188
186
  listAddableTemplates,
189
187
  listSupportedTemplates,
190
188
  listVisibleOAuthTemplates
191
- } from "./chunk-6AFYEDSU.js";
192
- import "./chunk-72WNE2IK.js";
189
+ } from "./chunk-VGM6EBG4.js";
190
+ import "./chunk-UT3JLF3M.js";
193
191
 
194
192
  // src/cli.ts
195
193
  import pc18 from "picocolors";
@@ -200,8 +198,6 @@ import { fileURLToPath } from "url";
200
198
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
201
199
  import { homedir } from "os";
202
200
  import { join } from "path";
203
- init_config();
204
- init_paths();
205
201
  var SKILL_DIR_NAME = "anygate-cli";
206
202
  var SKILL_INSTALL_DIRS = [
207
203
  join(getAppHome(), "skills"),
@@ -242,7 +238,8 @@ function skillInstallTargets() {
242
238
  }
243
239
  function formatProviderModels(provider) {
244
240
  const models = provider.modelsCache?.models ?? [];
245
- if (models.length === 0) return ` (no cached models \u2014 run: anygate providers refresh-models ${provider.id})`;
241
+ if (models.length === 0)
242
+ return ` (no cached models \u2014 run: anygate providers refresh-models ${provider.id})`;
246
243
  const lines = models.slice(0, 40).map((m) => ` ${m.id}${m.name !== m.id ? ` (${m.name})` : ""}`);
247
244
  if (models.length > 40) lines.push(` ... and ${models.length - 40} more`);
248
245
  return lines.join("\n");
@@ -253,13 +250,19 @@ function buildLiveStateSection() {
253
250
  const enabled = registry.providers.filter((p18) => p18.enabled);
254
251
  const prefLines = [];
255
252
  if (prefs.lastProvider || prefs.lastModel) {
256
- prefLines.push(` Claude last launch: provider=${prefs.lastProvider ?? "(none)"} model=${prefs.lastModel ?? "(none)"}`);
253
+ prefLines.push(
254
+ ` Claude last launch: provider=${prefs.lastProvider ?? "(none)"} model=${prefs.lastModel ?? "(none)"}`
255
+ );
257
256
  }
258
257
  if (prefs.lastCodexProvider || prefs.lastCodexModel) {
259
- prefLines.push(` Codex last launch: provider=${prefs.lastCodexProvider ?? "(none)"} model=${prefs.lastCodexModel ?? "(none)"}`);
258
+ prefLines.push(
259
+ ` Codex last launch: provider=${prefs.lastCodexProvider ?? "(none)"} model=${prefs.lastCodexModel ?? "(none)"}`
260
+ );
260
261
  }
261
262
  if (prefs.lastGeminiProvider || prefs.lastGeminiModel) {
262
- prefLines.push(` Gemini last launch: provider=${prefs.lastGeminiProvider ?? "(none)"} model=${prefs.lastGeminiModel ?? "(none)"}`);
263
+ prefLines.push(
264
+ ` Gemini last launch: provider=${prefs.lastGeminiProvider ?? "(none)"} model=${prefs.lastGeminiModel ?? "(none)"}`
265
+ );
263
266
  }
264
267
  if (prefs.favoriteModels?.length) {
265
268
  prefLines.push(` Favorites (${prefs.favoriteModels.length}/${MAX_MODEL_CATALOG}):`);
@@ -267,10 +270,12 @@ function buildLiveStateSection() {
267
270
  prefLines.push(` ${f.providerId} / ${f.modelId}`);
268
271
  }
269
272
  }
270
- const providerBlocks = enabled.length === 0 ? [" No registry providers configured. Built-in cloud: zen, go (OpenCode Zen/Go)."] : enabled.map((p18) => [
271
- ` ${p18.name} (${p18.id}) \u2014 ${p18.modelsCache?.models.length ?? 0} cached model(s)`,
272
- formatProviderModels(p18)
273
- ].join("\n"));
273
+ const providerBlocks = enabled.length === 0 ? [" No registry providers configured. Built-in cloud: zen, go (OpenCode Zen/Go)."] : enabled.map(
274
+ (p18) => [
275
+ ` ${p18.name} (${p18.id}) \u2014 ${p18.modelsCache?.models.length ?? 0} cached model(s)`,
276
+ formatProviderModels(p18)
277
+ ].join("\n")
278
+ );
274
279
  return `
275
280
  ================================================================================
276
281
  CURRENT LOCAL STATE (from disk \u2014 no network)
@@ -770,7 +775,9 @@ import * as p from "@clack/prompts";
770
775
  import open from "open";
771
776
  var ONBOARDING_TEMPLATES = ["kilo", "nvidia", "groq", "mistral", "cerebras"];
772
777
  function categorizeOnboardingProviders() {
773
- const templates = ONBOARDING_TEMPLATES.map((id) => getTemplateById(id)).filter((t) => t !== void 0 && t.supported);
778
+ const templates = ONBOARDING_TEMPLATES.map((id) => getTemplateById(id)).filter(
779
+ (t) => t !== void 0 && t.supported
780
+ );
774
781
  const keyless = [];
775
782
  const apiKeyRequired = [];
776
783
  for (const t of templates) {
@@ -800,7 +807,7 @@ async function handleKeylessProvider(template) {
800
807
  }
801
808
  async function handleApiKeyProvider(template) {
802
809
  const signupUrl = template.signupUrl ?? "https://opencode.ai/auth";
803
- printApiKeyProviderPanel(template.name, signupUrl);
810
+ printApiKeyProviderPanel(template.name, signupUrl, template.signupNote);
804
811
  let choice = await p.select({
805
812
  message: `How would you like to set up ${template.name}?`,
806
813
  options: [
@@ -812,7 +819,7 @@ async function handleApiKeyProvider(template) {
812
819
  {
813
820
  value: "signup",
814
821
  label: pc.cyan("Open signup page in browser"),
815
- hint: `Free tier at ${signupUrl}`
822
+ hint: template.signupNote ?? `Free tier at ${signupUrl}`
816
823
  },
817
824
  {
818
825
  value: "skip",
@@ -1032,28 +1039,27 @@ async function runMainMenu() {
1032
1039
  switch (choice) {
1033
1040
  case "claude":
1034
1041
  gateOutro("Launching Claude Code...");
1035
- return 0;
1036
- // The actual launch is handled by the claude command
1042
+ return dispatchCommand({ command: "claude", claudeArgs: [] });
1037
1043
  case "codex":
1038
1044
  gateOutro("Launching Codex...");
1039
- return 0;
1045
+ return dispatchCommand({ command: "codex", claudeArgs: [] });
1040
1046
  case "providers":
1041
1047
  gateOutro("Opening provider manager...");
1042
- return 0;
1048
+ return dispatchCommand({ command: "providers", claudeArgs: [] });
1043
1049
  case "onboarding":
1044
1050
  return runOnboardingFlow();
1045
1051
  case "doctor":
1046
1052
  gateOutro("Running diagnostics...");
1047
- return 0;
1053
+ return dispatchCommand({ command: "doctor", claudeArgs: [] });
1048
1054
  case "server":
1049
1055
  gateOutro("Starting server...");
1050
- return 0;
1056
+ return dispatchCommand({ command: "server", claudeArgs: [] });
1051
1057
  case "ui":
1052
1058
  gateOutro("Opening dashboard...");
1053
- return 0;
1059
+ return dispatchCommand({ command: "ui", claudeArgs: [] });
1054
1060
  case "settings":
1055
1061
  gateOutro("Opening settings...");
1056
- return 0;
1062
+ return dispatchCommand({ command: "providers", claudeArgs: [] });
1057
1063
  default:
1058
1064
  return 0;
1059
1065
  }
@@ -1122,7 +1128,10 @@ async function validateImportKey(lp, entry) {
1122
1128
  allowInsecureLocal: catalogTemplate?.apiKeyOptional === true
1123
1129
  });
1124
1130
  if (!urlCheck.ok || !urlCheck.normalizedUrl) {
1125
- return reject("invalid-key", `${urlCheck.error ?? "Invalid API base URL."} ${urlCheck.hint ?? ""}`.trim());
1131
+ return reject(
1132
+ "invalid-key",
1133
+ `${urlCheck.error ?? "Invalid API base URL."} ${urlCheck.hint ?? ""}`.trim()
1134
+ );
1126
1135
  }
1127
1136
  safeBaseUrl = urlCheck.normalizedUrl;
1128
1137
  }
@@ -1200,7 +1209,10 @@ async function importFromOpencode(options = {}) {
1200
1209
  continue;
1201
1210
  }
1202
1211
  const isOAuth = isOAuthImportProvider(lp.id, oauth);
1203
- const entry = localProviderToRegistry(lp, isOAuth ? { authType: "oauth", authRef: oauthAuthRef(lp.id) } : void 0);
1212
+ const entry = localProviderToRegistry(
1213
+ lp,
1214
+ isOAuth ? { authType: "oauth", authRef: oauthAuthRef(lp.id) } : void 0
1215
+ );
1204
1216
  if (!entry) {
1205
1217
  skipped.push({
1206
1218
  id: lp.id,
@@ -1233,7 +1245,9 @@ async function importFromOpencode(options = {}) {
1233
1245
  existing,
1234
1246
  incoming: entry,
1235
1247
  incomingProvider: lp,
1236
- existingKeyHint: await keyHint(existing.id, existing.authRef, { oauth: existing.authType === "oauth" }),
1248
+ existingKeyHint: await keyHint(existing.id, existing.authRef, {
1249
+ oauth: existing.authType === "oauth"
1250
+ }),
1237
1251
  incomingKeyHint: await keyHint(entry.id, entry.authRef, {
1238
1252
  fallbackKey: lp.apiKey,
1239
1253
  oauth: isOAuth
@@ -1254,7 +1268,10 @@ async function importFromOpencode(options = {}) {
1254
1268
  continue;
1255
1269
  }
1256
1270
  if (existingIdx >= 0) {
1257
- registry.providers[existingIdx] = { ...entry, addedAt: registry.providers[existingIdx].addedAt };
1271
+ registry.providers[existingIdx] = {
1272
+ ...entry,
1273
+ addedAt: registry.providers[existingIdx].addedAt
1274
+ };
1258
1275
  } else {
1259
1276
  registry.providers.push(entry);
1260
1277
  }
@@ -1295,7 +1312,8 @@ function detectShellProfile() {
1295
1312
  const shell = process.env["SHELL"] ?? "";
1296
1313
  if (process.platform === "darwin") {
1297
1314
  if (shell.includes("zsh")) return { display: "~/.zshrc", path: `${homedir2()}/.zshrc` };
1298
- if (shell.includes("bash")) return { display: "~/.bash_profile", path: `${homedir2()}/.bash_profile` };
1315
+ if (shell.includes("bash"))
1316
+ return { display: "~/.bash_profile", path: `${homedir2()}/.bash_profile` };
1299
1317
  return { display: "~/.profile", path: `${homedir2()}/.profile` };
1300
1318
  }
1301
1319
  if (process.platform === "linux") {
@@ -1350,28 +1368,70 @@ async function resolveOrCollectApiKey(simulate = false, trace = false) {
1350
1368
  const saveOptions = (() => {
1351
1369
  if (isMac) {
1352
1370
  return [
1353
- { value: "keychain", label: "Keychain only", hint: "Key stored encrypted in Keychain; anygate reads it automatically next time" },
1354
- { value: "keychain-autoload", label: `Keychain + ${display} auto-load`, hint: `Key in Keychain; ${display} also exports it so all terminal tools can see it` },
1355
- { value: "profile", label: `${display} only (plaintext)`, hint: "Key written directly to your shell profile \u2014 simpler but less secure" },
1356
- { value: "session", label: "This session only", hint: "Not saved anywhere \u2014 you'll be asked again next time" }
1371
+ {
1372
+ value: "keychain",
1373
+ label: "Keychain only",
1374
+ hint: "Key stored encrypted in Keychain; anygate reads it automatically next time"
1375
+ },
1376
+ {
1377
+ value: "keychain-autoload",
1378
+ label: `Keychain + ${display} auto-load`,
1379
+ hint: `Key in Keychain; ${display} also exports it so all terminal tools can see it`
1380
+ },
1381
+ {
1382
+ value: "profile",
1383
+ label: `${display} only (plaintext)`,
1384
+ hint: "Key written directly to your shell profile \u2014 simpler but less secure"
1385
+ },
1386
+ {
1387
+ value: "session",
1388
+ label: "This session only",
1389
+ hint: "Not saved anywhere \u2014 you'll be asked again next time"
1390
+ }
1357
1391
  ];
1358
1392
  }
1359
1393
  if (isWindows4) {
1360
1394
  return [
1361
- { value: "credential-manager", label: "Windows Credential Manager", hint: "Key stored securely; anygate reads it automatically next time" },
1362
- { value: "setx", label: "Persistent environment variable (plaintext)", hint: "Runs setx \u2014 key visible in System Properties \u2192 Environment Variables" },
1363
- { value: "session", label: "This session only", hint: "Not saved anywhere \u2014 you'll be asked again next time" }
1395
+ {
1396
+ value: "credential-manager",
1397
+ label: "Windows Credential Manager",
1398
+ hint: "Key stored securely; anygate reads it automatically next time"
1399
+ },
1400
+ {
1401
+ value: "setx",
1402
+ label: "Persistent environment variable (plaintext)",
1403
+ hint: "Runs setx \u2014 key visible in System Properties \u2192 Environment Variables"
1404
+ },
1405
+ {
1406
+ value: "session",
1407
+ label: "This session only",
1408
+ hint: "Not saved anywhere \u2014 you'll be asked again next time"
1409
+ }
1364
1410
  ];
1365
1411
  }
1366
1412
  const opts = [];
1367
1413
  if (secretServiceAvailable) {
1368
- opts.push({ value: "secret-service", label: "Secret Service (GNOME Keyring / KWallet)", hint: "Key stored securely in your desktop keyring; anygate reads it automatically next time" });
1414
+ opts.push({
1415
+ value: "secret-service",
1416
+ label: "Secret Service (GNOME Keyring / KWallet)",
1417
+ hint: "Key stored securely in your desktop keyring; anygate reads it automatically next time"
1418
+ });
1369
1419
  } else if (!simulate) {
1370
- p2.log.info("No keyring daemon detected \u2014 secure storage requires GNOME Keyring or KWallet running.");
1420
+ p2.log.info(
1421
+ "No keyring daemon detected \u2014 secure storage requires GNOME Keyring or KWallet running."
1422
+ );
1371
1423
  }
1372
1424
  opts.push(
1373
- { value: "profile", label: `${display} (plaintext)`, hint: "Key written directly to your shell profile" },
1374
- { value: "session", label: "This session only", hint: "Not saved anywhere \u2014 you'll be asked again next time" }
1425
+ {
1426
+ value: "profile",
1427
+ label: `${display} (plaintext)`,
1428
+ hint: "Key written directly to your shell profile"
1429
+ },
1430
+ {
1431
+ value: "session",
1432
+ label: "This session only",
1433
+ hint: "Not saved anywhere \u2014 you'll be asked again next time"
1434
+ }
1375
1435
  );
1376
1436
  return opts;
1377
1437
  })();
@@ -1412,7 +1472,9 @@ async function resolveOrCollectApiKey(simulate = false, trace = false) {
1412
1472
  ${autoLoadLine}
1413
1473
  `);
1414
1474
  }
1415
- p2.log.success(`Key saved to Keychain and auto-load added to ${display} \u2014 active now and in all future terminals.`);
1475
+ p2.log.success(
1476
+ `Key saved to Keychain and auto-load added to ${display} \u2014 active now and in all future terminals.`
1477
+ );
1416
1478
  } catch {
1417
1479
  p2.log.success("Key saved to Keychain \u2014 active now and automatically loaded next time.");
1418
1480
  p2.log.warn(`Could not write auto-load line to ${display}`);
@@ -1422,15 +1484,21 @@ ${autoLoadLine}
1422
1484
  }
1423
1485
  } else if (saveChoice === "credential-manager") {
1424
1486
  if (await saveToCredentialStore(trimmedKey)) {
1425
- p2.log.success("Key saved to Windows Credential Manager \u2014 active now and automatically loaded next time.");
1487
+ p2.log.success(
1488
+ "Key saved to Windows Credential Manager \u2014 active now and automatically loaded next time."
1489
+ );
1426
1490
  } else {
1427
1491
  p2.log.warn("Could not write to Credential Manager \u2014 key will be used for this session only");
1428
1492
  }
1429
1493
  } else if (saveChoice === "setx") {
1430
1494
  try {
1431
- const result = spawnSync("setx", ["OPENCODE_API_KEY", trimmedKey], { stdio: ["pipe", "pipe", "pipe"] });
1495
+ const result = spawnSync("setx", ["OPENCODE_API_KEY", trimmedKey], {
1496
+ stdio: ["pipe", "pipe", "pipe"]
1497
+ });
1432
1498
  if (result.status !== 0) throw new Error("setx exited with non-zero status");
1433
- p2.log.success("Key saved as a user environment variable \u2014 active now and in all future terminals.");
1499
+ p2.log.success(
1500
+ "Key saved as a user environment variable \u2014 active now and in all future terminals."
1501
+ );
1434
1502
  } catch {
1435
1503
  p2.log.warn("Could not run setx \u2014 key will be used for this session only");
1436
1504
  }
@@ -1534,7 +1602,9 @@ async function runFirstRunWizard(trace = false) {
1534
1602
  return runFirstRunWizard(trace);
1535
1603
  }
1536
1604
  if (result.imported.length === 0) {
1537
- p3.log.warn("No providers imported. Configure providers in OpenCode first, or use Quick start with Zen.");
1605
+ p3.log.warn(
1606
+ "No providers imported. Configure providers in OpenCode first, or use Quick start with Zen."
1607
+ );
1538
1608
  return runFirstRunWizard(trace);
1539
1609
  }
1540
1610
  p3.log.success(
@@ -1545,9 +1615,6 @@ async function runFirstRunWizard(trace = false) {
1545
1615
  return "continue";
1546
1616
  }
1547
1617
 
1548
- // src/cli/claude.ts
1549
- init_config();
1550
-
1551
1618
  // src/apps/shared/prompts.ts
1552
1619
  import * as p4 from "@clack/prompts";
1553
1620
  import pc3 from "picocolors";
@@ -1565,23 +1632,32 @@ function scoreModelSearch(query, fields) {
1565
1632
  return { normalized, compact: normalized.replace(/\s+/g, ""), weight: field.weight };
1566
1633
  });
1567
1634
  const tokens = normalizedQuery.split(" ").filter(Boolean);
1568
- if (!tokens.every((token) => searchableFields.some((field) => field.normalized.includes(token) || field.compact.includes(token)))) {
1635
+ if (!tokens.every(
1636
+ (token) => searchableFields.some(
1637
+ (field) => field.normalized.includes(token) || field.compact.includes(token)
1638
+ )
1639
+ )) {
1569
1640
  return 0;
1570
1641
  }
1571
1642
  let score = 1;
1572
1643
  for (const field of searchableFields) {
1573
1644
  if (field.normalized === normalizedQuery) score = Math.max(score, field.weight + 300);
1574
1645
  else if (field.compact === compactQuery) score = Math.max(score, field.weight + 260);
1575
- else if (field.normalized.startsWith(normalizedQuery)) score = Math.max(score, field.weight + 180);
1646
+ else if (field.normalized.startsWith(normalizedQuery))
1647
+ score = Math.max(score, field.weight + 180);
1576
1648
  else if (field.compact.startsWith(compactQuery)) score = Math.max(score, field.weight + 150);
1577
1649
  else if (field.normalized.includes(normalizedQuery)) score = Math.max(score, field.weight + 90);
1578
1650
  else if (field.compact.includes(compactQuery)) score = Math.max(score, field.weight + 70);
1579
1651
  }
1580
- return score + tokens.reduce((sum, token) => sum + searchableFields.reduce((best, field) => {
1581
- if (field.normalized.split(" ").includes(token)) return Math.max(best, 30);
1582
- if (field.normalized.includes(token) || field.compact.includes(token)) return Math.max(best, 12);
1583
- return best;
1584
- }, 0), 0);
1652
+ return score + tokens.reduce(
1653
+ (sum, token) => sum + searchableFields.reduce((best, field) => {
1654
+ if (field.normalized.split(" ").includes(token)) return Math.max(best, 30);
1655
+ if (field.normalized.includes(token) || field.compact.includes(token))
1656
+ return Math.max(best, 12);
1657
+ return best;
1658
+ }, 0),
1659
+ 0
1660
+ );
1585
1661
  }
1586
1662
 
1587
1663
  // src/apps/shared/prompts.ts
@@ -1687,7 +1763,11 @@ async function selectLargeCatalog(models, browseList, toOption, message, initial
1687
1763
  const method = await p4.select({
1688
1764
  message: `${message} (${models.length} available)`,
1689
1765
  options: [
1690
- { value: MODE_SEARCH, label: pc3.cyan("Search models"), hint: "Filter by name, id, or brand" },
1766
+ {
1767
+ value: MODE_SEARCH,
1768
+ label: pc3.cyan("Search models"),
1769
+ hint: "Filter by name, id, or brand"
1770
+ },
1691
1771
  {
1692
1772
  value: MODE_BROWSE,
1693
1773
  label: pc3.cyan("Browse all models"),
@@ -1703,13 +1783,9 @@ async function selectLargeCatalog(models, browseList, toOption, message, initial
1703
1783
  continue;
1704
1784
  }
1705
1785
  if (mode === "browse") {
1706
- const picked = await pickModelFromPagedList(
1707
- browseList,
1708
- toOption,
1709
- message,
1710
- initialModelId,
1711
- { search: true }
1712
- );
1786
+ const picked = await pickModelFromPagedList(browseList, toOption, message, initialModelId, {
1787
+ search: true
1788
+ });
1713
1789
  if (picked === "search") {
1714
1790
  mode = "search";
1715
1791
  continue;
@@ -1757,10 +1833,7 @@ async function selectModelWithSearch(models, toOption, message, initialModelId,
1757
1833
  if (models.length === 0) return null;
1758
1834
  const orderedBrowse = browseList ?? sortModelsByBrand(models);
1759
1835
  if (models.length <= MODEL_SEARCH_THRESHOLD) {
1760
- const options = [
1761
- ...models.map(toOption),
1762
- navOption("__back__", "\u2190 Go back", "")
1763
- ];
1836
+ const options = [...models.map(toOption), navOption("__back__", "\u2190 Go back", "")];
1764
1837
  const initialValue = initialModelId && options.some((o) => o.value === initialModelId) ? initialModelId : options[0]?.value;
1765
1838
  const picked = await p4.select({
1766
1839
  message,
@@ -1908,7 +1981,8 @@ function isGeminiNonInteractive(args) {
1908
1981
  for (let i = 0; i < args.length; i++) {
1909
1982
  const arg = args[i];
1910
1983
  if (arg === "--") return false;
1911
- if (arg === "-p" || arg === "--prompt" || arg === "-i" || arg === "--prompt-interactive") return true;
1984
+ if (arg === "-p" || arg === "--prompt" || arg === "-i" || arg === "--prompt-interactive")
1985
+ return true;
1912
1986
  if (arg.startsWith("-")) {
1913
1987
  i = skipAttachedFlagValue(args, i);
1914
1988
  continue;
@@ -2011,9 +2085,12 @@ function planLaunchWizard(opts) {
2011
2085
  return { skip: false, target: null };
2012
2086
  }
2013
2087
  function nonInteractiveLaunchError(agent) {
2014
- if (agent === "claude") return "Print mode requires --provider and --model, or saved preferences from a prior launch.";
2015
- if (agent === "codex") return "Non-interactive Codex launch requires --provider and --model, or saved preferences from a prior launch.";
2016
- if (agent === "antigravity") return "Non-interactive Antigravity launch requires --provider and --model, or saved preferences from a prior launch.";
2088
+ if (agent === "claude")
2089
+ return "Print mode requires --provider and --model, or saved preferences from a prior launch.";
2090
+ if (agent === "codex")
2091
+ return "Non-interactive Codex launch requires --provider and --model, or saved preferences from a prior launch.";
2092
+ if (agent === "antigravity")
2093
+ return "Non-interactive Antigravity launch requires --provider and --model, or saved preferences from a prior launch.";
2017
2094
  return "Non-interactive Gemini launch requires --provider and --model, or saved preferences from a prior launch.";
2018
2095
  }
2019
2096
  function isAntigravityNonInteractive(args) {
@@ -2027,7 +2104,6 @@ function isAntigravityNonInteractive(args) {
2027
2104
  // src/cli/providers-command.ts
2028
2105
  import pc4 from "picocolors";
2029
2106
  import * as p5 from "@clack/prompts";
2030
- init_config();
2031
2107
  function providerHubChoiceValue(entry) {
2032
2108
  return `provider:${entry.id}`;
2033
2109
  }
@@ -2039,8 +2115,16 @@ async function runProvidersImport() {
2039
2115
  const choice = await p5.select({
2040
2116
  message: "Which configuration should we keep?",
2041
2117
  options: [
2042
- { value: "keep", label: pc4.cyan("Keep mine"), hint: "Leave your current anygate config unchanged" },
2043
- { value: "import", label: pc4.cyan("Use imported"), hint: "Replace with OpenCode settings and refresh models" },
2118
+ {
2119
+ value: "keep",
2120
+ label: pc4.cyan("Keep mine"),
2121
+ hint: "Leave your current anygate config unchanged"
2122
+ },
2123
+ {
2124
+ value: "import",
2125
+ label: pc4.cyan("Use imported"),
2126
+ hint: "Replace with OpenCode settings and refresh models"
2127
+ },
2044
2128
  { value: "skip", label: pc4.dim("Skip this provider"), hint: "" }
2045
2129
  ]
2046
2130
  });
@@ -2183,7 +2267,9 @@ async function runProvidersRefreshModels(providerId) {
2183
2267
  }
2184
2268
  const diff = result.previousModelCount === void 0 ? 0 : (result.modelCount ?? 0) - result.previousModelCount;
2185
2269
  const diffStr = result.previousModelCount === void 0 ? "" : diff > 0 ? ` (+${diff})` : diff < 0 ? ` (${diff})` : "";
2186
- p5.log.success(`${result.name}: ${result.modelCount} model${result.modelCount === 1 ? "" : "s"} updated${diffStr}.`);
2270
+ p5.log.success(
2271
+ `${result.name}: ${result.modelCount} model${result.modelCount === 1 ? "" : "s"} updated${diffStr}.`
2272
+ );
2187
2273
  if (result.reason) {
2188
2274
  p5.log.warn(result.reason);
2189
2275
  }
@@ -2251,7 +2337,9 @@ async function pickTemplateFromCatalog() {
2251
2337
  const query = String(searchInput);
2252
2338
  const matched = filterTemplates(templates, query);
2253
2339
  if (matched.length === 0) {
2254
- const alreadyAdded = filterTemplates(listSupportedTemplates(), query).filter((t) => configuredIds.has(t.id));
2340
+ const alreadyAdded = filterTemplates(listSupportedTemplates(), query).filter(
2341
+ (t) => configuredIds.has(t.id)
2342
+ );
2255
2343
  if (alreadyAdded.length > 0) {
2256
2344
  p5.log.info(`Already configured: ${alreadyAdded.map((t) => t.name).join(", ")}`);
2257
2345
  } else {
@@ -2275,7 +2363,9 @@ async function pickTemplateFromCatalog() {
2275
2363
  }
2276
2364
  async function runOpenCodeCloudDetail() {
2277
2365
  const registry = loadRegistry();
2278
- const routes = registry.providers.filter((provider) => provider.id === "zen" || provider.id === "go");
2366
+ const routes = registry.providers.filter(
2367
+ (provider) => provider.id === "zen" || provider.id === "go"
2368
+ );
2279
2369
  printCloudProviderPanel("OpenCode Zen / Go");
2280
2370
  if (routes.length === 0) return "back";
2281
2371
  const choice = await p5.select({
@@ -2327,7 +2417,11 @@ async function runProviderDetail(id) {
2327
2417
  label: provider.enabled ? "Disable provider" : "Enable provider",
2328
2418
  hint: provider.enabled ? "Hide from anygate claude picker" : "Show in anygate claude picker"
2329
2419
  },
2330
- { value: "remove", label: "Remove provider", hint: "Delete from registry and Keychain when safe" },
2420
+ {
2421
+ value: "remove",
2422
+ label: "Remove provider",
2423
+ hint: "Delete from registry and Keychain when safe"
2424
+ },
2331
2425
  { value: "back", label: "Back", hint: "" }
2332
2426
  );
2333
2427
  const action = await p5.select({
@@ -2380,7 +2474,8 @@ function parseProvidersArgs(args) {
2380
2474
  if (first === "list") return { subcommand: "list", showHelp: false };
2381
2475
  if (first === "remove" || first === "rm") {
2382
2476
  const targetId = args[1];
2383
- if (!targetId) return { subcommand: "remove", showHelp: true, error: "Usage: anygate providers remove <id>" };
2477
+ if (!targetId)
2478
+ return { subcommand: "remove", showHelp: true, error: "Usage: anygate providers remove <id>" };
2384
2479
  return { subcommand: "remove", showHelp: false, removeId: targetId };
2385
2480
  }
2386
2481
  if (first === "refresh-models") {
@@ -2457,7 +2552,9 @@ async function runCustomEndpointAddFlow() {
2457
2552
  const usesHttp = /^http:\/\//i.test(String(baseUrl).trim());
2458
2553
  let allowInsecureHttp = false;
2459
2554
  if (usesHttp) {
2460
- p5.log.warn("HTTP is not encrypted. Only use it for a trusted local or LAN server, like Ollama on your own network.");
2555
+ p5.log.warn(
2556
+ "HTTP is not encrypted. Only use it for a trusted local or LAN server, like Ollama on your own network."
2557
+ );
2461
2558
  const allowLocal = await p5.confirm({
2462
2559
  message: "Allow insecure HTTP for this local/LAN server?",
2463
2560
  initialValue: true
@@ -2567,12 +2664,24 @@ async function runProvidersHub() {
2567
2664
  hint
2568
2665
  });
2569
2666
  }
2570
- options.push({ value: "auth-menu", label: "\u2192 Sign in with OAuth", hint: "GitHub Copilot \xB7 xAI \xB7 OpenAI" });
2667
+ options.push({
2668
+ value: "auth-menu",
2669
+ label: "\u2192 Sign in with OAuth",
2670
+ hint: "GitHub Copilot \xB7 xAI \xB7 OpenAI"
2671
+ });
2571
2672
  if (entries.length > 0) {
2572
- options.push({ value: "refresh-all", label: "\u21BA Refresh all models", hint: "Update model lists for all providers" });
2673
+ options.push({
2674
+ value: "refresh-all",
2675
+ label: "\u21BA Refresh all models",
2676
+ hint: "Update model lists for all providers"
2677
+ });
2573
2678
  }
2574
2679
  if (hasOpencode) {
2575
- options.push({ value: "import", label: "\u2192 Import providers from OpenCode CLI", hint: "One-time import" });
2680
+ options.push({
2681
+ value: "import",
2682
+ label: "\u2192 Import providers from OpenCode CLI",
2683
+ hint: "One-time import"
2684
+ });
2576
2685
  }
2577
2686
  options.push({ value: "done", label: "Done", hint: "" });
2578
2687
  const choice = await p5.select({
@@ -2836,15 +2945,17 @@ Error: ${launchPlan.error}
2836
2945
  }
2837
2946
  const localProviders = catalog.length > 0 ? catalog : null;
2838
2947
  if (switchMenuActive) {
2839
- const resolveRoute = makeRouteResolver(
2840
- localProviders
2841
- );
2948
+ const resolveRoute = makeRouteResolver(localProviders);
2842
2949
  const startingRoute = resolveRoute(activeProvider.id, selectedModel.id) ?? null;
2843
2950
  if (!startingRoute) {
2844
2951
  p6.log.error("Could not resolve a proxy route for the selected model.");
2845
2952
  return 1;
2846
2953
  }
2847
- const { routes: catalogRoutes, droppedFavorites } = buildCatalogRoutes(startingRoute, favorites, resolveRoute);
2954
+ const { routes: catalogRoutes, droppedFavorites } = buildCatalogRoutes(
2955
+ startingRoute,
2956
+ favorites,
2957
+ resolveRoute
2958
+ );
2848
2959
  if (droppedFavorites.length > 0) {
2849
2960
  p6.log.warn(
2850
2961
  `Skipping ${droppedFavorites.length} favorite${droppedFavorites.length === 1 ? "" : "s"} that are no longer available in /model`
@@ -2891,7 +3002,9 @@ Error: ${launchPlan.error}
2891
3002
  console.log(` ${pc5.bold("Provider:")} ${activeProvider.name}`);
2892
3003
  console.log(` ${pc5.bold("Model:")} ${selectedModel.id}`);
2893
3004
  console.log(` ${pc5.bold("Format:")} ${selectedModel.modelFormat} (${formatDesc})`);
2894
- console.log(` ${pc5.bold(selectedModel.modelFormat === "anthropic" ? "Endpoint:" : "SDK npm:")} ${endpoint}`);
3005
+ console.log(
3006
+ ` ${pc5.bold(selectedModel.modelFormat === "anthropic" ? "Endpoint:" : "SDK npm:")} ${endpoint}`
3007
+ );
2895
3008
  console.log(` ${pc5.bold("Key:")} ${activeProvider.name} provider key`);
2896
3009
  console.log("");
2897
3010
  console.log(pc5.dim(" (dry run complete \u2014 Claude Code was NOT launched)"));
@@ -2900,9 +3013,7 @@ Error: ${launchPlan.error}
2900
3013
  }
2901
3014
  const launchApiKey = await resolveLocalProviderApiKey(activeProvider);
2902
3015
  if (!launchApiKey?.trim()) {
2903
- p6.log.error(
2904
- new CredentialUnavailableError(activeProvider.id).userMessage
2905
- );
3016
+ p6.log.error(new CredentialUnavailableError(activeProvider.id).userMessage);
2906
3017
  return 1;
2907
3018
  }
2908
3019
  const isAvailable = await quickValidateModel(activeProvider.id, selectedModel.id);
@@ -2936,7 +3047,9 @@ Error: ${launchPlan.error}
2936
3047
  );
2937
3048
  if (!isAgentStdoutMode()) p6.log.info(`Cloud Code proxy started on port ${proxyHandle.port}`);
2938
3049
  } catch (err) {
2939
- p6.log.error(`Failed to start Cloud Code proxy: ${err instanceof Error ? err.message : String(err)}`);
3050
+ p6.log.error(
3051
+ `Failed to start Cloud Code proxy: ${err instanceof Error ? err.message : String(err)}`
3052
+ );
2940
3053
  return 1;
2941
3054
  }
2942
3055
  childEnv = buildChildEnv(
@@ -2965,7 +3078,9 @@ Error: ${launchPlan.error}
2965
3078
  );
2966
3079
  if (!isAgentStdoutMode()) p6.log.info(`OAuth proxy started on port ${proxyHandle.port}`);
2967
3080
  } catch (err) {
2968
- p6.log.error(`Failed to start OAuth proxy: ${err instanceof Error ? err.message : String(err)}`);
3081
+ p6.log.error(
3082
+ `Failed to start OAuth proxy: ${err instanceof Error ? err.message : String(err)}`
3083
+ );
2969
3084
  return 1;
2970
3085
  }
2971
3086
  childEnv = buildChildEnv(
@@ -3012,7 +3127,9 @@ Error: ${launchPlan.error}
3012
3127
  );
3013
3128
  }
3014
3129
  } catch (err) {
3015
- p6.log.error(`Failed to start SDK adapter proxy: ${err instanceof Error ? err.message : String(err)}`);
3130
+ p6.log.error(
3131
+ `Failed to start SDK adapter proxy: ${err instanceof Error ? err.message : String(err)}`
3132
+ );
3016
3133
  return 1;
3017
3134
  }
3018
3135
  childEnv = buildChildEnv(
@@ -3073,7 +3190,6 @@ async function launchClaudeViaCatalog(catalogRoutes, startingRoute, contextWindo
3073
3190
  // src/apps/codex/cli.ts
3074
3191
  import pc8 from "picocolors";
3075
3192
  import * as p9 from "@clack/prompts";
3076
- init_config();
3077
3193
 
3078
3194
  // src/apps/codex/proxy.ts
3079
3195
  import { createHash } from "crypto";
@@ -3130,7 +3246,9 @@ function applyClaudeCodeOAuthIdentity(input, sdkParams) {
3130
3246
  import { streamText, generateText, tool, jsonSchema } from "ai";
3131
3247
  function messageText(content) {
3132
3248
  if (typeof content === "string") return content;
3133
- return (content ?? []).map((p18) => p18.type === "output_text" || p18.type === "input_text" || p18.type === "text" ? p18.text ?? "" : "").join("");
3249
+ return (content ?? []).map(
3250
+ (p18) => p18.type === "output_text" || p18.type === "input_text" || p18.type === "text" ? p18.text ?? "" : ""
3251
+ ).join("");
3134
3252
  }
3135
3253
  function extractDeveloperAndInstructions(items, instructions) {
3136
3254
  const developerParts = [];
@@ -3174,9 +3292,16 @@ function mergeConsecutiveMessages(messages) {
3174
3292
  return out;
3175
3293
  }
3176
3294
  function ensureUserFirst(messages) {
3177
- if (messages.length === 0) return [{ role: "user", content: [{ type: "text", text: "(empty input)" }] }];
3295
+ if (messages.length === 0)
3296
+ return [{ role: "user", content: [{ type: "text", text: "(empty input)" }] }];
3178
3297
  if (messages[0].role === "assistant") {
3179
- return [{ role: "user", content: [{ type: "text", text: "(conversation continued)" }] }, ...messages];
3298
+ return [
3299
+ {
3300
+ role: "user",
3301
+ content: [{ type: "text", text: "(conversation continued)" }]
3302
+ },
3303
+ ...messages
3304
+ ];
3180
3305
  }
3181
3306
  return messages;
3182
3307
  }
@@ -3256,12 +3381,14 @@ function translateResponsesInput(input, instructions, npm) {
3256
3381
  const { rawId } = splitToolUseId(item.call_id);
3257
3382
  messages.push({
3258
3383
  role: "tool",
3259
- content: [{
3260
- type: "tool-result",
3261
- toolCallId: rawId,
3262
- toolName: toolNames.get(rawId) ?? "unknown",
3263
- output: { type: "text", value: serializeToolResultContent(item.output) }
3264
- }]
3384
+ content: [
3385
+ {
3386
+ type: "tool-result",
3387
+ toolCallId: rawId,
3388
+ toolName: toolNames.get(rawId) ?? "unknown",
3389
+ output: { type: "text", value: serializeToolResultContent(item.output) }
3390
+ }
3391
+ ]
3265
3392
  });
3266
3393
  } else if ("role" in item) {
3267
3394
  const role = item.role === "assistant" ? "assistant" : "user";
@@ -3283,8 +3410,14 @@ var TOOL_SEARCH_FLAT = {
3283
3410
  parameters: {
3284
3411
  type: "object",
3285
3412
  properties: {
3286
- query: { type: "string", description: "Search query describing the tool or capability needed." },
3287
- limit: { type: "number", description: "Maximum number of matching tools to return. Defaults to 8." }
3413
+ query: {
3414
+ type: "string",
3415
+ description: "Search query describing the tool or capability needed."
3416
+ },
3417
+ limit: {
3418
+ type: "number",
3419
+ description: "Maximum number of matching tools to return. Defaults to 8."
3420
+ }
3288
3421
  },
3289
3422
  required: ["query"],
3290
3423
  additionalProperties: false
@@ -3367,7 +3500,12 @@ function translateResponsesTools(tools, options = {}) {
3367
3500
  continue;
3368
3501
  }
3369
3502
  if (t.type === "custom") {
3370
- addTool(t.name, { type: "function", name: t.name, description: t.description ?? "", parameters: { type: "object", properties: {} } });
3503
+ addTool(t.name, {
3504
+ type: "function",
3505
+ name: t.name,
3506
+ description: t.description ?? "",
3507
+ parameters: { type: "object", properties: {} }
3508
+ });
3371
3509
  continue;
3372
3510
  }
3373
3511
  if (t.type !== "function" || !t.name) continue;
@@ -3469,7 +3607,13 @@ async function writeResponsesStream(fullStream, modelId, write, onDone, onProgre
3469
3607
  emit("response.output_item.added", {
3470
3608
  type: "response.output_item.added",
3471
3609
  output_index: textOutputIndex,
3472
- item: { id: textItemId, type: "message", role: "assistant", status: "in_progress", content: [] }
3610
+ item: {
3611
+ id: textItemId,
3612
+ type: "message",
3613
+ role: "assistant",
3614
+ status: "in_progress",
3615
+ content: []
3616
+ }
3473
3617
  });
3474
3618
  emit("response.content_part.added", {
3475
3619
  type: "response.content_part.added",
@@ -3723,7 +3867,14 @@ async function writeResponsesStream(fullStream, modelId, write, onDone, onProgre
3723
3867
  emit("response.output_item.added", {
3724
3868
  type: "response.output_item.added",
3725
3869
  output_index: idx,
3726
- item: { type: "function_call", id: itemId, call_id: callId, name: call.name, arguments: "", status: "in_progress" }
3870
+ item: {
3871
+ type: "function_call",
3872
+ id: itemId,
3873
+ call_id: callId,
3874
+ name: call.name,
3875
+ arguments: "",
3876
+ status: "in_progress"
3877
+ }
3727
3878
  });
3728
3879
  emit("response.function_call_arguments.done", {
3729
3880
  type: "response.function_call_arguments.done",
@@ -3731,9 +3882,20 @@ async function writeResponsesStream(fullStream, modelId, write, onDone, onProgre
3731
3882
  output_index: idx,
3732
3883
  arguments: args
3733
3884
  });
3734
- const fcItem = { type: "function_call", id: itemId, call_id: callId, name: call.name, arguments: args, status: "completed" };
3885
+ const fcItem = {
3886
+ type: "function_call",
3887
+ id: itemId,
3888
+ call_id: callId,
3889
+ name: call.name,
3890
+ arguments: args,
3891
+ status: "completed"
3892
+ };
3735
3893
  const fcSplit = splitBackFunctionCall(fcItem, namespaceMap, customToolNames);
3736
- emit("response.output_item.done", { type: "response.output_item.done", output_index: idx, item: fcSplit });
3894
+ emit("response.output_item.done", {
3895
+ type: "response.output_item.done",
3896
+ output_index: idx,
3897
+ item: fcSplit
3898
+ });
3737
3899
  outputItems.push(fcSplit);
3738
3900
  }
3739
3901
  } else if (textItemId) {
@@ -3797,7 +3959,13 @@ async function writeResponsesStream(fullStream, modelId, write, onDone, onProgre
3797
3959
  outputItems.push(fcItem);
3798
3960
  }
3799
3961
  if (outputItems.length === 0) {
3800
- outputItems.push({ id: newItemId("msg"), type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "(conversation context was too large to summarize)" }] });
3962
+ outputItems.push({
3963
+ id: newItemId("msg"),
3964
+ type: "message",
3965
+ role: "assistant",
3966
+ status: "completed",
3967
+ content: [{ type: "output_text", text: "(conversation context was too large to summarize)" }]
3968
+ });
3801
3969
  }
3802
3970
  let finalOutput = outputItems;
3803
3971
  if (isCompaction) {
@@ -3831,11 +3999,18 @@ async function streamResponsesResponse(model, params, modelId, write, onDone, on
3831
3999
  const idleTimeoutMs = options?.idleTimeoutMs ?? STREAM_IDLE_TIMEOUT_MS;
3832
4000
  const abort = new AbortController();
3833
4001
  let idleTimer = setTimeout(
3834
- () => abort.abort(new Error(`no data received from provider for ${Math.round(idleTimeoutMs / 1e3)}s`)),
4002
+ () => abort.abort(
4003
+ new Error(`no data received from provider for ${Math.round(idleTimeoutMs / 1e3)}s`)
4004
+ ),
3835
4005
  idleTimeoutMs
3836
4006
  );
3837
- const result = streamText({ model, ...params, abortSignal: abort.signal, onError: () => {
3838
- } });
4007
+ const result = streamText({
4008
+ model,
4009
+ ...params,
4010
+ abortSignal: abort.signal,
4011
+ onError: () => {
4012
+ }
4013
+ });
3839
4014
  Promise.resolve(result.text).catch(() => {
3840
4015
  });
3841
4016
  Promise.resolve(result.toolCalls).catch(() => {
@@ -3853,7 +4028,9 @@ async function streamResponsesResponse(model, params, modelId, write, onDone, on
3853
4028
  for await (const part of result.fullStream) {
3854
4029
  clearTimeout(idleTimer);
3855
4030
  idleTimer = setTimeout(
3856
- () => abort.abort(new Error(`no data received from provider for ${Math.round(idleTimeoutMs / 1e3)}s`)),
4031
+ () => abort.abort(
4032
+ new Error(`no data received from provider for ${Math.round(idleTimeoutMs / 1e3)}s`)
4033
+ ),
3857
4034
  idleTimeoutMs
3858
4035
  );
3859
4036
  yield part;
@@ -3906,7 +4083,13 @@ async function generateResponsesResponse(model, params, modelId) {
3906
4083
  arguments: typeof argsRaw === "string" ? argsRaw : JSON.stringify(argsRaw ?? {}),
3907
4084
  status: "completed"
3908
4085
  };
3909
- output.push(splitBackFunctionCall(fcItem, params.namespaceMap, params.customToolNames));
4086
+ output.push(
4087
+ splitBackFunctionCall(
4088
+ fcItem,
4089
+ params.namespaceMap,
4090
+ params.customToolNames
4091
+ )
4092
+ );
3910
4093
  }
3911
4094
  if (r.text !== null && r.text !== void 0) {
3912
4095
  output.push({
@@ -3918,7 +4101,13 @@ async function generateResponsesResponse(model, params, modelId) {
3918
4101
  });
3919
4102
  }
3920
4103
  if (output.length === 0) {
3921
- output.push({ id: newItemId("msg"), type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: "(conversation context was too large to summarize)" }] });
4104
+ output.push({
4105
+ id: newItemId("msg"),
4106
+ type: "message",
4107
+ role: "assistant",
4108
+ status: "completed",
4109
+ content: [{ type: "output_text", text: "(conversation context was too large to summarize)" }]
4110
+ });
3922
4111
  }
3923
4112
  const inputTokens = r.usage?.inputTokens ?? 0;
3924
4113
  const outputTokens = r.usage?.outputTokens ?? 0;
@@ -3944,80 +4133,102 @@ function responsesErrorBody(modelId, message, statusCode = 401) {
3944
4133
  created_at: Math.floor(Date.now() / 1e3),
3945
4134
  status: "failed",
3946
4135
  output: [],
3947
- error: { message, type: statusCode === 429 ? "rate_limit_error" : "api_error", code: String(statusCode) }
4136
+ error: {
4137
+ message,
4138
+ type: statusCode === 429 ? "rate_limit_error" : "api_error",
4139
+ code: String(statusCode)
4140
+ }
3948
4141
  };
3949
4142
  }
3950
4143
  function writeResponsesErrorStream(modelId, message, write, statusCode = 401) {
3951
- write(sseChunk("response.completed", {
3952
- type: "response.completed",
3953
- response: responsesErrorBody(modelId, message, statusCode)
3954
- }));
4144
+ write(
4145
+ sseChunk("response.completed", {
4146
+ type: "response.completed",
4147
+ response: responsesErrorBody(modelId, message, statusCode)
4148
+ })
4149
+ );
3955
4150
  }
3956
4151
  function writeResponsesRateLimitStream(modelId, message, write) {
3957
4152
  const responseId = newResponseId();
3958
4153
  const itemId = newItemId("msg");
3959
4154
  const createdAt = Math.floor(Date.now() / 1e3);
3960
4155
  const content = [{ type: "output_text", text: message }];
3961
- write(sseChunk("response.created", {
3962
- type: "response.created",
3963
- response: {
3964
- id: responseId,
3965
- object: "response",
3966
- model: modelId,
3967
- created_at: createdAt,
3968
- status: "in_progress",
3969
- output: []
3970
- }
3971
- }));
3972
- write(sseChunk("response.output_item.added", {
3973
- type: "response.output_item.added",
3974
- output_index: 0,
3975
- item: { id: itemId, type: "message", role: "assistant", status: "in_progress", content: [] }
3976
- }));
3977
- write(sseChunk("response.content_part.added", {
3978
- type: "response.content_part.added",
3979
- item_id: itemId,
3980
- output_index: 0,
3981
- content_index: 0,
3982
- part: { type: "output_text", text: "" }
3983
- }));
3984
- write(sseChunk("response.output_text.delta", {
3985
- type: "response.output_text.delta",
3986
- item_id: itemId,
3987
- output_index: 0,
3988
- content_index: 0,
3989
- delta: message
3990
- }));
3991
- write(sseChunk("response.output_text.done", {
3992
- type: "response.output_text.done",
3993
- item_id: itemId,
3994
- output_index: 0,
3995
- content_index: 0,
3996
- text: message
3997
- }));
3998
- write(sseChunk("response.content_part.done", {
3999
- type: "response.content_part.done",
4000
- item_id: itemId,
4001
- output_index: 0,
4002
- content_index: 0,
4003
- part: { type: "output_text", text: message }
4004
- }));
4005
- write(sseChunk("response.output_item.done", {
4006
- type: "response.output_item.done",
4007
- output_index: 0,
4008
- item: { id: itemId, type: "message", role: "assistant", status: "completed", content }
4009
- }));
4010
- write(sseChunk("response.completed", {
4011
- type: "response.completed",
4012
- response: {
4013
- id: responseId,
4014
- object: "response",
4015
- model: modelId,
4016
- created_at: createdAt,
4017
- status: "completed",
4018
- output: [{ id: itemId, type: "message", role: "assistant", status: "completed", content }]
4019
- }
4020
- }));
4156
+ write(
4157
+ sseChunk("response.created", {
4158
+ type: "response.created",
4159
+ response: {
4160
+ id: responseId,
4161
+ object: "response",
4162
+ model: modelId,
4163
+ created_at: createdAt,
4164
+ status: "in_progress",
4165
+ output: []
4166
+ }
4167
+ })
4168
+ );
4169
+ write(
4170
+ sseChunk("response.output_item.added", {
4171
+ type: "response.output_item.added",
4172
+ output_index: 0,
4173
+ item: { id: itemId, type: "message", role: "assistant", status: "in_progress", content: [] }
4174
+ })
4175
+ );
4176
+ write(
4177
+ sseChunk("response.content_part.added", {
4178
+ type: "response.content_part.added",
4179
+ item_id: itemId,
4180
+ output_index: 0,
4181
+ content_index: 0,
4182
+ part: { type: "output_text", text: "" }
4183
+ })
4184
+ );
4185
+ write(
4186
+ sseChunk("response.output_text.delta", {
4187
+ type: "response.output_text.delta",
4188
+ item_id: itemId,
4189
+ output_index: 0,
4190
+ content_index: 0,
4191
+ delta: message
4192
+ })
4193
+ );
4194
+ write(
4195
+ sseChunk("response.output_text.done", {
4196
+ type: "response.output_text.done",
4197
+ item_id: itemId,
4198
+ output_index: 0,
4199
+ content_index: 0,
4200
+ text: message
4201
+ })
4202
+ );
4203
+ write(
4204
+ sseChunk("response.content_part.done", {
4205
+ type: "response.content_part.done",
4206
+ item_id: itemId,
4207
+ output_index: 0,
4208
+ content_index: 0,
4209
+ part: { type: "output_text", text: message }
4210
+ })
4211
+ );
4212
+ write(
4213
+ sseChunk("response.output_item.done", {
4214
+ type: "response.output_item.done",
4215
+ output_index: 0,
4216
+ item: { id: itemId, type: "message", role: "assistant", status: "completed", content }
4217
+ })
4218
+ );
4219
+ write(
4220
+ sseChunk("response.completed", {
4221
+ type: "response.completed",
4222
+ response: {
4223
+ id: responseId,
4224
+ object: "response",
4225
+ model: modelId,
4226
+ created_at: createdAt,
4227
+ status: "completed",
4228
+ output: [{ id: itemId, type: "message", role: "assistant", status: "completed", content }]
4229
+ }
4230
+ })
4231
+ );
4021
4232
  }
4022
4233
  function responsesRateLimitBody(modelId, message) {
4023
4234
  const itemId = newItemId("msg");
@@ -4108,7 +4319,9 @@ var COMPACTION_PROMPT_MARKER = "You are performing a CONTEXT CHECKPOINT COMPACTI
4108
4319
  function inputItemText(content) {
4109
4320
  if (typeof content === "string") return content;
4110
4321
  if (!Array.isArray(content)) return "";
4111
- return content.map((p18) => p18 && typeof p18 === "object" && typeof p18.text === "string" ? p18.text : "").join("");
4322
+ return content.map(
4323
+ (p18) => p18 && typeof p18 === "object" && typeof p18.text === "string" ? p18.text : ""
4324
+ ).join("");
4112
4325
  }
4113
4326
  function isLikelyCodexCompactionRequest(body) {
4114
4327
  if (!Array.isArray(body.input)) return false;
@@ -4159,9 +4372,7 @@ function codexRouteLookupIds(requestedModel) {
4159
4372
  function findCodexProxyRoute(routes, requestedModel) {
4160
4373
  const ids = codexRouteLookupIds(requestedModel);
4161
4374
  for (const id of ids) {
4162
- const route = routes.find(
4163
- (r) => r.modelId === id || codexAppModelSlug(r.modelId) === id
4164
- );
4375
+ const route = routes.find((r) => r.modelId === id || codexAppModelSlug(r.modelId) === id);
4165
4376
  if (route) return route;
4166
4377
  }
4167
4378
  return void 0;
@@ -4180,18 +4391,21 @@ async function startCodexProxy(routes, options = {}) {
4180
4391
  silenceSdkWarnings();
4181
4392
  const models = /* @__PURE__ */ new Map();
4182
4393
  for (const route of routes) {
4183
- models.set(route.modelId, await createLanguageModel({
4184
- npm: route.npm,
4185
- modelId: route.upstreamModelId,
4186
- apiKey: route.apiKey,
4187
- baseURL: route.baseURL,
4188
- providerId: route.providerId ?? route.modelId,
4189
- authType: route.authType,
4190
- oauthAccountId: route.oauthAccountId,
4191
- providerData: route.providerData,
4192
- vertex: route.vertex,
4193
- headers: route.headers
4194
- }));
4394
+ models.set(
4395
+ route.modelId,
4396
+ await createLanguageModel({
4397
+ npm: route.npm,
4398
+ modelId: route.upstreamModelId,
4399
+ apiKey: route.apiKey,
4400
+ baseURL: route.baseURL,
4401
+ providerId: route.providerId ?? route.modelId,
4402
+ authType: route.authType,
4403
+ oauthAccountId: route.oauthAccountId,
4404
+ providerData: route.providerData,
4405
+ vertex: route.vertex,
4406
+ headers: route.headers
4407
+ })
4408
+ );
4195
4409
  }
4196
4410
  return new Promise((resolve, reject2) => {
4197
4411
  const log17 = debug ? makeTraceLogger(getCodexProxyDebugLogPath()) : () => {
@@ -4203,7 +4417,9 @@ async function startCodexProxy(routes, options = {}) {
4203
4417
  const server = createServer(async (req, res) => {
4204
4418
  const url = req.url ?? "/";
4205
4419
  if (debug) {
4206
- log17(`-> ${req.method} ${url} content-type=${req.headers["content-type"] ?? "(none)"} content-encoding=${req.headers["content-encoding"] ?? "(none)"} content-length=${req.headers["content-length"] ?? "(none)"}`);
4420
+ log17(
4421
+ `-> ${req.method} ${url} content-type=${req.headers["content-type"] ?? "(none)"} content-encoding=${req.headers["content-encoding"] ?? "(none)"} content-length=${req.headers["content-length"] ?? "(none)"}`
4422
+ );
4207
4423
  }
4208
4424
  if (!requireAuth && req.method === "POST") {
4209
4425
  const origin = req.headers.origin;
@@ -4219,7 +4435,9 @@ async function startCodexProxy(routes, options = {}) {
4219
4435
  }
4220
4436
  };
4221
4437
  if (!isValidLoopback(origin) || !isValidLoopback(referer)) {
4222
- sendJson(res, 403, { error: { message: "Forbidden origin", type: "invalid_request_error" } });
4438
+ sendJson(res, 403, {
4439
+ error: { message: "Forbidden origin", type: "invalid_request_error" }
4440
+ });
4223
4441
  return;
4224
4442
  }
4225
4443
  }
@@ -4257,7 +4475,9 @@ async function startCodexProxy(routes, options = {}) {
4257
4475
  const id = url.slice("/v1/models/".length);
4258
4476
  const route = findCodexProxyRoute(routes, id);
4259
4477
  if (!route) {
4260
- sendJson(res, 404, { error: { message: `Model not found: ${id}`, type: "invalid_request_error" } });
4478
+ sendJson(res, 404, {
4479
+ error: { message: `Model not found: ${id}`, type: "invalid_request_error" }
4480
+ });
4261
4481
  return;
4262
4482
  }
4263
4483
  sendJson(res, 200, {
@@ -4281,9 +4501,13 @@ async function startCodexProxy(routes, options = {}) {
4281
4501
  rawBody = await readBody(req);
4282
4502
  } catch (err) {
4283
4503
  if (debug) {
4284
- log17(`Error: failed to read/decode request body on POST ${url}: ${formatUpstreamError(err)} content-encoding=${req.headers["content-encoding"] ?? "(none)"}`);
4504
+ log17(
4505
+ `Error: failed to read/decode request body on POST ${url}: ${formatUpstreamError(err)} content-encoding=${req.headers["content-encoding"] ?? "(none)"}`
4506
+ );
4285
4507
  }
4286
- sendJson(res, 400, { error: { message: "Invalid request body", type: "invalid_request_error" } });
4508
+ sendJson(res, 400, {
4509
+ error: { message: "Invalid request body", type: "invalid_request_error" }
4510
+ });
4287
4511
  return;
4288
4512
  }
4289
4513
  let body;
@@ -4292,22 +4516,34 @@ async function startCodexProxy(routes, options = {}) {
4292
4516
  } catch (err) {
4293
4517
  if (debug) {
4294
4518
  const headers = JSON.stringify(req.headers);
4295
- log17(`Error: Invalid JSON body on POST ${url}: ${formatUpstreamError(err)} headers=${headers} rawBody=${JSON.stringify(rawBody.slice(0, 2e3))}`);
4519
+ log17(
4520
+ `Error: Invalid JSON body on POST ${url}: ${formatUpstreamError(err)} headers=${headers} rawBody=${JSON.stringify(rawBody.slice(0, 2e3))}`
4521
+ );
4296
4522
  }
4297
- sendJson(res, 400, { error: { message: "Invalid JSON body", type: "invalid_request_error" } });
4523
+ sendJson(res, 400, {
4524
+ error: { message: "Invalid JSON body", type: "invalid_request_error" }
4525
+ });
4298
4526
  return;
4299
4527
  }
4300
4528
  if (debug) {
4301
4529
  const prevId = body.previous_response_id ?? null;
4302
4530
  const inputItems = Array.isArray(body.input) ? body.input.length : typeof body.input === "string" ? 1 : 0;
4303
4531
  const tools = Array.isArray(body.tools) ? body.tools : [];
4304
- const toolNames = tools.map((t) => t && typeof t === "object" && "name" in t ? t.name : "?").join(",");
4305
- log17(`request: model=${String(body.model ?? "")} previous_response_id=${prevId ?? "(none)"} input_items=${inputItems} body_bytes=${rawBody.length} tools=[${toolNames || "none"}]`);
4306
- const mcpTools = tools.filter((t) => t && typeof t === "object" && "name" in t && String(t.name).startsWith("mcp__"));
4532
+ const toolNames = tools.map(
4533
+ (t) => t && typeof t === "object" && "name" in t ? t.name : "?"
4534
+ ).join(",");
4535
+ log17(
4536
+ `request: model=${String(body.model ?? "")} previous_response_id=${prevId ?? "(none)"} input_items=${inputItems} body_bytes=${rawBody.length} tools=[${toolNames || "none"}]`
4537
+ );
4538
+ const mcpTools = tools.filter(
4539
+ (t) => t && typeof t === "object" && "name" in t && String(t.name).startsWith("mcp__")
4540
+ );
4307
4541
  for (const t of mcpTools) {
4308
4542
  const mt = t;
4309
4543
  const subTools = mt.type === "namespace" && Array.isArray(mt.tools) ? ` subTools=[${mt.tools.length}]` : "";
4310
- log17(` mcp-tool: name=${mt.name} type=${mt.type} desc=${JSON.stringify(String(mt.description ?? "")).slice(0, 120)}${subTools}`);
4544
+ log17(
4545
+ ` mcp-tool: name=${mt.name} type=${mt.type} desc=${JSON.stringify(String(mt.description ?? "")).slice(0, 120)}${subTools}`
4546
+ );
4311
4547
  }
4312
4548
  }
4313
4549
  const modelId = String(body.model ?? "");
@@ -4322,41 +4558,55 @@ async function startCodexProxy(routes, options = {}) {
4322
4558
  resolved = { route: fallbackRoute, languageModel: fallbackLm };
4323
4559
  } else {
4324
4560
  if (debug) {
4325
- log17(`resolveModel failed: requested="${modelId}" known=[${routes.map((r) => r.modelId).join(", ")}]`);
4561
+ log17(
4562
+ `resolveModel failed: requested="${modelId}" known=[${routes.map((r) => r.modelId).join(", ")}]`
4563
+ );
4326
4564
  }
4327
- sendJson(res, 404, { error: { message: `Unknown model: ${modelId}`, type: "invalid_request_error" } });
4565
+ sendJson(res, 404, {
4566
+ error: { message: `Unknown model: ${modelId}`, type: "invalid_request_error" }
4567
+ });
4328
4568
  return;
4329
4569
  }
4330
4570
  }
4331
4571
  const { route, languageModel } = resolved;
4332
4572
  try {
4333
- let params = applyClaudeCodeOAuthIdentity(route, translateResponsesRequest(
4334
- body,
4335
- route.npm,
4336
- {
4337
- providerId: route.providerId,
4338
- apiBaseUrl: route.baseURL,
4339
- supportedParameters: route.supportedParameters,
4340
- reasoning: route.reasoning,
4341
- interleavedReasoningField: route.interleavedReasoningField,
4342
- upstreamModelId: route.upstreamModelId
4343
- },
4344
- { maxTools: maxToolsForNpm(route.npm) }
4345
- ));
4573
+ let params = applyClaudeCodeOAuthIdentity(
4574
+ route,
4575
+ translateResponsesRequest(
4576
+ body,
4577
+ route.npm,
4578
+ {
4579
+ providerId: route.providerId,
4580
+ apiBaseUrl: route.baseURL,
4581
+ supportedParameters: route.supportedParameters,
4582
+ reasoning: route.reasoning,
4583
+ interleavedReasoningField: route.interleavedReasoningField,
4584
+ upstreamModelId: route.upstreamModelId
4585
+ },
4586
+ { maxTools: maxToolsForNpm(route.npm) }
4587
+ )
4588
+ );
4346
4589
  if (route.contextWindow && route.contextWindow > 0) {
4347
4590
  const before = params.messages.length;
4348
4591
  const estimatedChars = estimateCodexRequestChars(params);
4349
4592
  const compaction = isLikelyCodexCompactionRequest(body);
4350
- if (debug) log17(`context check: model=${route.modelId} window=${route.contextWindow} chars=${estimatedChars} compaction=${compaction ? "yes" : "no"} messages=${before}`);
4593
+ if (debug)
4594
+ log17(
4595
+ `context check: model=${route.modelId} window=${route.contextWindow} chars=${estimatedChars} compaction=${compaction ? "yes" : "no"} messages=${before}`
4596
+ );
4351
4597
  params = protectCodexCompactionParams(body, params, route.contextWindow);
4352
4598
  params.isCompaction = compaction;
4353
4599
  if (debug && params.messages.length < before) {
4354
- log17(`context trim: model=${route.modelId} window=${route.contextWindow} kept=${params.messages.length}/${before} messages`);
4600
+ log17(
4601
+ `context trim: model=${route.modelId} window=${route.contextWindow} kept=${params.messages.length}/${before} messages`
4602
+ );
4355
4603
  }
4356
4604
  }
4357
4605
  if (debug) {
4358
4606
  const effort = body.reasoning?.effort;
4359
- log17(`model=${route.modelId} effort=${effort ?? "(none)"} providerOptions=${JSON.stringify(params.providerOptions)}`);
4607
+ log17(
4608
+ `model=${route.modelId} effort=${effort ?? "(none)"} providerOptions=${JSON.stringify(params.providerOptions)}`
4609
+ );
4360
4610
  }
4361
4611
  if (body.stream) {
4362
4612
  res.writeHead(200, {
@@ -4366,16 +4616,27 @@ async function startCodexProxy(routes, options = {}) {
4366
4616
  });
4367
4617
  const write = (chunk) => res.write(chunk);
4368
4618
  try {
4369
- await streamResponsesResponse(languageModel, params, modelId, write, (summary) => {
4370
- if (debug) {
4371
- const failure = `${summary.aborted ? " aborted=yes" : ""}${summary.errorMessage ? ` error=${JSON.stringify(summary.errorMessage)}` : ""}`;
4372
- log17(`response done: model=${route.modelId} reasoningChars=${summary.reasoningChars} textChars=${summary.textChars} toolCalls=${summary.toolCallCount} toolNames=[${summary.toolNames.join(",")}] loopDetected=${summary.loopDetected ?? "no"} dsmlRecovered=${summary.dsmlToolCallsRecovered ?? 0}${failure} reasoningPreview=${JSON.stringify(summary.reasoningPreview)}`);
4373
- }
4374
- }, (progress) => {
4375
- if (debug) {
4376
- log17(`response progress: model=${route.modelId} elapsedMs=${progress.elapsedMs} reasoningChars=${progress.reasoningChars} textChars=${progress.textChars} toolCalls=${progress.toolCallCount} reasoningTail=${JSON.stringify(progress.reasoningTail)}`);
4619
+ await streamResponsesResponse(
4620
+ languageModel,
4621
+ params,
4622
+ modelId,
4623
+ write,
4624
+ (summary) => {
4625
+ if (debug) {
4626
+ const failure = `${summary.aborted ? " aborted=yes" : ""}${summary.errorMessage ? ` error=${JSON.stringify(summary.errorMessage)}` : ""}`;
4627
+ log17(
4628
+ `response done: model=${route.modelId} reasoningChars=${summary.reasoningChars} textChars=${summary.textChars} toolCalls=${summary.toolCallCount} toolNames=[${summary.toolNames.join(",")}] loopDetected=${summary.loopDetected ?? "no"} dsmlRecovered=${summary.dsmlToolCallsRecovered ?? 0}${failure} reasoningPreview=${JSON.stringify(summary.reasoningPreview)}`
4629
+ );
4630
+ }
4631
+ },
4632
+ (progress) => {
4633
+ if (debug) {
4634
+ log17(
4635
+ `response progress: model=${route.modelId} elapsedMs=${progress.elapsedMs} reasoningChars=${progress.reasoningChars} textChars=${progress.textChars} toolCalls=${progress.toolCallCount} reasoningTail=${JSON.stringify(progress.reasoningTail)}`
4636
+ );
4637
+ }
4377
4638
  }
4378
- });
4639
+ );
4379
4640
  } catch (err) {
4380
4641
  const msg = formatUpstreamError(err);
4381
4642
  const status = upstreamHttpStatus(err);
@@ -4475,7 +4736,9 @@ async function startCodexProxy(routes, options = {}) {
4475
4736
  if (requireAuth) {
4476
4737
  const inboundKey = extractApiKey(req);
4477
4738
  if (!inboundKey || inboundKey !== PROXY_PLACEHOLDER_KEY) {
4478
- socket.write("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
4739
+ socket.write(
4740
+ "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
4741
+ );
4479
4742
  socket.destroy();
4480
4743
  return;
4481
4744
  }
@@ -4522,11 +4785,16 @@ Sec-WebSocket-Accept: ${wsAcceptKey(clientKey)}\r
4522
4785
  try {
4523
4786
  body = JSON.parse(frame.text);
4524
4787
  } catch {
4525
- if (debug) log17(`WS Error: Invalid JSON body: rawBody=${JSON.stringify(frame.text.slice(0, 2e3))}`);
4526
- sendWsEvent(`event: error
4788
+ if (debug)
4789
+ log17(
4790
+ `WS Error: Invalid JSON body: rawBody=${JSON.stringify(frame.text.slice(0, 2e3))}`
4791
+ );
4792
+ sendWsEvent(
4793
+ `event: error
4527
4794
  data: ${JSON.stringify({ error: { message: "Invalid JSON", type: "invalid_request_error" } })}
4528
4795
 
4529
- `);
4796
+ `
4797
+ );
4530
4798
  closeSocket();
4531
4799
  return;
4532
4800
  }
@@ -4534,8 +4802,12 @@ data: ${JSON.stringify({ error: { message: "Invalid JSON", type: "invalid_reques
4534
4802
  const prevId = body.previous_response_id ?? null;
4535
4803
  const inputItems = Array.isArray(body.input) ? body.input.length : typeof body.input === "string" ? 1 : 0;
4536
4804
  const tools = Array.isArray(body.tools) ? body.tools : [];
4537
- const toolNames = tools.map((t) => t && typeof t === "object" && "name" in t ? t.name : "?").join(",");
4538
- log17(`WS request: model=${String(body.model ?? "")} previous_response_id=${prevId ?? "(none)"} input_items=${inputItems} body_bytes=${frame.text.length} tools=[${toolNames || "none"}]`);
4805
+ const toolNames = tools.map(
4806
+ (t) => t && typeof t === "object" && "name" in t ? t.name : "?"
4807
+ ).join(",");
4808
+ log17(
4809
+ `WS request: model=${String(body.model ?? "")} previous_response_id=${prevId ?? "(none)"} input_items=${inputItems} body_bytes=${frame.text.length} tools=[${toolNames || "none"}]`
4810
+ );
4539
4811
  }
4540
4812
  const modelId = String(body.model ?? "");
4541
4813
  let resolved = resolveModel(routes, models, modelId);
@@ -4546,55 +4818,81 @@ data: ${JSON.stringify({ error: { message: "Invalid JSON", type: "invalid_reques
4546
4818
  if (debug) log17(`WS resolveModel fallback: requested="${modelId}" \u2192 ${fb.modelId}`);
4547
4819
  resolved = { route: fb, languageModel: fbLm };
4548
4820
  } else {
4549
- if (debug) log17(`WS resolveModel failed: requested="${modelId}" known=[${routes.map((r) => r.modelId).join(", ")}]`);
4550
- sendWsEvent(`event: error
4821
+ if (debug)
4822
+ log17(
4823
+ `WS resolveModel failed: requested="${modelId}" known=[${routes.map((r) => r.modelId).join(", ")}]`
4824
+ );
4825
+ sendWsEvent(
4826
+ `event: error
4551
4827
  data: ${JSON.stringify({ error: { message: `Unknown model: ${modelId}` } })}
4552
4828
 
4553
- `);
4829
+ `
4830
+ );
4554
4831
  closeSocket();
4555
4832
  return;
4556
4833
  }
4557
4834
  }
4558
4835
  const { route, languageModel } = resolved;
4559
4836
  try {
4560
- let params = applyClaudeCodeOAuthIdentity(route, translateResponsesRequest(
4561
- body,
4562
- route.npm,
4563
- {
4564
- providerId: route.providerId,
4565
- apiBaseUrl: route.baseURL,
4566
- supportedParameters: route.supportedParameters,
4567
- reasoning: route.reasoning,
4568
- interleavedReasoningField: route.interleavedReasoningField,
4569
- upstreamModelId: route.upstreamModelId
4570
- },
4571
- { maxTools: maxToolsForNpm(route.npm) }
4572
- ));
4837
+ let params = applyClaudeCodeOAuthIdentity(
4838
+ route,
4839
+ translateResponsesRequest(
4840
+ body,
4841
+ route.npm,
4842
+ {
4843
+ providerId: route.providerId,
4844
+ apiBaseUrl: route.baseURL,
4845
+ supportedParameters: route.supportedParameters,
4846
+ reasoning: route.reasoning,
4847
+ interleavedReasoningField: route.interleavedReasoningField,
4848
+ upstreamModelId: route.upstreamModelId
4849
+ },
4850
+ { maxTools: maxToolsForNpm(route.npm) }
4851
+ )
4852
+ );
4573
4853
  if (route.contextWindow && route.contextWindow > 0) {
4574
4854
  const before = params.messages.length;
4575
4855
  const estimatedChars = estimateCodexRequestChars(params);
4576
4856
  const compaction = isLikelyCodexCompactionRequest(body);
4577
- if (debug) log17(`WS context check: model=${route.modelId} window=${route.contextWindow} chars=${estimatedChars} compaction=${compaction ? "yes" : "no"} messages=${before} tools=${params.tools ? Object.keys(params.tools).length : 0}`);
4857
+ if (debug)
4858
+ log17(
4859
+ `WS context check: model=${route.modelId} window=${route.contextWindow} chars=${estimatedChars} compaction=${compaction ? "yes" : "no"} messages=${before} tools=${params.tools ? Object.keys(params.tools).length : 0}`
4860
+ );
4578
4861
  params = protectCodexCompactionParams(body, params, route.contextWindow);
4579
4862
  params.isCompaction = compaction;
4580
4863
  if (debug && params.messages.length < before) {
4581
- log17(`WS context trim: model=${route.modelId} window=${route.contextWindow} kept=${params.messages.length}/${before} messages tools=${params.tools ? Object.keys(params.tools).length : 0}`);
4864
+ log17(
4865
+ `WS context trim: model=${route.modelId} window=${route.contextWindow} kept=${params.messages.length}/${before} messages tools=${params.tools ? Object.keys(params.tools).length : 0}`
4866
+ );
4582
4867
  }
4583
4868
  }
4584
4869
  if (debug) {
4585
4870
  const effort = body.reasoning?.effort;
4586
- log17(`WS model=${route.modelId} effort=${effort ?? "(none)"} providerOptions=${JSON.stringify(params.providerOptions)}`);
4871
+ log17(
4872
+ `WS model=${route.modelId} effort=${effort ?? "(none)"} providerOptions=${JSON.stringify(params.providerOptions)}`
4873
+ );
4587
4874
  }
4588
- await streamResponsesResponse(languageModel, params, modelId, sendWsEvent, (summary) => {
4589
- if (debug) {
4590
- const failure = `${summary.aborted ? " aborted=yes" : ""}${summary.errorMessage ? ` error=${JSON.stringify(summary.errorMessage)}` : ""}`;
4591
- log17(`WS response done: model=${route.modelId} reasoningChars=${summary.reasoningChars} textChars=${summary.textChars} toolCalls=${summary.toolCallCount} toolNames=[${summary.toolNames.join(",")}] loopDetected=${summary.loopDetected ?? "no"} dsmlRecovered=${summary.dsmlToolCallsRecovered ?? 0}${failure} reasoningPreview=${JSON.stringify(summary.reasoningPreview)}`);
4592
- }
4593
- }, (progress) => {
4594
- if (debug) {
4595
- log17(`WS response progress: model=${route.modelId} elapsedMs=${progress.elapsedMs} reasoningChars=${progress.reasoningChars} textChars=${progress.textChars} toolCalls=${progress.toolCallCount} reasoningTail=${JSON.stringify(progress.reasoningTail)}`);
4875
+ await streamResponsesResponse(
4876
+ languageModel,
4877
+ params,
4878
+ modelId,
4879
+ sendWsEvent,
4880
+ (summary) => {
4881
+ if (debug) {
4882
+ const failure = `${summary.aborted ? " aborted=yes" : ""}${summary.errorMessage ? ` error=${JSON.stringify(summary.errorMessage)}` : ""}`;
4883
+ log17(
4884
+ `WS response done: model=${route.modelId} reasoningChars=${summary.reasoningChars} textChars=${summary.textChars} toolCalls=${summary.toolCallCount} toolNames=[${summary.toolNames.join(",")}] loopDetected=${summary.loopDetected ?? "no"} dsmlRecovered=${summary.dsmlToolCallsRecovered ?? 0}${failure} reasoningPreview=${JSON.stringify(summary.reasoningPreview)}`
4885
+ );
4886
+ }
4887
+ },
4888
+ (progress) => {
4889
+ if (debug) {
4890
+ log17(
4891
+ `WS response progress: model=${route.modelId} elapsedMs=${progress.elapsedMs} reasoningChars=${progress.reasoningChars} textChars=${progress.textChars} toolCalls=${progress.toolCallCount} reasoningTail=${JSON.stringify(progress.reasoningTail)}`
4892
+ );
4893
+ }
4596
4894
  }
4597
- });
4895
+ );
4598
4896
  } catch (err) {
4599
4897
  const msg = formatUpstreamError(err);
4600
4898
  const status = upstreamHttpStatus(err);
@@ -4706,7 +5004,6 @@ function codexProviderEnvKey(providerId) {
4706
5004
  }
4707
5005
 
4708
5006
  // src/apps/codex/session.ts
4709
- init_paths();
4710
5007
  import {
4711
5008
  copyFileSync,
4712
5009
  existsSync as existsSync3,
@@ -4912,7 +5209,6 @@ import { execFileSync, execSync, spawn } from "child_process";
4912
5209
  import { existsSync as existsSync4 } from "fs";
4913
5210
  import { homedir as homedir4 } from "os";
4914
5211
  import { join as join4 } from "path";
4915
- init_config();
4916
5212
  var isWindows = process.platform === "win32";
4917
5213
  var CODEX_CI_ENV_VARS = [
4918
5214
  "CI",
@@ -5029,7 +5325,9 @@ import pc6 from "picocolors";
5029
5325
  import * as p7 from "@clack/prompts";
5030
5326
  async function pickCodexProvider(providers, prefs, hasFavorites = false, initialProviderId, agentLabel = "Codex") {
5031
5327
  if (providers.length === 0 && !hasFavorites) return null;
5032
- const options = providers.map((lp) => providerSelectOption(lp));
5328
+ const options = providers.map(
5329
+ (lp) => providerSelectOption(lp)
5330
+ );
5033
5331
  if (hasFavorites) {
5034
5332
  options.unshift({
5035
5333
  value: "__favorites__",
@@ -5037,7 +5335,13 @@ async function pickCodexProvider(providers, prefs, hasFavorites = false, initial
5037
5335
  hint: `${prefs.favoriteModels?.length ?? 0} saved favorites`
5038
5336
  });
5039
5337
  }
5040
- const initial = initialProviderId && options.some((o) => o.value === initialProviderId) ? initialProviderId : hasFavorites ? "__favorites__" : prefs.lastCodexProvider && options.some((o) => o.value === prefs.lastCodexProvider) ? prefs.lastCodexProvider : options[0].value;
5338
+ const initial = initialProviderId && options.some((o) => o.value === initialProviderId) ? initialProviderId : (
5339
+ // When favorites exist, default to the Favorites Catalog so the gateway
5340
+ // exposes ALL saved models to the client picker — not just the last
5341
+ // single-provider selection (remembered via lastCodexProvider), which
5342
+ // would otherwise collapse the catalog to a single model.
5343
+ hasFavorites ? "__favorites__" : prefs.lastCodexProvider && options.some((o) => o.value === prefs.lastCodexProvider) ? prefs.lastCodexProvider : options[0].value
5344
+ );
5041
5345
  const chosen = await p7.select({
5042
5346
  message: `Which provider for ${agentLabel}?`,
5043
5347
  options,
@@ -5116,7 +5420,8 @@ function rejectManagedFlags(codexArgs) {
5116
5420
  if (takesValue.has(arg)) i++;
5117
5421
  continue;
5118
5422
  }
5119
- if (arg.startsWith("--profile=") || arg.startsWith("--model=") || arg.startsWith("--provider=") || arg.startsWith("-m=")) continue;
5423
+ if (arg.startsWith("--profile=") || arg.startsWith("--model=") || arg.startsWith("--provider=") || arg.startsWith("-m="))
5424
+ continue;
5120
5425
  out.push(arg);
5121
5426
  }
5122
5427
  return out;
@@ -5227,14 +5532,15 @@ async function resolveFavorite(fav, ctx) {
5227
5532
  apiKey: await resolveLocalProviderApiKey(found.provider) ?? "",
5228
5533
  authType: found.provider.authType,
5229
5534
  oauthAccountId: found.provider.oauthAccountId,
5230
- providerData: found.provider.providerData
5535
+ providerData: found.provider.providerData,
5536
+ headers: found.provider.headers
5231
5537
  };
5232
5538
  }
5233
5539
  return void 0;
5234
5540
  }
5235
5541
  async function buildFavoritesList(starting, favorites, ctx, max = 20, options = {}) {
5236
- const seen = /* @__PURE__ */ new Set();
5237
5542
  const out = [];
5543
+ const seen = /* @__PURE__ */ new Set();
5238
5544
  if (starting) {
5239
5545
  seen.add(`${starting.providerId}::${starting.model.id}`);
5240
5546
  out.push(starting);
@@ -5362,11 +5668,7 @@ async function resolveCodexFavorites(activeProvider, selectedModel, compatible,
5362
5668
  { providerId: activeProvider.id, modelId: selectedModel.id },
5363
5669
  ctx
5364
5670
  );
5365
- const { resolved, droppedFavorites } = await buildFavoritesList(
5366
- startingResolved,
5367
- favorites,
5368
- ctx
5369
- );
5671
+ const { resolved, droppedFavorites } = await buildFavoritesList(startingResolved, favorites, ctx);
5370
5672
  if (droppedFavorites.length > 0) {
5371
5673
  p8.log.warn(
5372
5674
  `Skipped ${droppedFavorites.length} stale/unauthorized favorite(s): ${droppedFavorites.map((f) => `${f.providerId}:${f.modelId}`).join(", ")}`
@@ -5403,10 +5705,7 @@ function buildCloudCodeProxyRoute(model, apiKey, providerData) {
5403
5705
  };
5404
5706
  }
5405
5707
  function buildOAuthAnthropicProxyRoute(model, apiKey, providerId, providerData) {
5406
- const aliasId = claudeCodeClientModelId(
5407
- aliasModelId(model.id, providerId),
5408
- model.contextWindow
5409
- );
5708
+ const aliasId = claudeCodeClientModelId(aliasModelId(model.id, providerId), model.contextWindow);
5410
5709
  return {
5411
5710
  aliasId,
5412
5711
  realModelId: model.upstreamModelId || model.id,
@@ -5425,12 +5724,19 @@ function buildOAuthAnthropicProxyRoute(model, apiKey, providerId, providerData)
5425
5724
  async function partitionAndStartCloudCodeBackend(items, toOutput, trace) {
5426
5725
  if (items.length === 0) return { backendItems: [], backend: null };
5427
5726
  const proxyRoutes = items.map(
5428
- (item) => item.model.modelFormat === "cloud-code" ? buildCloudCodeProxyRoute(item.model, item.apiKey, item.providerData ?? {}) : buildOAuthAnthropicProxyRoute(item.model, item.apiKey, item.providerId, item.providerData ?? {})
5727
+ (item) => item.model.modelFormat === "cloud-code" ? buildCloudCodeProxyRoute(item.model, item.apiKey, item.providerData ?? {}) : buildOAuthAnthropicProxyRoute(
5728
+ item.model,
5729
+ item.apiKey,
5730
+ item.providerId,
5731
+ item.providerData ?? {}
5732
+ )
5429
5733
  );
5430
5734
  const backend = await startCloudCodeCatalogBackend(proxyRoutes, proxyRoutes[0].aliasId, trace);
5431
5735
  return {
5432
5736
  backend,
5433
- backendItems: proxyRoutes.map((proxyRoute, index) => toOutput(proxyRoute, backend, items[index]))
5737
+ backendItems: proxyRoutes.map(
5738
+ (proxyRoute, index) => toOutput(proxyRoute, backend, items[index])
5739
+ )
5434
5740
  };
5435
5741
  }
5436
5742
  async function buildSingleModelCloudCodeRoute(model, apiKey, providerId, providerData, trace) {
@@ -5513,12 +5819,15 @@ async function writeLaunchArtifacts(route, selectedModel, providerName, proxyPor
5513
5819
  reasoning: route.reasoning,
5514
5820
  interleavedReasoningField: route.interleavedReasoningField
5515
5821
  });
5516
- writeOverlayFile(profilePath, buildCodexProfileToml({
5517
- route,
5518
- proxyPort,
5519
- catalogPath,
5520
- modelReasoningEffort: caps.defaultLevel || void 0
5521
- }));
5822
+ writeOverlayFile(
5823
+ profilePath,
5824
+ buildCodexProfileToml({
5825
+ route,
5826
+ proxyPort,
5827
+ catalogPath,
5828
+ modelReasoningEffort: caps.defaultLevel || void 0
5829
+ })
5830
+ );
5522
5831
  return { profilePath, catalogPath };
5523
5832
  }
5524
5833
  async function writeFavoritesLaunchArtifacts(resolved, starting, proxyPort) {
@@ -5535,12 +5844,15 @@ async function writeFavoritesLaunchArtifacts(resolved, starting, proxyPort) {
5535
5844
  upstreamModelId: model.upstreamModelId || model.id,
5536
5845
  apiKey: ""
5537
5846
  };
5538
- writeOverlayFile(profilePath, buildCodexProfileToml({
5539
- route: dummyRoute,
5540
- proxyPort,
5541
- catalogPath,
5542
- modelReasoningEffort: defaultReasoningEffortForFavorite(starting)
5543
- }));
5847
+ writeOverlayFile(
5848
+ profilePath,
5849
+ buildCodexProfileToml({
5850
+ route: dummyRoute,
5851
+ proxyPort,
5852
+ catalogPath,
5853
+ modelReasoningEffort: defaultReasoningEffortForFavorite(starting)
5854
+ })
5855
+ );
5544
5856
  return { profilePath, catalogPath };
5545
5857
  }
5546
5858
  function printCodexCleanupReminder(hadProxy) {
@@ -5618,19 +5930,24 @@ async function runCodexVertexLaunch(passthroughArgs, trace) {
5618
5930
  const debugLogPath = getCodexProxyDebugLogPath();
5619
5931
  let proxyHandle = null;
5620
5932
  try {
5621
- p9.log.info(`Vertex AI \xB7 ${selectedEntry.display_name} \u2014 project: ${config.project} / location: ${config.location}`);
5933
+ p9.log.info(
5934
+ `Vertex AI \xB7 ${selectedEntry.display_name} \u2014 project: ${config.project} / location: ${config.location}`
5935
+ );
5622
5936
  proxyHandle = await startCodexProxy(allRoutes, { debug: trace });
5623
5937
  const proxyPort = proxyHandle.port;
5624
5938
  const catalogPath = getCatalogOutputPath("vertex");
5625
5939
  writeOverlayFile(catalogPath, serializeCatalog(buildCatalogFile(allModels, "Vertex AI")));
5626
5940
  const profilePath = getProfileOutputPath();
5627
5941
  const caps = getReasoningCapabilities(VERTEX_ANTHROPIC_NPM, selectedEntry.id);
5628
- writeOverlayFile(profilePath, buildCodexProfileToml({
5629
- route: startingRoute,
5630
- proxyPort,
5631
- catalogPath,
5632
- modelReasoningEffort: caps.defaultLevel || void 0
5633
- }));
5942
+ writeOverlayFile(
5943
+ profilePath,
5944
+ buildCodexProfileToml({
5945
+ route: startingRoute,
5946
+ proxyPort,
5947
+ catalogPath,
5948
+ modelReasoningEffort: caps.defaultLevel || void 0
5949
+ })
5950
+ );
5634
5951
  writeSessionLock({
5635
5952
  pid: process.pid,
5636
5953
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -5692,7 +6009,9 @@ async function runCodexCommand(codexArgs, trace = false, launch = {}) {
5692
6009
  console.error(pc8.red("anygate codex --vertex requires an interactive terminal."));
5693
6010
  return 1;
5694
6011
  }
5695
- console.error(pc8.yellow(`Another anygate codex session may be running (pid ${sessionCheck.lock.pid}).`));
6012
+ console.error(
6013
+ pc8.yellow(`Another anygate codex session may be running (pid ${sessionCheck.lock.pid}).`)
6014
+ );
5696
6015
  console.error("Run anygate codex --restore to clean up, or wait for it to finish.");
5697
6016
  return 1;
5698
6017
  }
@@ -5717,12 +6036,16 @@ Error: ${launchPlan.error}
5717
6036
  const sessionCheck = checkSessionLock(isTty || allowNonTty);
5718
6037
  if (!sessionCheck.ok) {
5719
6038
  if (sessionCheck.reason === "non_tty") {
5720
- console.error(pc8.red(
5721
- "anygate codex requires an interactive terminal (or use --provider and --model for non-interactive launch)."
5722
- ));
6039
+ console.error(
6040
+ pc8.red(
6041
+ "anygate codex requires an interactive terminal (or use --provider and --model for non-interactive launch)."
6042
+ )
6043
+ );
5723
6044
  return 1;
5724
6045
  }
5725
- console.error(pc8.yellow(`Another anygate codex session may be running (pid ${sessionCheck.lock.pid}).`));
6046
+ console.error(
6047
+ pc8.yellow(`Another anygate codex session may be running (pid ${sessionCheck.lock.pid}).`)
6048
+ );
5726
6049
  console.error("Run anygate codex --restore to clean up, or wait for it to finish.");
5727
6050
  return 1;
5728
6051
  }
@@ -5762,7 +6085,9 @@ Error: ${launchPlan.error}
5762
6085
  if (compatible.length === 0) {
5763
6086
  if (!configOnly) {
5764
6087
  p9.log.warn("No Codex-compatible providers in your registry.");
5765
- p9.log.info("Add a provider with anygate providers add, or sign in with anygate providers auth openai.");
6088
+ p9.log.info(
6089
+ "Add a provider with anygate providers add, or sign in with anygate providers auth openai."
6090
+ );
5766
6091
  }
5767
6092
  return 0;
5768
6093
  }
@@ -5792,7 +6117,12 @@ Error: ${launchPlan.error}
5792
6117
  } else if (!configOnly) {
5793
6118
  let currentInitialProvider = prefs.lastCodexProvider && compatible.some((o) => o.id === prefs.lastCodexProvider) ? prefs.lastCodexProvider : compatible[0].id;
5794
6119
  while (true) {
5795
- const pickedProvider = await pickCodexProvider(compatible, prefs, favoritesActive, currentInitialProvider);
6120
+ const pickedProvider = await pickCodexProvider(
6121
+ compatible,
6122
+ prefs,
6123
+ favoritesActive,
6124
+ currentInitialProvider
6125
+ );
5796
6126
  if (!pickedProvider) return 0;
5797
6127
  if (pickedProvider === "__favorites__") {
5798
6128
  const favoritePick = await pickFavoriteStartingModel(
@@ -5907,21 +6237,26 @@ Error: ${launchPlan.error}
5907
6237
  trace
5908
6238
  );
5909
6239
  cloudCodeBackend = backend;
5910
- proxyHandle = await startCodexProxy([{
5911
- modelId: cloudRoute.aliasId,
5912
- npm: "@ai-sdk/anthropic",
5913
- apiKey: cloudCodeBackend.token,
5914
- baseURL: `http://127.0.0.1:${cloudCodeBackend.port}`,
5915
- upstreamModelId: cloudRoute.aliasId,
5916
- providerId: route.providerId,
5917
- authType: route.authType,
5918
- oauthAccountId: route.oauthAccountId,
5919
- providerData,
5920
- contextWindow: route.contextWindow,
5921
- supportedParameters: route.supportedParameters,
5922
- reasoning: route.reasoning,
5923
- interleavedReasoningField: route.interleavedReasoningField
5924
- }], { debug: trace });
6240
+ proxyHandle = await startCodexProxy(
6241
+ [
6242
+ {
6243
+ modelId: cloudRoute.aliasId,
6244
+ npm: "@ai-sdk/anthropic",
6245
+ apiKey: cloudCodeBackend.token,
6246
+ baseURL: `http://127.0.0.1:${cloudCodeBackend.port}`,
6247
+ upstreamModelId: cloudRoute.aliasId,
6248
+ providerId: route.providerId,
6249
+ authType: route.authType,
6250
+ oauthAccountId: route.oauthAccountId,
6251
+ providerData,
6252
+ contextWindow: route.contextWindow,
6253
+ supportedParameters: route.supportedParameters,
6254
+ reasoning: route.reasoning,
6255
+ interleavedReasoningField: route.interleavedReasoningField
6256
+ }
6257
+ ],
6258
+ { debug: trace }
6259
+ );
5925
6260
  proxyPort = proxyHandle.port;
5926
6261
  } else if (route.authType === "oauth" && selectedModel.modelFormat === "anthropic") {
5927
6262
  const providerData = activeProvider.providerData ?? {};
@@ -5933,38 +6268,48 @@ Error: ${launchPlan.error}
5933
6268
  trace
5934
6269
  );
5935
6270
  cloudCodeBackend = backend;
5936
- proxyHandle = await startCodexProxy([{
5937
- modelId: oauthRoute.aliasId,
5938
- npm: "@ai-sdk/anthropic",
5939
- apiKey: cloudCodeBackend.token,
5940
- baseURL: `http://127.0.0.1:${cloudCodeBackend.port}`,
5941
- upstreamModelId: oauthRoute.aliasId,
5942
- providerId: route.providerId,
5943
- authType: route.authType,
5944
- oauthAccountId: route.oauthAccountId,
5945
- providerData,
5946
- contextWindow: route.contextWindow,
5947
- supportedParameters: route.supportedParameters,
5948
- reasoning: route.reasoning,
5949
- interleavedReasoningField: route.interleavedReasoningField
5950
- }], { debug: trace });
6271
+ proxyHandle = await startCodexProxy(
6272
+ [
6273
+ {
6274
+ modelId: oauthRoute.aliasId,
6275
+ npm: "@ai-sdk/anthropic",
6276
+ apiKey: cloudCodeBackend.token,
6277
+ baseURL: `http://127.0.0.1:${cloudCodeBackend.port}`,
6278
+ upstreamModelId: oauthRoute.aliasId,
6279
+ providerId: route.providerId,
6280
+ authType: route.authType,
6281
+ oauthAccountId: route.oauthAccountId,
6282
+ providerData,
6283
+ contextWindow: route.contextWindow,
6284
+ supportedParameters: route.supportedParameters,
6285
+ reasoning: route.reasoning,
6286
+ interleavedReasoningField: route.interleavedReasoningField
6287
+ }
6288
+ ],
6289
+ { debug: trace }
6290
+ );
5951
6291
  proxyPort = proxyHandle.port;
5952
6292
  } else if (route.tier === "proxy") {
5953
- proxyHandle = await startCodexProxy([{
5954
- modelId: route.modelId,
5955
- npm: route.npm,
5956
- apiKey: route.apiKey,
5957
- baseURL: route.baseURL,
5958
- upstreamModelId: route.upstreamModelId,
5959
- providerId: route.providerId,
5960
- authType: route.authType,
5961
- oauthAccountId: route.oauthAccountId,
5962
- providerData: route.providerData,
5963
- supportedParameters: route.supportedParameters,
5964
- reasoning: route.reasoning,
5965
- interleavedReasoningField: route.interleavedReasoningField,
5966
- headers: route.headers
5967
- }], { debug: trace });
6293
+ proxyHandle = await startCodexProxy(
6294
+ [
6295
+ {
6296
+ modelId: route.modelId,
6297
+ npm: route.npm,
6298
+ apiKey: route.apiKey,
6299
+ baseURL: route.baseURL,
6300
+ upstreamModelId: route.upstreamModelId,
6301
+ providerId: route.providerId,
6302
+ authType: route.authType,
6303
+ oauthAccountId: route.oauthAccountId,
6304
+ providerData: route.providerData,
6305
+ supportedParameters: route.supportedParameters,
6306
+ reasoning: route.reasoning,
6307
+ interleavedReasoningField: route.interleavedReasoningField,
6308
+ headers: route.headers
6309
+ }
6310
+ ],
6311
+ { debug: trace }
6312
+ );
5968
6313
  proxyPort = proxyHandle.port;
5969
6314
  }
5970
6315
  const startingFavorite = resolvedFavorites.find(
@@ -5985,7 +6330,9 @@ Error: ${launchPlan.error}
5985
6330
  console.log(pc8.bold(pc8.cyan(" CONFIG PREVIEW \u2014 anygate codex")));
5986
6331
  console.log("");
5987
6332
  if (favoritesActive && resolvedFavorites.length > 0) {
5988
- console.log(` ${pc8.bold("Mode:")} Favorites Catalog (${resolvedFavorites.length} model${resolvedFavorites.length !== 1 ? "s" : ""})`);
6333
+ console.log(
6334
+ ` ${pc8.bold("Mode:")} Favorites Catalog (${resolvedFavorites.length} model${resolvedFavorites.length !== 1 ? "s" : ""})`
6335
+ );
5989
6336
  console.log("");
5990
6337
  console.log(` ${pc8.bold("Models:")}`);
5991
6338
  for (const r of resolvedFavorites) {
@@ -6053,7 +6400,7 @@ Error: ${launchPlan.error}
6053
6400
  // src/cli/codex.ts
6054
6401
  async function handleCodexCommand(parsed) {
6055
6402
  if (parsed.showVersion) {
6056
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
6403
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
6057
6404
  console.log(VERSION2);
6058
6405
  return 0;
6059
6406
  }
@@ -6071,7 +6418,6 @@ async function handleCodexCommand(parsed) {
6071
6418
  // src/apps/codex/app.ts
6072
6419
  import pc9 from "picocolors";
6073
6420
  import * as p10 from "@clack/prompts";
6074
- init_config();
6075
6421
 
6076
6422
  // src/apps/codex/app-provider-routes.ts
6077
6423
  function codexRouteToProxyRoute(provider, model, apiKey) {
@@ -6312,7 +6658,9 @@ function applyAppConfigPatch(spec, configPath = getCodexConfigPath()) {
6312
6658
  try {
6313
6659
  existing = parseCodexConfig(existingText);
6314
6660
  } catch (err) {
6315
- throw new Error(`Invalid existing Codex config at ${configPath}: ${err instanceof Error ? err.message : err}`);
6661
+ throw new Error(
6662
+ `Invalid existing Codex config at ${configPath}: ${err instanceof Error ? err.message : err}`
6663
+ );
6316
6664
  }
6317
6665
  const merged = mergeAppConfig(existing, spec);
6318
6666
  const text4 = `${stringify(merged)}
@@ -6350,9 +6698,24 @@ function restoreConfigFromState(state, configPath = getCodexConfigPath()) {
6350
6698
  if ("hadOpenAIBaseUrl" in state) {
6351
6699
  applyRestoreKey(config, "openai_base_url", Boolean(state.hadOpenAIBaseUrl), state.openAIBaseUrl);
6352
6700
  }
6353
- applyRestoreKey(config, "model_reasoning_effort", state.hadModelReasoningEffort, state.modelReasoningEffort);
6354
- applyRestoreNumber(config, "model_context_window", state.hadModelContextWindow ?? false, state.modelContextWindow);
6355
- applyRestoreNumber(config, "model_auto_compact_token_limit", state.hadModelAutoCompactTokenLimit ?? false, state.modelAutoCompactTokenLimit);
6701
+ applyRestoreKey(
6702
+ config,
6703
+ "model_reasoning_effort",
6704
+ state.hadModelReasoningEffort,
6705
+ state.modelReasoningEffort
6706
+ );
6707
+ applyRestoreNumber(
6708
+ config,
6709
+ "model_context_window",
6710
+ state.hadModelContextWindow ?? false,
6711
+ state.modelContextWindow
6712
+ );
6713
+ applyRestoreNumber(
6714
+ config,
6715
+ "model_auto_compact_token_limit",
6716
+ state.hadModelAutoCompactTokenLimit ?? false,
6717
+ state.modelAutoCompactTokenLimit
6718
+ );
6356
6719
  const sidecar = getCodexAppSidecarProfilePath();
6357
6720
  if (existsSync5(sidecar)) {
6358
6721
  try {
@@ -6379,14 +6742,7 @@ function previewAppConfigToml(spec) {
6379
6742
  }
6380
6743
 
6381
6744
  // src/apps/codex/app-session.ts
6382
- import {
6383
- copyFileSync as copyFileSync2,
6384
- existsSync as existsSync6,
6385
- mkdirSync as mkdirSync4,
6386
- readdirSync as readdirSync2,
6387
- readFileSync as readFileSync5,
6388
- rmSync as rmSync3
6389
- } from "fs";
6745
+ import { copyFileSync as copyFileSync2, existsSync as existsSync6, mkdirSync as mkdirSync4, readdirSync as readdirSync2, readFileSync as readFileSync5, rmSync as rmSync3 } from "fs";
6390
6746
  import { basename as basename2, join as join6 } from "path";
6391
6747
  function getAppSessionLockPath(env = process.env) {
6392
6748
  return join6(getAnygateICodexDir(env), "session-app.json");
@@ -6697,7 +7053,9 @@ async function runCodexAppVertexLaunch(configOnly, trace = false) {
6697
7053
  console.log(` ${pc9.bold("Project:")} ${config.project}`);
6698
7054
  console.log(` ${pc9.bold("Location:")} ${config.location}`);
6699
7055
  console.log(` ${pc9.bold("Model:")} ${selectedEntry.display_name}`);
6700
- console.log(` ${pc9.bold("Catalog:")} ${vertexModels.length} model${vertexModels.length !== 1 ? "s" : ""} available`);
7056
+ console.log(
7057
+ ` ${pc9.bold("Catalog:")} ${vertexModels.length} model${vertexModels.length !== 1 ? "s" : ""} available`
7058
+ );
6701
7059
  console.log("");
6702
7060
  console.log(` ${pc9.bold("Catalog file:")}`);
6703
7061
  console.log(` ${pc9.dim(shortenPath(catalogPath))}`);
@@ -6743,7 +7101,9 @@ async function runCodexAppVertexLaunch(configOnly, trace = false) {
6743
7101
  proxyPort
6744
7102
  });
6745
7103
  sessionActive = true;
6746
- p10.log.info(`Vertex AI \xB7 ${selectedEntry.display_name} \u2014 project: ${config.project} / location: ${config.location}`);
7104
+ p10.log.info(
7105
+ `Vertex AI \xB7 ${selectedEntry.display_name} \u2014 project: ${config.project} / location: ${config.location}`
7106
+ );
6747
7107
  logProxy(proxyPort);
6748
7108
  logActiveModel(selectedEntry.display_name, selectedEntry.id);
6749
7109
  try {
@@ -6803,8 +7163,14 @@ async function runCodexAppCommand(args, opts = {}) {
6803
7163
  console.error(pc9.red("anygate codex-app requires an interactive terminal."));
6804
7164
  return 1;
6805
7165
  }
6806
- console.error(pc9.yellow(`Another anygate codex-app session may be running (pid ${sessionCheck.lock.pid}).`));
6807
- console.error("Stop it with Ctrl+C in that terminal, or run anygate codex-app --restore after it exits.");
7166
+ console.error(
7167
+ pc9.yellow(
7168
+ `Another anygate codex-app session may be running (pid ${sessionCheck.lock.pid}).`
7169
+ )
7170
+ );
7171
+ console.error(
7172
+ "Stop it with Ctrl+C in that terminal, or run anygate codex-app --restore after it exits."
7173
+ );
6808
7174
  return 1;
6809
7175
  }
6810
7176
  }
@@ -6878,7 +7244,12 @@ async function runCodexAppCommand(args, opts = {}) {
6878
7244
  } else {
6879
7245
  let currentInitialProvider = prefs.lastCodexProvider && compatible.some((o) => o.id === prefs.lastCodexProvider) ? prefs.lastCodexProvider : compatible[0].id;
6880
7246
  while (true) {
6881
- const pickedProvider = await pickCodexProvider(compatible, prefs, favoritesActive, currentInitialProvider);
7247
+ const pickedProvider = await pickCodexProvider(
7248
+ compatible,
7249
+ prefs,
7250
+ favoritesActive,
7251
+ currentInitialProvider
7252
+ );
6882
7253
  if (!pickedProvider) return 0;
6883
7254
  if (pickedProvider === "__favorites__") {
6884
7255
  const favoritePick = await pickFavoriteStartingModel(
@@ -6925,18 +7296,19 @@ async function runCodexAppCommand(args, opts = {}) {
6925
7296
  let resolvedFavorites = [];
6926
7297
  let providersById = /* @__PURE__ */ new Map();
6927
7298
  if (favoritesActive) {
6928
- const res = await resolveCodexFavorites(activeProvider, selectedModel, compatible, favorites, "codex-app");
7299
+ const res = await resolveCodexFavorites(
7300
+ activeProvider,
7301
+ selectedModel,
7302
+ compatible,
7303
+ favorites,
7304
+ "codex-app"
7305
+ );
6929
7306
  resolvedFavorites = res.resolvedFavorites;
6930
7307
  providersById = res.providersById;
6931
7308
  }
6932
7309
  if (!configOnly) {
6933
7310
  const modelLabel = formatCodexModelLabel(selectedModel);
6934
- const confirmed = useFavoritesCatalog || await confirmCodexLaunch(
6935
- activeProvider.name,
6936
- modelLabel,
6937
- selectedModel.id,
6938
- appRoute
6939
- );
7311
+ const confirmed = useFavoritesCatalog || await confirmCodexLaunch(activeProvider.name, modelLabel, selectedModel.id, appRoute);
6940
7312
  if (!confirmed) {
6941
7313
  cloudCodeBackend?.handle.close();
6942
7314
  return 0;
@@ -6963,7 +7335,9 @@ async function runCodexAppCommand(args, opts = {}) {
6963
7335
  console.log(pc9.bold(pc9.cyan(" CONFIG PREVIEW \u2014 anygate codex-app")));
6964
7336
  console.log("");
6965
7337
  if (favoritesActive) {
6966
- console.log(` ${pc9.bold("Mode:")} Favorites Catalog (${resolvedFavorites.length} model${resolvedFavorites.length !== 1 ? "s" : ""})`);
7338
+ console.log(
7339
+ ` ${pc9.bold("Mode:")} Favorites Catalog (${resolvedFavorites.length} model${resolvedFavorites.length !== 1 ? "s" : ""})`
7340
+ );
6967
7341
  console.log("");
6968
7342
  console.log(` ${pc9.bold("Models:")}`);
6969
7343
  for (const r of resolvedFavorites) {
@@ -6973,7 +7347,9 @@ async function runCodexAppCommand(args, opts = {}) {
6973
7347
  console.log(` ${pc9.bold("Mode:")} Single model`);
6974
7348
  console.log(` ${pc9.bold("Provider:")} ${activeProvider.name}`);
6975
7349
  console.log(` ${pc9.bold("Model:")} ${formatCodexModelLabel(selectedModel)}`);
6976
- console.log(` ${pc9.bold("Catalog:")} ${routable.length} model${routable.length !== 1 ? "s" : ""} available`);
7350
+ console.log(
7351
+ ` ${pc9.bold("Catalog:")} ${routable.length} model${routable.length !== 1 ? "s" : ""} available`
7352
+ );
6977
7353
  }
6978
7354
  console.log("");
6979
7355
  console.log(` ${pc9.bold("config.toml patch preview:")}`);
@@ -7012,7 +7388,11 @@ async function runCodexAppCommand(args, opts = {}) {
7012
7388
  return { ...route2, oauthAccountId: provider?.oauthAccountId, providerData };
7013
7389
  });
7014
7390
  const startingAlias = backendRoutes[0].aliasId;
7015
- cloudCodeBackendFav = await startCloudCodeCatalogBackend(backendRoutes, startingAlias, trace);
7391
+ cloudCodeBackendFav = await startCloudCodeCatalogBackend(
7392
+ backendRoutes,
7393
+ startingAlias,
7394
+ trace
7395
+ );
7016
7396
  backendCodexRoutes = backendRoutes.map((cr) => ({
7017
7397
  modelId: cr.aliasId,
7018
7398
  npm: "@ai-sdk/anthropic",
@@ -7027,19 +7407,19 @@ async function runCodexAppCommand(args, opts = {}) {
7027
7407
  }));
7028
7408
  }
7029
7409
  const regularRoutes = buildCodexProxyRoutesFromResolved(regularResolved, providersById);
7030
- proxyHandle = await startCodexProxy(
7031
- [...backendCodexRoutes, ...regularRoutes],
7032
- { requireAuth: false, debug: trace }
7033
- );
7410
+ proxyHandle = await startCodexProxy([...backendCodexRoutes, ...regularRoutes], {
7411
+ requireAuth: false,
7412
+ debug: trace
7413
+ });
7034
7414
  proxyPort = proxyHandle.port;
7035
7415
  } else {
7036
7416
  if (!appProviderRoutes) {
7037
7417
  throw new Error("Codex App provider routes were not initialized");
7038
7418
  }
7039
- proxyHandle = await startCodexProxy(
7040
- appProviderRoutes.routes,
7041
- { requireAuth: false, debug: trace }
7042
- );
7419
+ proxyHandle = await startCodexProxy(appProviderRoutes.routes, {
7420
+ requireAuth: false,
7421
+ debug: trace
7422
+ });
7043
7423
  proxyPort = proxyHandle.port;
7044
7424
  }
7045
7425
  const modelLabel = formatCodexModelLabel(selectedModel);
@@ -7064,11 +7444,17 @@ async function runCodexAppCommand(args, opts = {}) {
7064
7444
  });
7065
7445
  sessionActive = true;
7066
7446
  const prevRecent = prefs.recentModelsByProvider?.[activeProvider.id] ?? [];
7067
- const updatedRecent = [selectedModel.id, ...prevRecent.filter((id) => id !== selectedModel.id)].slice(0, 3);
7447
+ const updatedRecent = [
7448
+ selectedModel.id,
7449
+ ...prevRecent.filter((id) => id !== selectedModel.id)
7450
+ ].slice(0, 3);
7068
7451
  savePreferences({
7069
7452
  lastCodexProvider: activeProvider.id,
7070
7453
  lastCodexModel: selectedModel.id,
7071
- recentModelsByProvider: { ...prefs.recentModelsByProvider, [activeProvider.id]: updatedRecent }
7454
+ recentModelsByProvider: {
7455
+ ...prefs.recentModelsByProvider,
7456
+ [activeProvider.id]: updatedRecent
7457
+ }
7072
7458
  });
7073
7459
  logProxy(proxyPort);
7074
7460
  logActiveModel(modelLabel, selectedModel.id);
@@ -7109,7 +7495,7 @@ async function runCodexAppCommand(args, opts = {}) {
7109
7495
  // src/cli/codex-app.ts
7110
7496
  async function handleCodexAppCommand(parsed) {
7111
7497
  if (parsed.showVersion) {
7112
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
7498
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
7113
7499
  console.log(VERSION2);
7114
7500
  return 0;
7115
7501
  }
@@ -7143,7 +7529,6 @@ This command launches the ChatGPT Desktop app with anygate's provider registry.
7143
7529
  // src/apps/claude/desktop.ts
7144
7530
  import pc10 from "picocolors";
7145
7531
  import * as p11 from "@clack/prompts";
7146
- init_config();
7147
7532
 
7148
7533
  // src/apps/claude/desktop-app.ts
7149
7534
  import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync4, mkdirSync as mkdirSync5 } from "fs";
@@ -7444,7 +7829,13 @@ async function runClaudeAppCommand(args, boot) {
7444
7829
  } else if (useFavoritesCatalog && hasFavorites) {
7445
7830
  useFavorites = true;
7446
7831
  } else {
7447
- const pickedProvider = await pickCodexProvider(compatible, prefs, hasFavorites, void 0, "Claude");
7832
+ const pickedProvider = await pickCodexProvider(
7833
+ compatible,
7834
+ prefs,
7835
+ hasFavorites,
7836
+ void 0,
7837
+ "Claude"
7838
+ );
7448
7839
  if (!pickedProvider) return 0;
7449
7840
  if (pickedProvider === "__favorites__") {
7450
7841
  useFavorites = true;
@@ -7470,7 +7861,9 @@ async function runClaudeAppCommand(args, boot) {
7470
7861
  const antigravityProvider = catalog.find((lp) => lp.id === "antigravity");
7471
7862
  const cloudCodeFavoriteModels = favorites.map((fav) => {
7472
7863
  if (fav.providerId !== "antigravity") return null;
7473
- const model = antigravityProvider?.models.find((m) => m.id === fav.modelId);
7864
+ const model = antigravityProvider?.models.find(
7865
+ (m) => m.id === fav.modelId
7866
+ );
7474
7867
  return model?.modelFormat === "cloud-code" ? model : null;
7475
7868
  }).filter((m) => m !== null);
7476
7869
  const regularFavorites = favorites.filter(
@@ -7488,21 +7881,23 @@ async function runClaudeAppCommand(args, boot) {
7488
7881
  const startingAlias = cloudRoutes[0].aliasId;
7489
7882
  cloudCodeFavBackend = await startCloudCodeCatalogBackend(cloudRoutes, startingAlias, trace);
7490
7883
  const favBackend = cloudCodeFavBackend;
7491
- cloudCodeServerModels = cloudCodeFavoriteModels.map((model) => modelToServerModelInfo(model, antigravityProvider, {
7492
- isFree: false,
7493
- providerId: "antigravity",
7494
- sourceBackend: "antigravity",
7495
- modelFormat: "anthropic",
7496
- cost: void 0,
7497
- baseUrl: `http://127.0.0.1:${favBackend.port}`,
7498
- completionsUrl: void 0,
7499
- npm: void 0,
7500
- apiBaseUrl: void 0,
7501
- apiKey: favBackend.token,
7502
- authType: void 0,
7503
- oauthAccountId: void 0,
7504
- headers: void 0
7505
- }));
7884
+ cloudCodeServerModels = cloudCodeFavoriteModels.map(
7885
+ (model) => modelToServerModelInfo(model, antigravityProvider, {
7886
+ isFree: false,
7887
+ providerId: "antigravity",
7888
+ sourceBackend: "antigravity",
7889
+ modelFormat: "anthropic",
7890
+ cost: void 0,
7891
+ baseUrl: `http://127.0.0.1:${favBackend.port}`,
7892
+ completionsUrl: void 0,
7893
+ npm: void 0,
7894
+ apiBaseUrl: void 0,
7895
+ apiKey: favBackend.token,
7896
+ authType: void 0,
7897
+ oauthAccountId: void 0,
7898
+ headers: void 0
7899
+ })
7900
+ );
7506
7901
  }
7507
7902
  const regularLocalProviders = providersForTarget(catalog, "claude-app");
7508
7903
  const regularAllModels = regularLocalProviders.flatMap(
@@ -7521,17 +7916,19 @@ async function runClaudeAppCommand(args, boot) {
7521
7916
  const providerData = activeProvider.providerData ?? {};
7522
7917
  const cloudRoute = buildCloudCodeProxyRoute(selectedModel, activeProvider.apiKey, providerData);
7523
7918
  cloudCodeBackend = await startCloudCodeCatalogBackend([cloudRoute], cloudRoute.aliasId, trace);
7524
- serverModels = [modelToServerModelInfo(selectedModel, activeProvider, {
7525
- modelFormat: "anthropic",
7526
- baseUrl: `http://127.0.0.1:${cloudCodeBackend.port}`,
7527
- completionsUrl: void 0,
7528
- npm: void 0,
7529
- apiBaseUrl: void 0,
7530
- apiKey: cloudCodeBackend.token,
7531
- authType: void 0,
7532
- oauthAccountId: void 0,
7533
- headers: void 0
7534
- })];
7919
+ serverModels = [
7920
+ modelToServerModelInfo(selectedModel, activeProvider, {
7921
+ modelFormat: "anthropic",
7922
+ baseUrl: `http://127.0.0.1:${cloudCodeBackend.port}`,
7923
+ completionsUrl: void 0,
7924
+ npm: void 0,
7925
+ apiBaseUrl: void 0,
7926
+ apiKey: cloudCodeBackend.token,
7927
+ authType: void 0,
7928
+ oauthAccountId: void 0,
7929
+ headers: void 0
7930
+ })
7931
+ ];
7535
7932
  } else {
7536
7933
  serverModels = [modelToServerModelInfo(selectedModel, activeProvider)];
7537
7934
  }
@@ -7562,11 +7959,17 @@ async function runClaudeAppCommand(args, boot) {
7562
7959
  setupExitCleanup(uuid);
7563
7960
  if (!useFavorites) {
7564
7961
  const prevRecent = prefs.recentModelsByProvider?.[activeProvider.id] ?? [];
7565
- const updatedRecent = [selectedModel.id, ...prevRecent.filter((id) => id !== selectedModel.id)].slice(0, 3);
7962
+ const updatedRecent = [
7963
+ selectedModel.id,
7964
+ ...prevRecent.filter((id) => id !== selectedModel.id)
7965
+ ].slice(0, 3);
7566
7966
  savePreferences({
7567
7967
  lastCodexProvider: activeProvider.id,
7568
7968
  lastCodexModel: selectedModel.id,
7569
- recentModelsByProvider: { ...prefs.recentModelsByProvider, [activeProvider.id]: updatedRecent }
7969
+ recentModelsByProvider: {
7970
+ ...prefs.recentModelsByProvider,
7971
+ [activeProvider.id]: updatedRecent
7972
+ }
7570
7973
  });
7571
7974
  }
7572
7975
  console.log(`
@@ -7612,7 +8015,7 @@ ${pc10.bold("Claude Desktop 3P Mode Active")}`);
7612
8015
  // src/cli/claude-app.ts
7613
8016
  async function handleClaudeAppCommand(parsed) {
7614
8017
  if (parsed.showVersion) {
7615
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
8018
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
7616
8019
  console.log(VERSION2);
7617
8020
  return 0;
7618
8021
  }
@@ -7644,10 +8047,8 @@ This command launches the Claude Desktop app with anygate's provider registry.
7644
8047
  // src/apps/gemini/cli.ts
7645
8048
  import pc11 from "picocolors";
7646
8049
  import * as p13 from "@clack/prompts";
7647
- init_config();
7648
8050
 
7649
8051
  // src/apps/gemini/launch.ts
7650
- init_config();
7651
8052
  import { spawn as spawn2 } from "child_process";
7652
8053
  import { existsSync as existsSync9, mkdirSync as mkdirSync6, mkdtempSync, rmSync as rmSync5, writeFileSync as writeFileSync6 } from "fs";
7653
8054
  import { homedir as homedir6, tmpdir } from "os";
@@ -7737,7 +8138,9 @@ function launchGemini(geminiPath, modelId, env, extraArgs) {
7737
8138
  import * as p12 from "@clack/prompts";
7738
8139
  async function pickGeminiProvider(providers, prefs, hasFavorites = false, initialProviderId) {
7739
8140
  if (providers.length === 0 && !hasFavorites) return null;
7740
- const options = providers.map((lp) => providerSelectOption(lp));
8141
+ const options = providers.map(
8142
+ (lp) => providerSelectOption(lp)
8143
+ );
7741
8144
  if (hasFavorites) {
7742
8145
  options.unshift({
7743
8146
  value: "__favorites__",
@@ -7854,7 +8257,8 @@ function rejectGeminiManagedFlags(geminiArgs) {
7854
8257
  if (takesValue.has(arg)) i++;
7855
8258
  continue;
7856
8259
  }
7857
- if (arg.startsWith("--model=") || arg.startsWith("--provider=") || arg.startsWith("-m=")) continue;
8260
+ if (arg.startsWith("--model=") || arg.startsWith("--provider=") || arg.startsWith("-m="))
8261
+ continue;
7858
8262
  out.push(arg);
7859
8263
  }
7860
8264
  return out;
@@ -7889,7 +8293,9 @@ function lookupGeminiRoute(routes, requestedModel, defaultRoute) {
7889
8293
  }
7890
8294
  const fallback = defaultRoute ?? routes[0];
7891
8295
  if (requestedModel !== fallback.aliasId) {
7892
- console.error(`[gemini-proxy] model '${requestedModel}' not in catalog \u2014 remapping to default route '${fallback.aliasId}' (upstream: ${fallback.realModelId})`);
8296
+ console.error(
8297
+ `[gemini-proxy] model '${requestedModel}' not in catalog \u2014 remapping to default route '${fallback.aliasId}' (upstream: ${fallback.realModelId})`
8298
+ );
7893
8299
  }
7894
8300
  return fallback;
7895
8301
  }
@@ -8037,7 +8443,9 @@ async function startGeminiProxy(routes, debug = false) {
8037
8443
  const plog = debug ? makeTraceLogger(getGeminiProxyDebugLogPath()) : () => {
8038
8444
  };
8039
8445
  const onRejection = (reason) => {
8040
- plog(`Unhandled Rejection: ${reason instanceof Error ? reason.stack || reason.message : String(reason)}`);
8446
+ plog(
8447
+ `Unhandled Rejection: ${reason instanceof Error ? reason.stack || reason.message : String(reason)}`
8448
+ );
8041
8449
  };
8042
8450
  const onException = (error) => {
8043
8451
  plog(`Uncaught Exception: ${error.stack || error.message}`);
@@ -8117,7 +8525,7 @@ ${rawBody}`);
8117
8525
  const modelCommand = parseModelCommand(lastUserTurn);
8118
8526
  if (modelCommand !== null) {
8119
8527
  if (modelCommand === "") {
8120
- const current = sessionRouteOverride ?? (lookupGeminiRoute(routes, requestedModel) ?? defaultRoute);
8528
+ const current = sessionRouteOverride ?? lookupGeminiRoute(routes, requestedModel) ?? defaultRoute;
8121
8529
  const availableList = routes.map((r) => ` - ${r.aliasId} (${r.displayName})`).join("\n");
8122
8530
  const exampleId = routes.length > 1 ? routes[1].aliasId : routes[0]?.aliasId ?? "deepseek-v4";
8123
8531
  const text4 = `Current model: ${current.displayName} (${current.aliasId})
@@ -8134,16 +8542,25 @@ Example: .model ${exampleId}`;
8134
8542
  if (targetRoute) {
8135
8543
  sessionRouteOverride = targetRoute;
8136
8544
  plog(`.model switch: ${targetRoute.aliasId} (${targetRoute.realModelId})`);
8137
- sendMockGeminiResponse(res, `\u2705 Switched model to ${targetRoute.displayName} (${targetRoute.aliasId})`, isStream, targetRoute.aliasId);
8545
+ sendMockGeminiResponse(
8546
+ res,
8547
+ `\u2705 Switched model to ${targetRoute.displayName} (${targetRoute.aliasId})`,
8548
+ isStream,
8549
+ targetRoute.aliasId
8550
+ );
8138
8551
  } else {
8139
8552
  const available = routes.map((r) => r.aliasId).join(", ");
8140
- sendMockGeminiResponse(res, `\u274C Model '${modelCommand}' not found.
8553
+ sendMockGeminiResponse(
8554
+ res,
8555
+ `\u274C Model '${modelCommand}' not found.
8141
8556
 
8142
- Available: ${available}`, isStream);
8557
+ Available: ${available}`,
8558
+ isStream
8559
+ );
8143
8560
  }
8144
8561
  return;
8145
8562
  }
8146
- const route = sessionRouteOverride ?? (lookupGeminiRoute(routes, requestedModel) ?? defaultRoute);
8563
+ const route = sessionRouteOverride ?? lookupGeminiRoute(routes, requestedModel) ?? defaultRoute;
8147
8564
  plog(`Route selected: ${route.aliasId} (upstream model: ${route.realModelId})`);
8148
8565
  body.contents = sanitizeModelSwitchTurns(body.contents || []);
8149
8566
  const languageModel = await getOrInitModel(route);
@@ -8155,7 +8572,12 @@ Available: ${available}`, isStream);
8155
8572
  params.providerOptions,
8156
8573
  deepMergeProviderOptions(
8157
8574
  thinkingProviderOptions(route.npm || "@ai-sdk/openai-compatible"),
8158
- effortProviderOptions(route.npm || "@ai-sdk/openai-compatible", "high", route.realModelId, route)
8575
+ effortProviderOptions(
8576
+ route.npm || "@ai-sdk/openai-compatible",
8577
+ "high",
8578
+ route.realModelId,
8579
+ route
8580
+ )
8159
8581
  )
8160
8582
  );
8161
8583
  plog(`Translated SDK params:
@@ -8164,7 +8586,7 @@ ${JSON.stringify(params, null, 2)}`);
8164
8586
  res.writeHead(200, {
8165
8587
  "Content-Type": "text/event-stream",
8166
8588
  "Cache-Control": "no-cache",
8167
- "Connection": "keep-alive"
8589
+ Connection: "keep-alive"
8168
8590
  });
8169
8591
  plog("Starting streamText...");
8170
8592
  const { fullStream } = streamText2({
@@ -8179,10 +8601,12 @@ ${JSON.stringify(params, null, 2)}`);
8179
8601
  if (isThinking && (p18.type === "tool-input-start" || p18.type === "tool-call" || p18.type === "finish")) {
8180
8602
  isThinking = false;
8181
8603
  const chunk = {
8182
- candidates: [{ content: { role: "model", parts: [{ text: `
8604
+ candidates: [
8605
+ { content: { role: "model", parts: [{ text: `
8183
8606
  </thinking>
8184
8607
 
8185
- ` }] } }],
8608
+ ` }] } }
8609
+ ],
8186
8610
  modelVersion: route.aliasId
8187
8611
  };
8188
8612
  res.write(`data: ${JSON.stringify(chunk)}
@@ -8213,12 +8637,14 @@ ${JSON.stringify(params, null, 2)}`);
8213
8637
  ` + text4;
8214
8638
  }
8215
8639
  const chunk = {
8216
- candidates: [{
8217
- content: {
8218
- role: "model",
8219
- parts: [{ text: text4 }]
8640
+ candidates: [
8641
+ {
8642
+ content: {
8643
+ role: "model",
8644
+ parts: [{ text: text4 }]
8645
+ }
8220
8646
  }
8221
- }],
8647
+ ],
8222
8648
  modelVersion: route.aliasId
8223
8649
  };
8224
8650
  const data = `data: ${JSON.stringify(chunk)}
@@ -8237,14 +8663,18 @@ ${JSON.stringify(params, null, 2)}`);
8237
8663
  const name = buf ? buf.name : p18.toolName;
8238
8664
  plog(`Streaming tool call: ${name} with args: ${JSON.stringify(args)}`);
8239
8665
  const chunk = {
8240
- candidates: [{
8241
- content: {
8242
- role: "model",
8243
- parts: [{
8244
- functionCall: { name, args }
8245
- }]
8666
+ candidates: [
8667
+ {
8668
+ content: {
8669
+ role: "model",
8670
+ parts: [
8671
+ {
8672
+ functionCall: { name, args }
8673
+ }
8674
+ ]
8675
+ }
8246
8676
  }
8247
- }],
8677
+ ],
8248
8678
  modelVersion: route.aliasId
8249
8679
  };
8250
8680
  res.write(`data: ${JSON.stringify(chunk)}
@@ -8252,9 +8682,11 @@ ${JSON.stringify(params, null, 2)}`);
8252
8682
  `);
8253
8683
  } else if (p18.type === "finish") {
8254
8684
  const chunk = {
8255
- candidates: [{
8256
- finishReason: mapFinishReason(p18.finishReason ?? "")
8257
- }],
8685
+ candidates: [
8686
+ {
8687
+ finishReason: mapFinishReason(p18.finishReason ?? "")
8688
+ }
8689
+ ],
8258
8690
  usageMetadata: {
8259
8691
  promptTokenCount: p18.totalUsage?.inputTokens || 0,
8260
8692
  candidatesTokenCount: p18.totalUsage?.outputTokens || 0
@@ -8295,13 +8727,15 @@ ${result.reasoning}
8295
8727
  }
8296
8728
  }
8297
8729
  const response = {
8298
- candidates: [{
8299
- content: {
8300
- role: "model",
8301
- parts
8302
- },
8303
- finishReason: mapFinishReason(result.finishReason ?? "")
8304
- }],
8730
+ candidates: [
8731
+ {
8732
+ content: {
8733
+ role: "model",
8734
+ parts
8735
+ },
8736
+ finishReason: mapFinishReason(result.finishReason ?? "")
8737
+ }
8738
+ ],
8305
8739
  usageMetadata: {
8306
8740
  promptTokenCount: result.usage?.inputTokens || 0,
8307
8741
  candidatesTokenCount: result.usage?.outputTokens || 0
@@ -8319,13 +8753,19 @@ ${JSON.stringify(response, null, 2)}`);
8319
8753
  res.writeHead(404);
8320
8754
  res.end("Not Found");
8321
8755
  } catch (err) {
8322
- plog(`Error handling request: ${err instanceof Error ? err.stack || err.message : String(err)}`);
8756
+ plog(
8757
+ `Error handling request: ${err instanceof Error ? err.stack || err.message : String(err)}`
8758
+ );
8323
8759
  const errMsg = formatUpstreamError(err);
8324
8760
  if (debug) {
8325
8761
  console.error(`[Gemini Proxy] ${errMsg}`);
8326
8762
  }
8327
8763
  if (!res.headersSent) {
8328
- sendMockGeminiResponse(res, `\u26A0 ${errMsg}`, req.url?.includes("streamGenerateContent") ?? false);
8764
+ sendMockGeminiResponse(
8765
+ res,
8766
+ `\u26A0 ${errMsg}`,
8767
+ req.url?.includes("streamGenerateContent") ?? false
8768
+ );
8329
8769
  } else {
8330
8770
  try {
8331
8771
  writeGeminiStreamText(res, `\u26A0 ${errMsg}`);
@@ -8412,28 +8852,34 @@ function sendMockGeminiResponse(res, text4, isStream, modelVersion) {
8412
8852
  res.writeHead(200, {
8413
8853
  "Content-Type": "text/event-stream",
8414
8854
  "Cache-Control": "no-cache",
8415
- "Connection": "keep-alive"
8855
+ Connection: "keep-alive"
8416
8856
  });
8417
8857
  writeGeminiStreamText(res, text4, modelVersion);
8418
8858
  res.end();
8419
8859
  } else {
8420
8860
  res.writeHead(200, { "Content-Type": "application/json" });
8421
- res.end(JSON.stringify({
8422
- candidates: [{
8423
- content: { role: "model", parts: [{ text: text4 }] },
8424
- finishReason: "STOP"
8425
- }],
8426
- usageMetadata: { promptTokenCount: 0, candidatesTokenCount: 0 },
8427
- ...modelVersion ? { modelVersion } : {}
8428
- }));
8861
+ res.end(
8862
+ JSON.stringify({
8863
+ candidates: [
8864
+ {
8865
+ content: { role: "model", parts: [{ text: text4 }] },
8866
+ finishReason: "STOP"
8867
+ }
8868
+ ],
8869
+ usageMetadata: { promptTokenCount: 0, candidatesTokenCount: 0 },
8870
+ ...modelVersion ? { modelVersion } : {}
8871
+ })
8872
+ );
8429
8873
  }
8430
8874
  }
8431
8875
  function writeGeminiStreamText(res, text4, modelVersion) {
8432
8876
  const chunk = {
8433
- candidates: [{
8434
- content: { role: "model", parts: [{ text: text4 }] },
8435
- finishReason: "STOP"
8436
- }],
8877
+ candidates: [
8878
+ {
8879
+ content: { role: "model", parts: [{ text: text4 }] },
8880
+ finishReason: "STOP"
8881
+ }
8882
+ ],
8437
8883
  usageMetadata: { promptTokenCount: 0, candidatesTokenCount: 0 },
8438
8884
  ...modelVersion ? { modelVersion } : {}
8439
8885
  };
@@ -8602,7 +9048,9 @@ Error: ${launchPlan.error}
8602
9048
  const compatible = providersForTarget(providersForPicker(catalog), "gemini");
8603
9049
  if (compatible.length === 0) {
8604
9050
  p13.log.warn("No Gemini-compatible providers in your registry.");
8605
- p13.log.info("Add a provider with anygate providers add, or sign in with anygate providers auth openai.");
9051
+ p13.log.info(
9052
+ "Add a provider with anygate providers add, or sign in with anygate providers auth openai."
9053
+ );
8606
9054
  return 0;
8607
9055
  }
8608
9056
  let activeProvider = compatible.find((lp) => lp.id === prefs.lastGeminiProvider) ?? compatible[0];
@@ -8611,7 +9059,6 @@ Error: ${launchPlan.error}
8611
9059
  p13.log.error(`Provider "${activeProvider.name}" has no models available.`);
8612
9060
  return 1;
8613
9061
  }
8614
- ;
8615
9062
  if (launchPlan.skip && launchPlan.target) {
8616
9063
  const resolved = findProviderAndModel(compatible, launchPlan.target);
8617
9064
  if (!resolved) {
@@ -8660,9 +9107,7 @@ Error: ${launchPlan.error}
8660
9107
  recordLaunchSelection("gemini", activeProvider.id, selectedModel.id, prefs);
8661
9108
  const launchApiKey = await resolveLocalProviderApiKey(activeProvider);
8662
9109
  if (!launchApiKey?.trim()) {
8663
- p13.log.error(
8664
- new CredentialUnavailableError(activeProvider.id).userMessage
8665
- );
9110
+ p13.log.error(new CredentialUnavailableError(activeProvider.id).userMessage);
8666
9111
  return 1;
8667
9112
  }
8668
9113
  const providerRoutes = activeProvider.models.map((m) => ({
@@ -8785,7 +9230,7 @@ Error: ${launchPlan.error}
8785
9230
  // src/cli/gemini.ts
8786
9231
  async function handleGeminiCommand(parsed) {
8787
9232
  if (parsed.showVersion) {
8788
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
9233
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
8789
9234
  console.log(VERSION2);
8790
9235
  return 0;
8791
9236
  }
@@ -8800,7 +9245,6 @@ async function handleGeminiCommand(parsed) {
8800
9245
  }
8801
9246
 
8802
9247
  // src/apps/gemini/antigravity.ts
8803
- init_config();
8804
9248
  import pc12 from "picocolors";
8805
9249
  import * as p14 from "@clack/prompts";
8806
9250
  import { appendFileSync as appendFileSync2 } from "fs";
@@ -9085,7 +9529,9 @@ function evaluateAgySwitchCompatibility(opts) {
9085
9529
  const shapeMatches = validation.warnings.length === 0 && validation.switchSlots.length > 0;
9086
9530
  const warnings = [];
9087
9531
  if (opts.versionReadError) {
9088
- warnings.push(`Could not read agy --version (${opts.versionReadError}); validating AGY fixture shape instead.`);
9532
+ warnings.push(
9533
+ `Could not read agy --version (${opts.versionReadError}); validating AGY fixture shape instead.`
9534
+ );
9089
9535
  }
9090
9536
  if (opts.version && KNOWN_INCOMPATIBLE_AGY_VERSIONS.has(opts.version)) {
9091
9537
  return {
@@ -9109,9 +9555,13 @@ function evaluateAgySwitchCompatibility(opts) {
9109
9555
  };
9110
9556
  }
9111
9557
  if (opts.version && !KNOWN_COMPATIBLE_AGY_VERSIONS.has(opts.version)) {
9112
- warnings.push(`Unvalidated AGY version ${opts.version}; fixture shape matches, so multi-model switching remains enabled.`);
9558
+ warnings.push(
9559
+ `Unvalidated AGY version ${opts.version}; fixture shape matches, so multi-model switching remains enabled.`
9560
+ );
9113
9561
  } else if (!opts.version && !opts.versionReadError) {
9114
- warnings.push("AGY version is unknown; fixture shape matches, so multi-model switching remains enabled.");
9562
+ warnings.push(
9563
+ "AGY version is unknown; fixture shape matches, so multi-model switching remains enabled."
9564
+ );
9115
9565
  }
9116
9566
  return {
9117
9567
  mode: "multi-model",
@@ -9169,10 +9619,7 @@ function withCascadeCheckpointer(entry, maxTokenLimit = 128e3) {
9169
9619
  function applyRouteContextBounds(entry, route) {
9170
9620
  const maxTokenLimit = route.contextWindow ?? 128e3;
9171
9621
  const maxOutputTokens = Math.min(entry.maxOutputTokens ?? 65536, maxTokenLimit);
9172
- const checkpointTokenLimit = Math.min(
9173
- 128e3,
9174
- Math.max(1, maxTokenLimit - maxOutputTokens)
9175
- );
9622
+ const checkpointTokenLimit = Math.min(128e3, Math.max(1, maxTokenLimit - maxOutputTokens));
9176
9623
  entry.maxTokens = maxTokenLimit;
9177
9624
  entry.maxOutputTokens = maxOutputTokens;
9178
9625
  entry.supportsImages = route.inputTypes?.includes("image") ?? false;
@@ -9255,7 +9702,9 @@ function injectGatewayModels(fixture, routes, templateKey) {
9255
9702
  if (routes.length > 0) {
9256
9703
  result.models[GATEWAY_CASCADE_ANCHOR_ID] ??= structuredClone(template);
9257
9704
  result.models[GATEWAY_CASCADE_FALLBACK_ID] ??= structuredClone(GATEWAY_CASCADE_FALLBACK_ENTRY);
9258
- result.models[GATEWAY_CASCADE_INTENT_MODEL_ID] ??= structuredClone(GATEWAY_CASCADE_INTENT_MODEL_ENTRY);
9705
+ result.models[GATEWAY_CASCADE_INTENT_MODEL_ID] ??= structuredClone(
9706
+ GATEWAY_CASCADE_INTENT_MODEL_ENTRY
9707
+ );
9259
9708
  if (!result.models[GATEWAY_CASCADE_PLAN_ANCHOR_ID]) {
9260
9709
  const planAnchor = withCascadeCheckpointer(structuredClone(template));
9261
9710
  planAnchor.model = GATEWAY_CASCADE_PLAN_MODEL;
@@ -9274,9 +9723,11 @@ function injectGatewayModels(fixture, routes, templateKey) {
9274
9723
  result.agentModelSorts = [
9275
9724
  {
9276
9725
  displayName: "Recommended",
9277
- groups: [{
9278
- modelIds: slots.map((slot) => slot.slotId)
9279
- }]
9726
+ groups: [
9727
+ {
9728
+ modelIds: slots.map((slot) => slot.slotId)
9729
+ }
9730
+ ]
9280
9731
  }
9281
9732
  ];
9282
9733
  return result;
@@ -9321,6 +9772,7 @@ function buildAntigravityRoutes(resolvedFavorites, maxRoutes = MAX_MODEL_CATALOG
9321
9772
  ...fav.authType ? { authType: fav.authType } : {},
9322
9773
  ...fav.oauthAccountId ? { oauthAccountId: fav.oauthAccountId } : {},
9323
9774
  ...fav.providerData ? { providerData: fav.providerData } : {},
9775
+ ...fav.headers ? { headers: fav.headers } : {},
9324
9776
  baseURL,
9325
9777
  contextWindow,
9326
9778
  inputTypes
@@ -10603,8 +11055,16 @@ async function startCloudCodeGateway(routes, opts = {}) {
10603
11055
  if (trace) log17(`[gateway] active route: ${route.catalogId} via ${model}`);
10604
11056
  }
10605
11057
  if (isCloudCodeOAuthRoute(route)) {
10606
- handleCloudCodeForwardRequest(res, route, parsed, lowerUrl, log17).catch((err) => {
10607
- log17(`[gateway] cloud-code forward error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
11058
+ handleCloudCodeForwardRequest(
11059
+ res,
11060
+ route,
11061
+ parsed,
11062
+ lowerUrl,
11063
+ log17
11064
+ ).catch((err) => {
11065
+ log17(
11066
+ `[gateway] cloud-code forward error: ${err instanceof Error ? err.stack || err.message : String(err)}`
11067
+ );
10608
11068
  if (!res.headersSent) {
10609
11069
  respondJson(res, 500, { error: { code: 500, message: formatUpstreamError(err) } });
10610
11070
  } else if (!res.writableEnded) {
@@ -10616,7 +11076,11 @@ async function startCloudCodeGateway(routes, opts = {}) {
10616
11076
  const baseProviderOptions = providerOptionsCache.get(route.catalogId);
10617
11077
  const isStream = lowerUrl.includes("stream");
10618
11078
  const conversationKey = conversationKeyFromRequest(parsed);
10619
- const requestOptions = reasoningEchoOptionsForRoute(route, parsed, reasoningEchoesByConversation);
11079
+ const requestOptions = reasoningEchoOptionsForRoute(
11080
+ route,
11081
+ parsed,
11082
+ reasoningEchoesByConversation
11083
+ );
10620
11084
  const rememberReasoning = (reasoning) => {
10621
11085
  if (!shouldEchoReasoningForRoute(route)) return;
10622
11086
  rememberReasoningEcho(reasoningEchoesByConversation, conversationKey, reasoning);
@@ -10626,7 +11090,9 @@ async function startCloudCodeGateway(routes, opts = {}) {
10626
11090
  requestOptions,
10627
11091
  onReasoningWithToolCall: rememberReasoning
10628
11092
  }).catch((err) => {
10629
- log17(`[gateway] stream error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
11093
+ log17(
11094
+ `[gateway] stream error: ${err instanceof Error ? err.stack || err.message : String(err)}`
11095
+ );
10630
11096
  if (!res.headersSent) {
10631
11097
  respondJson(res, 500, { error: { code: 500, message: formatUpstreamError(err) } });
10632
11098
  } else if (!res.writableEnded) {
@@ -10638,7 +11104,9 @@ async function startCloudCodeGateway(routes, opts = {}) {
10638
11104
  requestOptions,
10639
11105
  onReasoningWithToolCall: rememberReasoning
10640
11106
  }).catch((err) => {
10641
- log17(`[gateway] unary error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
11107
+ log17(
11108
+ `[gateway] unary error: ${err instanceof Error ? err.stack || err.message : String(err)}`
11109
+ );
10642
11110
  if (!res.headersSent) {
10643
11111
  respondJson(res, 500, { error: { code: 500, message: formatUpstreamError(err) } });
10644
11112
  }
@@ -10659,7 +11127,13 @@ async function startCloudCodeGateway(routes, opts = {}) {
10659
11127
  return;
10660
11128
  }
10661
11129
  if (lowerUrl.includes("userquota")) {
10662
- respondJson(res, 200, { quotaSummary: { remainingQueries: 9999, totalQueries: 9999, quotaType: "GATEWAY_UNLIMITED" } });
11130
+ respondJson(res, 200, {
11131
+ quotaSummary: {
11132
+ remainingQueries: 9999,
11133
+ totalQueries: 9999,
11134
+ quotaType: "GATEWAY_UNLIMITED"
11135
+ }
11136
+ });
10663
11137
  return;
10664
11138
  }
10665
11139
  if (lowerUrl.includes("userinfo")) {
@@ -10738,7 +11212,12 @@ async function startCloudCodeGateway(routes, opts = {}) {
10738
11212
  }
10739
11213
  respondJson(res, 200, {});
10740
11214
  }).catch((err) => {
10741
- respondJson(res, 400, { error: { code: 400, message: `Failed to read request: ${err instanceof Error ? err.message : String(err)}` } });
11215
+ respondJson(res, 400, {
11216
+ error: {
11217
+ code: 400,
11218
+ message: `Failed to read request: ${err instanceof Error ? err.message : String(err)}`
11219
+ }
11220
+ });
10742
11221
  });
10743
11222
  });
10744
11223
  return new Promise((resolve, reject2) => {
@@ -11012,10 +11491,13 @@ function respondJson(res, status, data) {
11012
11491
  res.end(body);
11013
11492
  }
11014
11493
  async function handleStreamingRequest(res, route, providerOptions, parsed, log17, options = {}) {
11015
- const sdkParams = applyClaudeCodeOAuthIdentity(route, translateRequest(parsed, {
11016
- ...options.requestOptions,
11017
- maxTools: maxToolsForNpm(route.npm)
11018
- }));
11494
+ const sdkParams = applyClaudeCodeOAuthIdentity(
11495
+ route,
11496
+ translateRequest(parsed, {
11497
+ ...options.requestOptions,
11498
+ maxTools: maxToolsForNpm(route.npm)
11499
+ })
11500
+ );
11019
11501
  const effectiveProviderOptions = deepMergeProviderOptions(
11020
11502
  providerOptions,
11021
11503
  sdkParams.providerOptions
@@ -11028,7 +11510,8 @@ async function handleStreamingRequest(res, route, providerOptions, parsed, log17
11028
11510
  providerId: route.providerId,
11029
11511
  authType: route.authType,
11030
11512
  oauthAccountId: route.oauthAccountId,
11031
- providerData: route.providerData
11513
+ providerData: route.providerData,
11514
+ headers: route.headers
11032
11515
  });
11033
11516
  const responseId = `gateway-${Date.now()}`;
11034
11517
  const { fullStream } = streamText3({
@@ -11148,10 +11631,13 @@ async function handleStreamingRequest(res, route, providerOptions, parsed, log17
11148
11631
  res.end();
11149
11632
  }
11150
11633
  async function handleUnaryRequest(res, route, providerOptions, parsed, _log, options = {}) {
11151
- const sdkParams = applyClaudeCodeOAuthIdentity(route, translateRequest(parsed, {
11152
- ...options.requestOptions,
11153
- maxTools: maxToolsForNpm(route.npm)
11154
- }));
11634
+ const sdkParams = applyClaudeCodeOAuthIdentity(
11635
+ route,
11636
+ translateRequest(parsed, {
11637
+ ...options.requestOptions,
11638
+ maxTools: maxToolsForNpm(route.npm)
11639
+ })
11640
+ );
11155
11641
  const effectiveProviderOptions = deepMergeProviderOptions(
11156
11642
  providerOptions,
11157
11643
  sdkParams.providerOptions
@@ -11164,7 +11650,8 @@ async function handleUnaryRequest(res, route, providerOptions, parsed, _log, opt
11164
11650
  providerId: route.providerId,
11165
11651
  authType: route.authType,
11166
11652
  oauthAccountId: route.oauthAccountId,
11167
- providerData: route.providerData
11653
+ providerData: route.providerData,
11654
+ headers: route.headers
11168
11655
  });
11169
11656
  const responseId = `gateway-${Date.now()}`;
11170
11657
  const result = await generateText3({
@@ -11186,7 +11673,10 @@ async function handleUnaryRequest(res, route, providerOptions, parsed, _log, opt
11186
11673
  if (result.toolCalls?.length) {
11187
11674
  for (const tc of result.toolCalls) {
11188
11675
  parts.push({
11189
- functionCall: { name: tc.toolName, args: normalizeFunctionCallArgs(tc.input) }
11676
+ functionCall: {
11677
+ name: tc.toolName,
11678
+ args: normalizeFunctionCallArgs(tc.input)
11679
+ }
11190
11680
  });
11191
11681
  }
11192
11682
  }
@@ -11197,10 +11687,12 @@ async function handleUnaryRequest(res, route, providerOptions, parsed, _log, opt
11197
11687
  parts.push({ text: "" });
11198
11688
  }
11199
11689
  const response = {
11200
- candidates: [{
11201
- content: { role: "model", parts },
11202
- finishReason: mapFinishReason2(result.finishReason ?? "")
11203
- }],
11690
+ candidates: [
11691
+ {
11692
+ content: { role: "model", parts },
11693
+ finishReason: mapFinishReason2(result.finishReason ?? "")
11694
+ }
11695
+ ],
11204
11696
  usageMetadata: {
11205
11697
  promptTokenCount: result.usage?.inputTokens || 0,
11206
11698
  candidatesTokenCount: result.usage?.outputTokens || 0,
@@ -11233,7 +11725,8 @@ async function resolveAntigravityLaunchRoutes(opts) {
11233
11725
  apiKey,
11234
11726
  authType: opts.provider.authType,
11235
11727
  oauthAccountId: opts.provider.oauthAccountId,
11236
- providerData: opts.provider.providerData
11728
+ providerData: opts.provider.providerData,
11729
+ headers: opts.provider.headers
11237
11730
  };
11238
11731
  const ctx = {
11239
11732
  agent: "antigravity",
@@ -11260,7 +11753,6 @@ async function resolveAntigravityLaunchRoutes(opts) {
11260
11753
  }
11261
11754
 
11262
11755
  // src/gateway/antigravity/launch-cli.ts
11263
- init_config();
11264
11756
  import { execFileSync as execFileSync2, execSync as execSync2, spawn as spawn3 } from "child_process";
11265
11757
  import { existsSync as existsSync10 } from "fs";
11266
11758
  import { homedir as homedir7 } from "os";
@@ -11435,7 +11927,6 @@ function prepareIdeProfile(profileDir, gatewayUrl, isIDE) {
11435
11927
  }
11436
11928
 
11437
11929
  // src/gateway/antigravity/launch-ide.ts
11438
- init_config();
11439
11930
  function sleep(ms) {
11440
11931
  return new Promise((resolve) => setTimeout(resolve, ms));
11441
11932
  }
@@ -11486,14 +11977,20 @@ function defaultProcessList() {
11486
11977
  }
11487
11978
  }
11488
11979
  function isAntigravityIdeRunning(profileDir, processList = defaultProcessList) {
11489
- if (process.platform === "win32") return winIsProcessRunningForProfile("Antigravity IDE.exe", profileDir);
11980
+ if (process.platform === "win32")
11981
+ return winIsProcessRunningForProfile("Antigravity IDE.exe", profileDir);
11490
11982
  const output = processList();
11491
- return output.split("\n").some((line2) => line2.includes("Antigravity IDE.app") && line2.includes(`--user-data-dir=${profileDir}`));
11983
+ return output.split("\n").some(
11984
+ (line2) => line2.includes("Antigravity IDE.app") && line2.includes(`--user-data-dir=${profileDir}`)
11985
+ );
11492
11986
  }
11493
11987
  function isAntigravityAppRunning(profileDir, processList = defaultProcessList) {
11494
- if (process.platform === "win32") return winIsProcessRunningForProfile("Antigravity.exe", profileDir);
11988
+ if (process.platform === "win32")
11989
+ return winIsProcessRunningForProfile("Antigravity.exe", profileDir);
11495
11990
  const output = processList();
11496
- return output.split("\n").some((line2) => line2.includes("Antigravity.app") && line2.includes(`--user-data-dir=${profileDir}`));
11991
+ return output.split("\n").some(
11992
+ (line2) => line2.includes("Antigravity.app") && line2.includes(`--user-data-dir=${profileDir}`)
11993
+ );
11497
11994
  }
11498
11995
  async function waitForAntigravityIdeQuit(profileDir, options = {}) {
11499
11996
  const processList = options.processList ?? defaultProcessList;
@@ -11564,7 +12061,14 @@ function findAntigravityAppBinary() {
11564
12061
  if (process.platform !== "darwin") return null;
11565
12062
  const defaultPath = "/Applications/Antigravity.app/Contents/MacOS/Antigravity";
11566
12063
  if (existsSync11(defaultPath)) return defaultPath;
11567
- const homePath = join11(homedir9(), "Applications", "Antigravity.app", "Contents", "MacOS", "Antigravity");
12064
+ const homePath = join11(
12065
+ homedir9(),
12066
+ "Applications",
12067
+ "Antigravity.app",
12068
+ "Contents",
12069
+ "MacOS",
12070
+ "Antigravity"
12071
+ );
11568
12072
  if (existsSync11(homePath)) return homePath;
11569
12073
  return null;
11570
12074
  }
@@ -11579,7 +12083,16 @@ function findAntigravityIdeBinary() {
11579
12083
  if (process.platform !== "darwin") return null;
11580
12084
  const defaultPath = "/Applications/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide";
11581
12085
  if (existsSync11(defaultPath)) return defaultPath;
11582
- const homePath = join11(homedir9(), "Applications", "Antigravity IDE.app", "Contents", "Resources", "app", "bin", "antigravity-ide");
12086
+ const homePath = join11(
12087
+ homedir9(),
12088
+ "Applications",
12089
+ "Antigravity IDE.app",
12090
+ "Contents",
12091
+ "Resources",
12092
+ "app",
12093
+ "bin",
12094
+ "antigravity-ide"
12095
+ );
11583
12096
  if (existsSync11(homePath)) return homePath;
11584
12097
  return null;
11585
12098
  }
@@ -11599,10 +12112,7 @@ function launchAntigravityApp(env, profileDir, gatewayUrl, extraArgs) {
11599
12112
  return;
11600
12113
  }
11601
12114
  prepareIdeProfile(profileDir, gatewayUrl, false);
11602
- const args = [
11603
- `--user-data-dir=${profileDir}`,
11604
- ...extraArgs
11605
- ];
12115
+ const args = [`--user-data-dir=${profileDir}`, ...extraArgs];
11606
12116
  const child = spawn4(binaryPath, args, {
11607
12117
  stdio: "inherit",
11608
12118
  env
@@ -11702,7 +12212,9 @@ function resolveAntigravityBootModel(provider, modelSelector) {
11702
12212
  };
11703
12213
  }
11704
12214
  async function pickAntigravityCliFavoriteLaunchModel(favorites, allProviders) {
11705
- const resolved = favorites.map((favorite) => resolveFavoriteModel(favorite, allProviders)).filter((entry) => entry !== null);
12215
+ const resolved = favorites.map((favorite) => resolveFavoriteModel(favorite, allProviders)).filter(
12216
+ (entry) => entry !== null
12217
+ );
11706
12218
  if (resolved.length === 0) {
11707
12219
  p14.log.warn("No Antigravity CLI favorites are available.");
11708
12220
  p14.log.info(pc12.dim("Manage them with `anygate favorites --agy`."));
@@ -11822,7 +12334,9 @@ async function resolveAndBuildRoutes(provider, model, allProviders, prefs, opts)
11822
12334
  );
11823
12335
  }
11824
12336
  if (result.capacitySkippedFavorites.length > 0) {
11825
- p14.log.warn(formatAgyCapacityWarning(opts.validatedSlotCount, result.capacitySkippedFavorites.length));
12337
+ p14.log.warn(
12338
+ formatAgyCapacityWarning(opts.validatedSlotCount, result.capacitySkippedFavorites.length)
12339
+ );
11826
12340
  p14.log.warn(
11827
12341
  "Not exposed: " + result.capacitySkippedFavorites.map((fav) => `${fav.providerId}:${fav.modelId}`).join(", ")
11828
12342
  );
@@ -11867,7 +12381,9 @@ async function runAntigravityCommand(intro, tracePrefix, trace, boot, launch, op
11867
12381
  const prefs = loadPreferences();
11868
12382
  gateIntro(intro);
11869
12383
  if (tracePrefix === "agy" && (prefs.favoriteModels?.length ?? 0) > 0 && (prefs.antigravityCliFavoriteModels?.length ?? 0) === 0 && !prefs.antigravityCliFavoritesHintShown) {
11870
- p14.log.info("Tip: AGY uses its own favorites list. Run `anygate favorites --agy` to set up switching.");
12384
+ p14.log.info(
12385
+ "Tip: AGY uses its own favorites list. Run `anygate favorites --agy` to set up switching."
12386
+ );
11871
12387
  savePreferences({ antigravityCliFavoritesHintShown: true });
11872
12388
  }
11873
12389
  const agyFavorites = prefs.antigravityCliFavoriteModels ?? [];
@@ -11953,7 +12469,12 @@ async function runAgyCommand(childArgs, trace = false, boot) {
11953
12469
  trace,
11954
12470
  boot,
11955
12471
  (env, routes) => launchAntigravityCli(env, buildAgyLaunchArgs(routes[0].displayName, childArgs)),
11956
- { childArgs, versionGuard: true, pauseForCapacityWarning: true, useFavoritesCatalog: agyArgsIncludeFavoritesFlag(childArgs) }
12472
+ {
12473
+ childArgs,
12474
+ versionGuard: true,
12475
+ pauseForCapacityWarning: true,
12476
+ useFavoritesCatalog: agyArgsIncludeFavoritesFlag(childArgs)
12477
+ }
11957
12478
  );
11958
12479
  }
11959
12480
  async function runAntigravityAppCommand(childArgs, trace = false, boot) {
@@ -11970,7 +12491,9 @@ async function runAntigravityAppCommand(childArgs, trace = false, boot) {
11970
12491
  initialValue: true
11971
12492
  });
11972
12493
  if (p14.isCancel(restart) || !restart) {
11973
- p14.log.info("Quit and reopen Antigravity when you are ready for the new gateway to take effect.");
12494
+ p14.log.info(
12495
+ "Quit and reopen Antigravity when you are ready for the new gateway to take effect."
12496
+ );
11974
12497
  return 0;
11975
12498
  }
11976
12499
  quitAntigravityAppGracefully();
@@ -12001,7 +12524,12 @@ async function runAntigravityAppCommand(childArgs, trace = false, boot) {
12001
12524
  }
12002
12525
  return 0;
12003
12526
  },
12004
- { childArgs, versionGuard: false, pauseForCapacityWarning: false, useFavoritesCatalog: agyArgsIncludeFavoritesFlag(childArgs) }
12527
+ {
12528
+ childArgs,
12529
+ versionGuard: false,
12530
+ pauseForCapacityWarning: false,
12531
+ useFavoritesCatalog: agyArgsIncludeFavoritesFlag(childArgs)
12532
+ }
12005
12533
  );
12006
12534
  }
12007
12535
  async function runAntigravityIdeCommand(childArgs, trace = false, boot) {
@@ -12018,7 +12546,9 @@ async function runAntigravityIdeCommand(childArgs, trace = false, boot) {
12018
12546
  initialValue: true
12019
12547
  });
12020
12548
  if (p14.isCancel(restart) || !restart) {
12021
- p14.log.info("Quit and reopen Antigravity IDE when you are ready for the new gateway to take effect.");
12549
+ p14.log.info(
12550
+ "Quit and reopen Antigravity IDE when you are ready for the new gateway to take effect."
12551
+ );
12022
12552
  return 0;
12023
12553
  }
12024
12554
  quitAntigravityIdeGracefully();
@@ -12049,7 +12579,12 @@ async function runAntigravityIdeCommand(childArgs, trace = false, boot) {
12049
12579
  }
12050
12580
  return 0;
12051
12581
  },
12052
- { childArgs, versionGuard: false, pauseForCapacityWarning: false, useFavoritesCatalog: agyArgsIncludeFavoritesFlag(childArgs) }
12582
+ {
12583
+ childArgs,
12584
+ versionGuard: false,
12585
+ pauseForCapacityWarning: false,
12586
+ useFavoritesCatalog: agyArgsIncludeFavoritesFlag(childArgs)
12587
+ }
12053
12588
  );
12054
12589
  }
12055
12590
 
@@ -12139,7 +12674,7 @@ Examples:
12139
12674
  `;
12140
12675
  async function handleAgyCommand(parsed) {
12141
12676
  if (parsed.showVersion) {
12142
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
12677
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
12143
12678
  console.log(VERSION2);
12144
12679
  return 0;
12145
12680
  }
@@ -12154,7 +12689,7 @@ async function handleAgyCommand(parsed) {
12154
12689
  }
12155
12690
  async function handleAntigravityAppCommand(parsed) {
12156
12691
  if (parsed.showVersion) {
12157
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
12692
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
12158
12693
  console.log(VERSION2);
12159
12694
  return 0;
12160
12695
  }
@@ -12169,7 +12704,7 @@ async function handleAntigravityAppCommand(parsed) {
12169
12704
  }
12170
12705
  async function handleAntigravityIdeCommand(parsed) {
12171
12706
  if (parsed.showVersion) {
12172
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
12707
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
12173
12708
  console.log(VERSION2);
12174
12709
  return 0;
12175
12710
  }
@@ -12274,12 +12809,11 @@ Options:
12274
12809
  `);
12275
12810
  return 0;
12276
12811
  }
12277
- const { runUiCommand } = await import("./command-7AI36ICY.js");
12812
+ const { runUiCommand } = await import("./command-PFFQI5YC.js");
12278
12813
  return runUiCommand({ trace: parsed.trace });
12279
12814
  }
12280
12815
 
12281
12816
  // src/cli/models.ts
12282
- init_config();
12283
12817
  import pc14 from "picocolors";
12284
12818
  import * as p16 from "@clack/prompts";
12285
12819
 
@@ -12287,7 +12821,7 @@ import * as p16 from "@clack/prompts";
12287
12821
  import * as p15 from "@clack/prompts";
12288
12822
  import pc13 from "picocolors";
12289
12823
 
12290
- // src/apps/claude/favorites.ts
12824
+ // src/apps/shared/favorites.ts
12291
12825
  function isFavorite(list, fav) {
12292
12826
  return list.some((f) => f.providerId === fav.providerId && f.modelId === fav.modelId);
12293
12827
  }
@@ -12371,7 +12905,11 @@ async function pickGlobalFavoriteModel(providers, favorites, opts) {
12371
12905
  message: "Add a favorite",
12372
12906
  options: [
12373
12907
  { value: "back", label: pc13.cyan("\u2190 Back to favorites"), hint: "" },
12374
- { value: ADD_BY_PROVIDER, label: pc13.cyan("Browse by provider \u2192"), hint: "Pick one provider first" }
12908
+ {
12909
+ value: ADD_BY_PROVIDER,
12910
+ label: pc13.cyan("Browse by provider \u2192"),
12911
+ hint: "Pick one provider first"
12912
+ }
12375
12913
  ]
12376
12914
  });
12377
12915
  if (p15.isCancel(fallback) || fallback === "back") return null;
@@ -12398,7 +12936,9 @@ async function pickGlobalFavoriteModel(providers, favorites, opts) {
12398
12936
  const picked = parseGlobalFavoritePickKey(result.id, matched);
12399
12937
  if (!picked) continue;
12400
12938
  if (isFavorite(favorites, { providerId: picked.providerId, modelId: picked.model.id })) {
12401
- p15.log.warn(`${picked.model.name || picked.model.id} (${picked.providerName}) is already in your favorites.`);
12939
+ p15.log.warn(
12940
+ `${picked.model.name || picked.model.id} (${picked.providerName}) is already in your favorites.`
12941
+ );
12402
12942
  continue;
12403
12943
  }
12404
12944
  return picked;
@@ -12427,7 +12967,9 @@ async function runModelsCommand(parsed) {
12427
12967
  }));
12428
12968
  if (favoriteProviders.length === 0) {
12429
12969
  p16.log.warn("No providers found.");
12430
- p16.log.info(`OpenCode Zen/Go is always available. Add providers with ${pc14.cyan("anygate providers")}.`);
12970
+ p16.log.info(
12971
+ `OpenCode Zen/Go is always available. Add providers with ${pc14.cyan("anygate providers")}.`
12972
+ );
12431
12973
  gateOutro("Done");
12432
12974
  return 0;
12433
12975
  }
@@ -12500,7 +13042,9 @@ async function runModelsCommand(parsed) {
12500
13042
  }
12501
13043
  }
12502
13044
  if (addPath === "free") {
12503
- const globalPick = await pickGlobalFavoriteModel(favoriteProviders, favorites, { freeOnly: true });
13045
+ const globalPick = await pickGlobalFavoriteModel(favoriteProviders, favorites, {
13046
+ freeOnly: true
13047
+ });
12504
13048
  if (globalPick === null) continue;
12505
13049
  if (globalPick !== ADD_BY_PROVIDER) {
12506
13050
  provider = favoriteProviders.find((ap) => ap.id === globalPick.providerId);
@@ -12694,7 +13238,7 @@ async function runValidateSubcommand(parsed) {
12694
13238
  // src/cli/providers.ts
12695
13239
  async function handleProvidersCommand(parsed) {
12696
13240
  if (parsed.showVersion) {
12697
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
13241
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
12698
13242
  console.log(VERSION2);
12699
13243
  return 0;
12700
13244
  }
@@ -12807,7 +13351,7 @@ async function runDoctorCommand(_dryRun) {
12807
13351
  // src/cli/doctor.ts
12808
13352
  async function handleDoctorCommand(parsed) {
12809
13353
  if (parsed.showVersion) {
12810
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
13354
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
12811
13355
  console.log(VERSION2);
12812
13356
  return 0;
12813
13357
  }
@@ -12862,7 +13406,8 @@ function detectShell() {
12862
13406
  if (shell.includes("zsh")) return "zsh";
12863
13407
  if (shell.includes("bash")) return "bash";
12864
13408
  if (shell.includes("fish")) return "fish";
12865
- if (process.env["PSModulePath"] || process.env["POWERSHELL_DISTRIBUTION_CHANNEL"]) return "powershell";
13409
+ if (process.env["PSModulePath"] || process.env["POWERSHELL_DISTRIBUTION_CHANNEL"])
13410
+ return "powershell";
12866
13411
  return void 0;
12867
13412
  }
12868
13413
  function normalizeShell(input) {
@@ -12905,7 +13450,9 @@ _anygate "$@"
12905
13450
  `;
12906
13451
  }
12907
13452
  function fishScript() {
12908
- const lines = SUBCOMMANDS.map((c) => `complete -c anygate -n "not __fish_seen_subcommand_from ${SUBCOMMANDS.join(" ")}" -a ${c} -d 'anygate ${c}'`);
13453
+ const lines = SUBCOMMANDS.map(
13454
+ (c) => `complete -c anygate -n "not __fish_seen_subcommand_from ${SUBCOMMANDS.join(" ")}" -a ${c} -d 'anygate ${c}'`
13455
+ );
12909
13456
  lines.push(`complete -c anygate -s h -l help -d 'Show help'`);
12910
13457
  lines.push(`complete -c anygate -s v -l version -d 'Show version'`);
12911
13458
  return `# anygate fish completion
@@ -12944,7 +13491,7 @@ function runCompletionsCommand(shellArg) {
12944
13491
  // src/cli/completions.ts
12945
13492
  async function handleCompletionsCommand(parsed) {
12946
13493
  if (parsed.showVersion) {
12947
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
13494
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
12948
13495
  console.log(VERSION2);
12949
13496
  return 0;
12950
13497
  }
@@ -13019,7 +13566,9 @@ async function runUpdateCommand(dryRun) {
13019
13566
  });
13020
13567
  child.on("close", (code) => {
13021
13568
  if (code === 0) {
13022
- p17.log.success("anygate updated. Restart your shell or re-run anygate to use the new version.");
13569
+ p17.log.success(
13570
+ "anygate updated. Restart your shell or re-run anygate to use the new version."
13571
+ );
13023
13572
  } else {
13024
13573
  p17.log.error(`Update failed (exit ${code}). Try ${pc17.cyan(UPDATE_COMMAND)} manually.`);
13025
13574
  }
@@ -13031,7 +13580,7 @@ async function runUpdateCommand(dryRun) {
13031
13580
  // src/cli/update.ts
13032
13581
  async function handleUpdateCommand(parsed) {
13033
13582
  if (parsed.showVersion) {
13034
- const { VERSION: VERSION2 } = await import("./constants-HE3EOSMH.js");
13583
+ const { VERSION: VERSION2 } = await import("./constants-GW5BAY6G.js");
13035
13584
  console.log(VERSION2);
13036
13585
  return 0;
13037
13586
  }
@@ -13086,7 +13635,15 @@ registerCommand("completions", handleCompletionsCommand);
13086
13635
  registerCommand("update", handleUpdateCommand);
13087
13636
 
13088
13637
  // src/cli.ts
13089
- var STARTER_CLAUDE_FLAGS = /* @__PURE__ */ new Set(["--dry-run", "--setup", "--trace", "--help", "-h", "--version", "-v"]);
13638
+ var STARTER_CLAUDE_FLAGS = /* @__PURE__ */ new Set([
13639
+ "--dry-run",
13640
+ "--setup",
13641
+ "--trace",
13642
+ "--help",
13643
+ "-h",
13644
+ "--version",
13645
+ "-v"
13646
+ ]);
13090
13647
  var GATEWAY_LAUNCH_FLAGS = /* @__PURE__ */ new Set(["--provider", "--model"]);
13091
13648
  function parseGatewayLaunchFlag(arg, rest, index, parsed) {
13092
13649
  if (arg === "--provider" || arg === "--model") {