@lunaroute/cli 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +517 -27
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { Command, InvalidArgumentError, Option } from "commander";
5
5
 
6
6
  // package.json
7
- var version = "0.9.0";
7
+ var version = "0.11.0";
8
8
 
9
9
  // src/login.ts
10
10
  import { createServer } from "http";
@@ -656,8 +656,10 @@ ${nextStr}`);
656
656
  }
657
657
  if (curStr !== null) {
658
658
  if (curStr === nextStr) continue;
659
- copyFileSync(fw.path, `${fw.path}.bak`);
660
- summary.backedUp.push(`${fw.path}.bak`);
659
+ if (fw.backup !== false) {
660
+ copyFileSync(fw.path, `${fw.path}.bak`);
661
+ summary.backedUp.push(`${fw.path}.bak`);
662
+ }
661
663
  }
662
664
  const dir = dirname(fw.path);
663
665
  const dirExisted = existsSync3(dir);
@@ -805,8 +807,9 @@ function describeSpawnError(command, installHint, err) {
805
807
 
806
808
  // src/setup/paths.ts
807
809
  import { execSync } from "child_process";
810
+ import { lstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
808
811
  import { homedir as homedir2 } from "os";
809
- import { join as join3 } from "path";
812
+ import { dirname as dirname2, join as join3 } from "path";
810
813
  function configHome() {
811
814
  return process.env.XDG_CONFIG_HOME || join3(homedir2(), ".config");
812
815
  }
@@ -864,6 +867,47 @@ function gitRepoRoot(cwd = process.cwd()) {
864
867
  return null;
865
868
  }
866
869
  }
870
+ function claudeDesktop3pDir() {
871
+ return join3(configHome(), "Claude-3p");
872
+ }
873
+ function claudeDesktopConfigLibraryDir() {
874
+ return join3(claudeDesktop3pDir(), "configLibrary");
875
+ }
876
+ function claudeDesktopPointerPath() {
877
+ return join3(claudeDesktopConfigLibraryDir(), "_meta.json");
878
+ }
879
+ function isRealDir(p) {
880
+ try {
881
+ const st = lstatSync(p);
882
+ return st.isDirectory() && !st.isSymbolicLink();
883
+ } catch {
884
+ return false;
885
+ }
886
+ }
887
+ function isRegularFile(p) {
888
+ try {
889
+ const st = lstatSync(p);
890
+ return st.isFile() && !st.isSymbolicLink();
891
+ } catch {
892
+ return false;
893
+ }
894
+ }
895
+ function resolveClaudeDesktopAppliedProfile(platform = process.platform) {
896
+ if (platform !== "linux") return null;
897
+ if (!isRealDir(claudeDesktop3pDir()) || !isRealDir(claudeDesktopConfigLibraryDir())) return null;
898
+ if (!isRegularFile(claudeDesktopPointerPath())) return null;
899
+ let appliedId;
900
+ try {
901
+ const raw = readFileSync4(claudeDesktopPointerPath(), "utf8");
902
+ appliedId = JSON.parse(raw)?.appliedId;
903
+ } catch {
904
+ return null;
905
+ }
906
+ if (typeof appliedId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(appliedId)) return null;
907
+ const candidate = join3(claudeDesktopConfigLibraryDir(), `${appliedId}.json`);
908
+ if (!isRegularFile(candidate)) return null;
909
+ return dirname2(realpathSync(candidate)) === realpathSync(claudeDesktopConfigLibraryDir()) ? candidate : null;
910
+ }
867
911
 
868
912
  // src/setup/adapters/opencode.ts
869
913
  var EXTENSION = "@lunaroute/opencode-extension";
@@ -968,7 +1012,7 @@ function buildKeyPlan(key2) {
968
1012
  }
969
1013
 
970
1014
  // src/setup/adapters/pi.ts
971
- import { readFileSync as readFileSync4 } from "fs";
1015
+ import { readFileSync as readFileSync5 } from "fs";
972
1016
  function buildPiModelEntry(m) {
973
1017
  if (!m.context_window_tokens || !m.max_output_tokens) return null;
974
1018
  const reasoning = m.capabilities?.reasoning === true;
@@ -1042,7 +1086,7 @@ function buildPlan2(ctx) {
1042
1086
  }
1043
1087
  function stalePiProviderExists() {
1044
1088
  try {
1045
- const obj = JSON.parse(readFileSync4(piModelsPath(), "utf8"));
1089
+ const obj = JSON.parse(readFileSync5(piModelsPath(), "utf8"));
1046
1090
  return Boolean(obj.providers?.lunaroute);
1047
1091
  } catch {
1048
1092
  return false;
@@ -1132,7 +1176,22 @@ function buildPlan3(ctx) {
1132
1176
  // auxiliary) only when asked to, and LunaRoute reads it to give
1133
1177
  // auto-mode classifier and other auxiliary requests a fast path
1134
1178
  // instead of queueing them behind the session's own requests.
1135
- { name: "CLAUDE_CODE_GATEWAY_HINT_HEADERS", value: "1" }
1179
+ { name: "CLAUDE_CODE_GATEWAY_HINT_HEADERS", value: "1" },
1180
+ // Claude Code keeps only discovered ids containing "claude"/"anthropic"
1181
+ // (kata 4sak). The normal catalog has no such id, so discovery would
1182
+ // otherwise yield an empty picker. X-LunaRoute-Client: claude-desktop
1183
+ // selects the gateway's Claude-shaped alias variant (kata d8qg); aliases
1184
+ // translate back to canonical models at ingress, and the header is
1185
+ // informational only (never auth/entitlements/billing). Claude Code sends
1186
+ // ANTHROPIC_CUSTOM_HEADERS on the discovery GET too (vendor gateway guide).
1187
+ { name: "ANTHROPIC_CUSTOM_HEADERS", value: "X-LunaRoute-Client: claude-desktop" },
1188
+ // Populates the /model picker from GET /v1/models. Gateway discovery is
1189
+ // opt-in since Claude Code v2.1.129: without this export the picker lists
1190
+ // only ANTHROPIC_MODEL and the aliases silently never appear (kata d7fm).
1191
+ // Mirrors the run adapter and the Connect tab. The hint header above is a
1192
+ // separate setting: that one fast-paths auxiliary requests, this one
1193
+ // fills the picker.
1194
+ { name: "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", value: "1" }
1136
1195
  ],
1137
1196
  notes: [
1138
1197
  ...isWin ? [
@@ -1142,12 +1201,13 @@ function buildPlan3(ctx) {
1142
1201
  // Blocker corrected in kata z2sw: Desktop routing does NOT come from these
1143
1202
  // variables. Saying so here is the whole point — the previous wording
1144
1203
  // implied env vars were the Desktop lever, which the vendor doc contradicts.
1145
- "Claude Desktop does not route through these variables: its gateway routing comes from its own third-party inference configuration. Open Help \u2192 Troubleshooting \u2192 Enable Developer Mode, then Developer \u2192 Configure Third-Party Inference and enter your routing URL. An administrator-distributed configuration takes precedence and makes that form read-only, and a host-managed deployment (CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST) overrides endpoint and auth routing from settings files by design. With a gateway configured, Desktop runs local sessions only \u2014 no SSH or cloud environments, and no Remote Control.",
1204
+ "Claude Desktop does not route through these variables: it is its own harness here \u2014 run `lunaroute setup claude-desktop` for it (or see the Claude Desktop tab at /connect). Its gateway routing comes from its own third-party inference configuration. Open Help \u2192 Troubleshooting \u2192 Enable Developer Mode, then Developer \u2192 Configure Third-Party Inference and enter your routing URL. An administrator-distributed configuration takes precedence and makes that form read-only, and a host-managed deployment (CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST) overrides endpoint and auth routing from settings files by design. With a gateway configured, Desktop runs local sessions only \u2014 no SSH or cloud environments, and no Remote Control.",
1146
1205
  ...isWin ? [
1147
1206
  "To restart Claude Desktop, quit it fully; if it will not quit, end the Claude process in Task Manager (Ctrl+Shift+Esc).",
1148
1207
  "WSL is a separate environment: Windows user variables do not cross into it (WSLENV is the bridge) and the npm global install is separate. Run `lunaroute setup claude-code` again inside the distribution."
1149
1208
  ] : [],
1150
1209
  `Change ANTHROPIC_MODEL to any of: ${ctx.models.map((m) => m.id).join(", ")}`,
1210
+ "ANTHROPIC_CUSTOM_HEADERS carries X-LunaRoute-Client: claude-desktop so the /model picker's gateway discovery returns Claude-shaped alias ids instead of an empty list: Claude Code drops any discovered id without 'claude'/'anthropic' in it, and LunaRoute's normal catalog has none. The aliases route back to the real model at the gateway \u2014 pick one in /model like any other, or set ANTHROPIC_MODEL to a plain model id to skip the aliases.",
1151
1211
  "ANTHROPIC_DEFAULT_HAIKU_MODEL pins Claude Code's background model (titles, summaries, compaction, the auxiliary classifier) \u2014 it defaults to your main model, and you can point it at a smaller/faster model from the list above.",
1152
1212
  "(Auth travels in the Authorization: Bearer header via ANTHROPIC_AUTH_TOKEN.)",
1153
1213
  "CLAUDE_CODE_GATEWAY_HINT_HEADERS=1 makes Claude Code label its auxiliary requests (the auto-mode safety classifier) so LunaRoute can route them to a fast path; without it they are still detected via their wire marker, just less directly.",
@@ -1188,8 +1248,82 @@ function validatedRoutingUrl(routingUrl) {
1188
1248
  return routingUrl;
1189
1249
  }
1190
1250
 
1191
- // src/setup/adapters/codex.ts
1251
+ // src/setup/adapters/claudeDesktop.ts
1192
1252
  function buildPlan4(ctx) {
1253
+ const dialect = ctx.dialect ?? resolveDialect();
1254
+ const isWin = dialect === "win32";
1255
+ const routingUrl = validatedRoutingUrl(ctx.routingUrl);
1256
+ const profile = {
1257
+ inferenceProvider: "gateway",
1258
+ inferenceGatewayBaseUrl: routingUrl,
1259
+ // A placeholder, never a live secret: a printed plan must not carry the
1260
+ // key (kata a6qg), and this adapter has no key in its context anyway — the
1261
+ // CLI passes one only to plans that WRITE a credential, which this one
1262
+ // deliberately does not.
1263
+ inferenceGatewayApiKey: "<your-lunaroute-key>",
1264
+ inferenceGatewayAuthScheme: "bearer",
1265
+ modelDiscoveryEnabled: true,
1266
+ inferenceCustomHeaders: { "X-LunaRoute-Client": "claude-desktop" }
1267
+ };
1268
+ const probe = isWin ? `Invoke-RestMethod -Method Get -Uri ${quoteArg(`${routingUrl}/v1/models`, "win32")} -Headers @{ Authorization = "Bearer <your-lunaroute-key>"; "X-LunaRoute-Client" = "claude-desktop" }` : `curl ${quoteArg(`${routingUrl}/v1/models`, "posix")} -H "Authorization: Bearer <your-lunaroute-key>" -H "X-LunaRoute-Client: claude-desktop"`;
1269
+ return {
1270
+ fileWrites: [],
1271
+ exports: [],
1272
+ notes: [
1273
+ "\nThe CLI writes this for you: `lunaroute setup claude-desktop` merges these keys into the profile Desktop created (verified on Linux). Undo it with `lunaroute setup claude-desktop --remove` \u2014 that restores your pre-LunaRoute profile from a snapshot taken before the first write, kept at ~/.config/lunaroute/backups/claude-desktop/ (0600, and it holds your key). If no snapshot exists it prints the keys to remove by hand and changes nothing.",
1274
+ "Claude Desktop does not route through environment variables \u2014 not the ones above, and not ~/.claude/settings.json. It reads its own third-party-inference configuration.",
1275
+ isWin ? "Create that configuration from the app: Help \u2192 Troubleshooting \u2192 Enable Developer Mode, then Developer \u2192 Configure Third-Party Inference. Then merge the keys below into the profile file the app wrote, and restart Desktop (end the Claude process in Task Manager if it will not quit)." : "Create that configuration from the app: Help \u2192 Troubleshooting \u2192 Enable Developer Mode, then Developer \u2192 Configure Third-Party Inference. Then merge the keys below into the profile file the app wrote, and quit and reopen Desktop.",
1276
+ "Manual fallback: merge into the profile file the app itself created \u2014 do not hand-create one. Its name is app-generated, so find it where the app wrote it:",
1277
+ " ~/.config/Claude-3p/configLibrary/<your-profile>.json (verified on Linux; macOS and Windows use the same shape but their paths are unverified)",
1278
+ JSON.stringify(profile, null, 2),
1279
+ "Do NOT add an `inferenceModels` list. A pinned list turns model discovery off, and the picker will then show none of LunaRoute's models.",
1280
+ "Replace <your-lunaroute-key> with your key: `lunaroute key` prints it if you signed in with the CLI, or paste the LUNAROUTE_API_KEY you provisioned directly. Desktop stores it literally in that file and expands no environment variables, so paste it in full and keep the file private.",
1281
+ "The picker fills from discovery with LunaRoute's Claude-family aliases: the id is a wire alias (for example claude-opus-lr29) and the catalog carries a human-readable display_name label (for example GLM 5.3), falling back to the canonical LunaRoute model id when none is configured. Whether Desktop renders that label is unverified; the id is what it requires.",
1282
+ "With a gateway configured, Desktop runs local sessions only: no SSH or cloud environments, and no Remote Control.",
1283
+ "Confirm the key and preview the picker's catalog without opening the app:",
1284
+ ` ${probe}`
1285
+ ]
1286
+ };
1287
+ }
1288
+ function claudeDesktopKeys(routingUrl, key2) {
1289
+ return {
1290
+ inferenceProvider: "gateway",
1291
+ inferenceGatewayBaseUrl: routingUrl,
1292
+ inferenceGatewayApiKey: key2,
1293
+ inferenceGatewayAuthScheme: "bearer",
1294
+ modelDiscoveryEnabled: true,
1295
+ inferenceCustomHeaders: { "X-LunaRoute-Client": "claude-desktop" }
1296
+ };
1297
+ }
1298
+ function buildKeyPlan3(routingUrl, key2, appliedPath) {
1299
+ const ours = claudeDesktopKeys(routingUrl, key2);
1300
+ const ourHeaders = ours.inferenceCustomHeaders;
1301
+ return {
1302
+ fileWrites: [
1303
+ {
1304
+ kind: "json",
1305
+ path: appliedPath,
1306
+ backup: false,
1307
+ merge: (existing) => {
1308
+ if (existing === null) return ours;
1309
+ if (typeof existing !== "object" || Array.isArray(existing)) {
1310
+ throw new Error(
1311
+ `refusing to modify ${appliedPath}: it is valid JSON but not a JSON object.`
1312
+ );
1313
+ }
1314
+ const obj = existing;
1315
+ const existingHeaders = typeof obj.inferenceCustomHeaders === "object" && obj.inferenceCustomHeaders !== null && !Array.isArray(obj.inferenceCustomHeaders) ? obj.inferenceCustomHeaders : {};
1316
+ return { ...obj, ...ours, inferenceCustomHeaders: { ...existingHeaders, ...ourHeaders } };
1317
+ }
1318
+ }
1319
+ ],
1320
+ exports: [],
1321
+ notes: []
1322
+ };
1323
+ }
1324
+
1325
+ // src/setup/adapters/codex.ts
1326
+ function buildPlan5(ctx) {
1193
1327
  const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1194
1328
  const base = validatedRoutingUrl(ctx.routingUrl);
1195
1329
  const model = requireFirstModel(ctx, "codex");
@@ -1203,11 +1337,20 @@ function buildPlan4(ctx) {
1203
1337
  "[model_providers.lunaroute]",
1204
1338
  'name = "LunaRoute"',
1205
1339
  `base_url = "${base}/v1"`,
1340
+ // Codex's model discovery decodes {models:[ModelInfo]} and cannot read
1341
+ // the OpenAI-shaped /v1/models, so it fetches its own Codex-shaped path
1342
+ // (kata 3jrx). This is what populates the /model picker.
1343
+ `model_catalog_url = "${base}/v1/codex/models"`,
1206
1344
  'env_key = "LUNAROUTE_API_KEY"',
1207
1345
  'wire_api = "responses"',
1208
1346
  // Codex only calls /v1/alpha/search when the provider opts in; the
1209
1347
  // endpoint is derived from base_url by the /responses suffix swap.
1210
- "supports_standalone_web_search = true"
1348
+ "supports_standalone_web_search = true",
1349
+ "",
1350
+ // No-op on current Codex (Stable, default-on); enables discovery on
1351
+ // builds where the flag was still under development.
1352
+ "[features]",
1353
+ "api_key_model_discovery = true"
1211
1354
  ]).join("\n") + "\n";
1212
1355
  return {
1213
1356
  fileWrites: [{ kind: "text", path: codexProfilePath(), content }],
@@ -1217,13 +1360,13 @@ function buildPlan4(ctx) {
1217
1360
  `Change model to any of: ${ctx.models.map((m) => m.id).join(", ")}, or pass \`--model <id>\` for one session. If you change model, update or remove model_context_window to match.`,
1218
1361
  "The key rides the Authorization: Bearer header via env_key; LunaRoute authenticates the lr_ key at the edge and never forwards it upstream.",
1219
1362
  "One file: the model and the named provider live in the profile file \u2014 your ~/.codex/config.toml is untouched.",
1220
- "Codex logs a `Model metadata ... fallback metadata` warning for LunaRoute models (its /v1/models catalog shape differs); it is expected and harmless \u2014 model_context_window pins the real window above."
1363
+ "Codex discovers the LunaRoute catalog via the profile's `model_catalog_url`, so its `/model` picker lists all LunaRoute chat models and the `fallback metadata` warning is gone."
1221
1364
  ]
1222
1365
  };
1223
1366
  }
1224
1367
 
1225
1368
  // src/setup/adapters/copilotCli.ts
1226
- function buildPlan5(ctx) {
1369
+ function buildPlan6(ctx) {
1227
1370
  const firstModel = requireFirstModel(ctx, "copilot-cli");
1228
1371
  const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1229
1372
  return {
@@ -1259,7 +1402,7 @@ function buildPlan5(ctx) {
1259
1402
  }
1260
1403
 
1261
1404
  // src/setup/adapters/generic.ts
1262
- function buildPlan6(ctx) {
1405
+ function buildPlan7(ctx) {
1263
1406
  return {
1264
1407
  fileWrites: [],
1265
1408
  exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
@@ -1282,7 +1425,7 @@ function primaryModel(ctx) {
1282
1425
  function asRecord(v) {
1283
1426
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
1284
1427
  }
1285
- function buildPlan7(ctx) {
1428
+ function buildPlan8(ctx) {
1286
1429
  const base = validatedRoutingUrl(ctx.routingUrl);
1287
1430
  const models = ctx.models.map((m) => ({ id: m.id, name: m.id }));
1288
1431
  const primary = primaryModel(ctx);
@@ -1340,7 +1483,7 @@ openclaw: restart the gateway, then \`openclaw models list\` and \`openclaw mode
1340
1483
  }
1341
1484
 
1342
1485
  // src/setup/adapters/dsh.ts
1343
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1486
+ import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
1344
1487
  import { isMap, isSeq, parseDocument as parseDocument2 } from "yaml";
1345
1488
  var PI_AI_ROW_ID = "llm-pi-ai";
1346
1489
  var ROUTE_KEY = "lunaroute";
@@ -1434,7 +1577,7 @@ function homePatchOverridesPiAi() {
1434
1577
  const path = dshHomePatchPath();
1435
1578
  if (!existsSync4(path)) return false;
1436
1579
  try {
1437
- const doc = parseDocument2(readFileSync5(path, "utf8"), { logLevel: "silent" });
1580
+ const doc = parseDocument2(readFileSync6(path, "utf8"), { logLevel: "silent" });
1438
1581
  if (!isSeq(doc.contents)) return false;
1439
1582
  return doc.contents.items.some(
1440
1583
  (item) => isMap(item) && item.get("id") === PI_AI_ROW_ID
@@ -1443,7 +1586,7 @@ function homePatchOverridesPiAi() {
1443
1586
  return false;
1444
1587
  }
1445
1588
  }
1446
- function buildPlan8(ctx) {
1589
+ function buildPlan9(ctx) {
1447
1590
  const base = validatedRoutingUrl(ctx.routingUrl);
1448
1591
  if (ctx.models.length === 0) {
1449
1592
  throw new Error("no LunaRoute chat models in the catalog \u2014 nothing to configure for dsh");
@@ -1489,16 +1632,205 @@ function buildPlan8(ctx) {
1489
1632
  };
1490
1633
  }
1491
1634
 
1635
+ // src/setup/snapshot.ts
1636
+ import {
1637
+ chmodSync as chmodSync4,
1638
+ closeSync,
1639
+ constants,
1640
+ fstatSync,
1641
+ linkSync,
1642
+ lstatSync as lstatSync2,
1643
+ mkdirSync as mkdirSync4,
1644
+ openSync,
1645
+ readFileSync as readFileSync7,
1646
+ renameSync as renameSync2,
1647
+ rmSync as rmSync2,
1648
+ statSync,
1649
+ writeFileSync as writeFileSync4
1650
+ } from "fs";
1651
+ import { randomBytes as randomBytes2 } from "crypto";
1652
+ import { basename, dirname as dirname3, join as join4 } from "path";
1653
+ function claudeDesktopSnapshotDir() {
1654
+ return join4(configDir(), "backups", "claude-desktop");
1655
+ }
1656
+ function claudeDesktopSnapshotPath(profilePath) {
1657
+ return join4(claudeDesktopSnapshotDir(), basename(profilePath));
1658
+ }
1659
+ function notRegular(path) {
1660
+ return new Error(`${path} is not a regular file \u2014 refusing to read it.`);
1661
+ }
1662
+ function readRegularFileNoFollow(path) {
1663
+ let fd;
1664
+ try {
1665
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1666
+ } catch {
1667
+ throw notRegular(path);
1668
+ }
1669
+ try {
1670
+ if (!fstatSync(fd).isFile()) throw notRegular(path);
1671
+ return readFileSync7(fd);
1672
+ } finally {
1673
+ closeSync(fd);
1674
+ }
1675
+ }
1676
+ function writeFileAtomic(path, data, mode = 384) {
1677
+ const tmp = stageTemp(path, data, mode);
1678
+ renameSync2(tmp, path);
1679
+ }
1680
+ function stageTemp(path, data, mode = 384) {
1681
+ const tmp = join4(dirname3(path), `.${basename(path)}.${randomBytes2(6).toString("hex")}.tmp`);
1682
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
1683
+ try {
1684
+ writeFileSync4(fd, data);
1685
+ } finally {
1686
+ closeSync(fd);
1687
+ }
1688
+ return tmp;
1689
+ }
1690
+ function writeFileNoClobber(path, data, mode = 384) {
1691
+ const tmp = stageTemp(path, data, mode);
1692
+ try {
1693
+ linkSync(tmp, path);
1694
+ return true;
1695
+ } catch (err) {
1696
+ if (err.code === "EEXIST") return false;
1697
+ throw err;
1698
+ } finally {
1699
+ rmSync2(tmp, { force: true });
1700
+ }
1701
+ }
1702
+ function validateSnapshotDir() {
1703
+ const dir = claudeDesktopSnapshotDir();
1704
+ let st;
1705
+ try {
1706
+ st = lstatSync2(dir);
1707
+ } catch {
1708
+ return;
1709
+ }
1710
+ const ownedByUs = typeof process.getuid === "function" && st.uid === process.getuid();
1711
+ if (!st.isDirectory() || st.isSymbolicLink() || !ownedByUs) {
1712
+ throw new Error(
1713
+ `refusing to use ${dir} as the snapshot directory: it is not a directory owned by this user.`
1714
+ );
1715
+ }
1716
+ }
1717
+ function ensureSnapshotDir() {
1718
+ const dir = claudeDesktopSnapshotDir();
1719
+ mkdirSync4(dirname3(dir), { recursive: true, mode: 448 });
1720
+ let st;
1721
+ try {
1722
+ st = lstatSync2(dir);
1723
+ } catch {
1724
+ mkdirSync4(dir, { recursive: true, mode: 448 });
1725
+ st = lstatSync2(dir);
1726
+ }
1727
+ const ownedByUs = typeof process.getuid === "function" && st.uid === process.getuid();
1728
+ if (!st.isDirectory() || st.isSymbolicLink() || !ownedByUs) {
1729
+ throw new Error(
1730
+ `refusing to use ${dir} as the snapshot directory: it is not a directory owned by this user.`
1731
+ );
1732
+ }
1733
+ if ((st.mode & 511) !== 448) chmodSync4(dir, 448);
1734
+ return dir;
1735
+ }
1736
+ function alreadyConfigured(existing, keys) {
1737
+ if (typeof existing !== "object" || existing === null || Array.isArray(existing)) return false;
1738
+ const obj = existing;
1739
+ for (const [k, v] of Object.entries(keys)) {
1740
+ if (k === "inferenceCustomHeaders") {
1741
+ const ours = v["X-LunaRoute-Client"];
1742
+ const theirs = obj.inferenceCustomHeaders?.["X-LunaRoute-Client"];
1743
+ if (theirs !== ours) return false;
1744
+ continue;
1745
+ }
1746
+ if (obj[k] !== v) return false;
1747
+ }
1748
+ return true;
1749
+ }
1750
+ function snapshotClaudeDesktopProfile(profilePath, keys) {
1751
+ ensureSnapshotDir();
1752
+ const path = claudeDesktopSnapshotPath(profilePath);
1753
+ const existing = inspectSnapshotPath(path);
1754
+ if (existing.kind === "invalid") {
1755
+ throw new Error(`refusing to reuse a snapshot at ${path}: ${existing.why}.`);
1756
+ }
1757
+ if (existing.kind === "regular") {
1758
+ readRegularFileNoFollow(path);
1759
+ return { taken: false, path, reason: "exists" };
1760
+ }
1761
+ const bytes = readRegularFileNoFollow(profilePath);
1762
+ let parsed;
1763
+ try {
1764
+ parsed = JSON.parse(bytes.toString("utf8"));
1765
+ } catch {
1766
+ throw new Error(`refusing to snapshot ${profilePath}: it is not valid JSON.`);
1767
+ }
1768
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1769
+ throw new Error(`refusing to snapshot ${profilePath}: it is not a JSON object.`);
1770
+ }
1771
+ if (alreadyConfigured(parsed, keys)) return { taken: false, path, reason: "already-configured" };
1772
+ if (!writeFileNoClobber(path, bytes)) {
1773
+ const winner = inspectSnapshotPath(path);
1774
+ if (winner.kind === "invalid") {
1775
+ throw new Error(`refusing to reuse a snapshot at ${path}: ${winner.why}.`);
1776
+ }
1777
+ if (winner.kind === "none") {
1778
+ throw new Error(
1779
+ `refusing to continue: an entry appeared at ${path} during publication and is now gone \u2014 re-run setup.`
1780
+ );
1781
+ }
1782
+ readRegularFileNoFollow(path);
1783
+ return { taken: false, path, reason: "exists" };
1784
+ }
1785
+ return { taken: true, path };
1786
+ }
1787
+ function inspectSnapshotPath(path) {
1788
+ let st;
1789
+ try {
1790
+ st = lstatSync2(path);
1791
+ } catch (err) {
1792
+ const code = err.code;
1793
+ if (code === "ENOENT") return { kind: "none" };
1794
+ return { kind: "invalid", why: `cannot read ${path} (${code ?? "unknown error"})` };
1795
+ }
1796
+ if (st.isFile() && !st.isSymbolicLink()) return { kind: "regular", stats: st };
1797
+ return { kind: "invalid", why: `${path} is not a regular file (a symlink, directory or FIFO)` };
1798
+ }
1799
+ function claudeDesktopSnapshotStatus(profilePath) {
1800
+ return inspectSnapshotPath(claudeDesktopSnapshotPath(profilePath)).kind;
1801
+ }
1802
+ function claudeDesktopSnapshotTakenAt(profilePath) {
1803
+ try {
1804
+ const st = statSync(claudeDesktopSnapshotPath(profilePath));
1805
+ return st.mtime.toISOString().slice(0, 16).replace("T", " ");
1806
+ } catch {
1807
+ return null;
1808
+ }
1809
+ }
1810
+ function restoreClaudeDesktopProfile(profilePath) {
1811
+ validateSnapshotDir();
1812
+ const path = claudeDesktopSnapshotPath(profilePath);
1813
+ const entry = inspectSnapshotPath(path);
1814
+ if (entry.kind === "none") return { restored: false, reason: "no-snapshot" };
1815
+ if (entry.kind === "invalid") throw new Error(`refusing to restore from ${path}: ${entry.why}.`);
1816
+ const snapshot = readRegularFileNoFollow(path);
1817
+ const current = readRegularFileNoFollow(profilePath);
1818
+ if (snapshot.equals(current)) return { restored: false };
1819
+ writeFileAtomic(profilePath, snapshot);
1820
+ return { restored: true };
1821
+ }
1822
+
1492
1823
  // src/commands/setup.ts
1493
1824
  var ADAPTERS = {
1494
1825
  opencode: buildPlan,
1495
1826
  pi: buildPlan2,
1496
- openclaw: buildPlan7,
1497
- dsh: buildPlan8,
1827
+ openclaw: buildPlan8,
1828
+ dsh: buildPlan9,
1498
1829
  "claude-code": buildPlan3,
1499
- codex: buildPlan4,
1500
- "copilot-cli": buildPlan5,
1501
- generic: buildPlan6
1830
+ "claude-desktop": buildPlan4,
1831
+ codex: buildPlan5,
1832
+ "copilot-cli": buildPlan6,
1833
+ generic: buildPlan7
1502
1834
  };
1503
1835
  var PI_INSTALL_PACKAGES = ["npm:@lunaroute/pi-extension"];
1504
1836
  var PI_INSTALL_HINT = "Install pi first: npm install -g --ignore-scripts @earendil-works/pi-coding-agent (https://pi.dev)";
@@ -1522,6 +1854,7 @@ async function runSetup(harness, opts, deps = {
1522
1854
  );
1523
1855
  return 1;
1524
1856
  }
1857
+ if (opts.remove) return runRemove(harness, opts, deps);
1525
1858
  let stored = loadProfile(opts.profile);
1526
1859
  const settings = resolveSettings(opts.profile);
1527
1860
  if (opts.key && !LR_KEY_RE.test(opts.key)) {
@@ -1573,6 +1906,7 @@ async function runSetup(harness, opts, deps = {
1573
1906
  }
1574
1907
  const creds = await requireCreds(opts, deps, stored);
1575
1908
  if (!creds) return 1;
1909
+ if (harness === "claude-desktop") return runClaudeDesktopSetup(creds, routingUrl, opts, deps);
1576
1910
  if (harness === "hermes") {
1577
1911
  return runHermesSetup(creds, routingUrl, opts, deps);
1578
1912
  }
@@ -1731,6 +2065,144 @@ async function runPiSetup(opts, stored, routingUrl, deps) {
1731
2065
  return 1;
1732
2066
  }
1733
2067
  }
2068
+ var CLAUDE_DESKTOP_NO_PROFILE = "Claude Desktop has not created a third-party inference profile yet \u2014 in Desktop open Help \u2192 Troubleshooting \u2192 Enable Developer Mode, then Developer \u2192 Configure Third-Party Inference once; then re-run.";
2069
+ var CLAUDE_DESKTOP_UNVERIFIED_PLATFORM = "The Claude Desktop profile path is verified on Linux only \u2014 this platform's path is unverified (kata yc1y), so the CLI will not guess it. Configure Desktop by hand instead: Help \u2192 Troubleshooting \u2192 Enable Developer Mode, then Developer \u2192 Configure Third-Party Inference.";
2070
+ function claudeDesktopRefusal() {
2071
+ return process.platform === "linux" ? CLAUDE_DESKTOP_NO_PROFILE : CLAUDE_DESKTOP_UNVERIFIED_PLATFORM;
2072
+ }
2073
+ async function runClaudeDesktopSetup(creds, routingUrl, opts, deps) {
2074
+ const profilePath = resolveClaudeDesktopAppliedProfile();
2075
+ if (!profilePath) {
2076
+ if (opts.print) {
2077
+ return applyAndReport(
2078
+ buildPlan4({ routingUrl, orgId: creds.org_id, models: [], keyEnvVar: "LUNAROUTE_API_KEY" }),
2079
+ "",
2080
+ false,
2081
+ opts.profile
2082
+ );
2083
+ }
2084
+ console.error(claudeDesktopRefusal());
2085
+ return 1;
2086
+ }
2087
+ if (opts.print) {
2088
+ printClaudeDesktopPreview(profilePath, routingUrl);
2089
+ return 0;
2090
+ }
2091
+ try {
2092
+ if (!await deps.confirm(`Merge LunaRoute's gateway keys into ${profilePath}?`, { yes: opts.yes })) {
2093
+ console.log("Skipped. Nothing written.");
2094
+ return 0;
2095
+ }
2096
+ } catch (err) {
2097
+ if (err instanceof NonInteractiveTerminalError) {
2098
+ console.error(
2099
+ "No interactive terminal available. Re-run with --yes to accept prompts, or --print to preview without writing."
2100
+ );
2101
+ return 1;
2102
+ }
2103
+ throw err;
2104
+ }
2105
+ const keys = claudeDesktopKeys(routingUrl, creds.routing_key);
2106
+ try {
2107
+ const snap = snapshotClaudeDesktopProfile(profilePath, keys);
2108
+ if (snap.taken) console.log(`Snapshot: ${snap.path} (restores this profile on --remove)`);
2109
+ else if (snap.reason === "exists") console.log(`Snapshot: keeping the existing ${snap.path}`);
2110
+ else
2111
+ console.log(
2112
+ `Snapshot: none taken \u2014 ${profilePath} already holds LunaRoute's keys, so there is no pre-LunaRoute state to record.`
2113
+ );
2114
+ } catch (err) {
2115
+ console.error(err instanceof Error ? err.message : String(err));
2116
+ return 1;
2117
+ }
2118
+ const plan = buildKeyPlan3(routingUrl, creds.routing_key, profilePath);
2119
+ return applyAndReport(plan, creds.routing_key, true, opts.profile);
2120
+ }
2121
+ function printClaudeDesktopPreview(profilePath, routingUrl) {
2122
+ const status = claudeDesktopSnapshotStatus(profilePath);
2123
+ const snapPath = claudeDesktopSnapshotPath(profilePath);
2124
+ console.log(`# would merge LunaRoute's gateway keys into ${profilePath}`);
2125
+ console.log(
2126
+ status === "regular" ? `# snapshot: keeping the existing ${snapPath}` : `# snapshot: ${snapPath} (taken before the write)`
2127
+ );
2128
+ console.log(`# the API key is stored literally in that file, never printed here`);
2129
+ for (const [k, v] of Object.entries(claudeDesktopKeys(routingUrl, "<your-lr_\u2026-key>"))) {
2130
+ if (k === "inferenceCustomHeaders") continue;
2131
+ console.log(`# ${k} = ${JSON.stringify(v)}`);
2132
+ }
2133
+ console.log(`# inferenceCustomHeaders["X-LunaRoute-Client"] = "claude-desktop" (your other entries are kept)`);
2134
+ }
2135
+ var REVERSIBLE = ["claude-desktop"];
2136
+ async function runRemove(harness, opts, deps) {
2137
+ if (!REVERSIBLE.includes(harness)) {
2138
+ console.error(`${harness} has no reverse; supports: ${REVERSIBLE.join(", ")}.`);
2139
+ return 1;
2140
+ }
2141
+ const profilePath = resolveClaudeDesktopAppliedProfile();
2142
+ if (!profilePath) {
2143
+ console.error(claudeDesktopRefusal());
2144
+ return 1;
2145
+ }
2146
+ const snapPath = claudeDesktopSnapshotPath(profilePath);
2147
+ const status = claudeDesktopSnapshotStatus(profilePath);
2148
+ const hasSnapshot = status === "regular";
2149
+ const takenAt = hasSnapshot ? claudeDesktopSnapshotTakenAt(profilePath) : null;
2150
+ if (opts.print) {
2151
+ console.log(
2152
+ hasSnapshot ? `# would restore ${profilePath} from ${snapPath}${takenAt ? ` (taken ${takenAt})` : ""}` : status === "invalid" ? `# would refuse: ${snapPath} is not a regular file` : `# would leave ${profilePath} unchanged (no snapshot)`
2153
+ );
2154
+ if (!hasSnapshot) printClaudeDesktopKeysByHand(profilePath);
2155
+ return 0;
2156
+ }
2157
+ if (status === "invalid") {
2158
+ console.error(
2159
+ `Refusing to touch ${profilePath}: ${snapPath} is not a regular file (a symlink, directory or FIFO), so it is not a usable snapshot. Inspect and remove it by hand.`
2160
+ );
2161
+ return 1;
2162
+ }
2163
+ if (!hasSnapshot) {
2164
+ console.log(
2165
+ "No snapshot exists for this profile \u2014 nothing was changed, and nothing was removed (a hand-configured profile can hold exactly the values we would write, and value matching is not authorship). Remove these by hand:"
2166
+ );
2167
+ printClaudeDesktopKeysByHand(profilePath);
2168
+ return 0;
2169
+ }
2170
+ try {
2171
+ const question = `Restore ${profilePath} from the snapshot at ${snapPath}${takenAt ? ` taken ${takenAt}` : ""}?`;
2172
+ if (!await deps.confirm(question, { yes: opts.yes })) {
2173
+ console.log("Skipped. Nothing written.");
2174
+ return 0;
2175
+ }
2176
+ } catch (err) {
2177
+ if (err instanceof NonInteractiveTerminalError) {
2178
+ console.error(
2179
+ "No interactive terminal available. Re-run with --yes to accept prompts, or --print to preview without writing."
2180
+ );
2181
+ return 1;
2182
+ }
2183
+ throw err;
2184
+ }
2185
+ try {
2186
+ const { restored } = restoreClaudeDesktopProfile(profilePath);
2187
+ console.log(
2188
+ restored ? `Restored ${profilePath} from ${snapPath}.` : `Already restored \u2014 ${profilePath} matches the snapshot; nothing written.`
2189
+ );
2190
+ return 0;
2191
+ } catch (err) {
2192
+ console.error(err instanceof Error ? err.message : String(err));
2193
+ return 1;
2194
+ }
2195
+ }
2196
+ function printClaudeDesktopKeysByHand(profilePath) {
2197
+ console.log(` in ${profilePath}:`);
2198
+ for (const [k, v] of Object.entries(claudeDesktopKeys("<your-routing-url>", "<your-lr_\u2026-key>"))) {
2199
+ if (k === "inferenceCustomHeaders") continue;
2200
+ console.log(` delete ${k} only if it is ${JSON.stringify(v)}`);
2201
+ }
2202
+ console.log(
2203
+ ' inside inferenceCustomHeaders, delete ONLY the "X-LunaRoute-Client": "claude-desktop" entry \u2014 keep your other header entries'
2204
+ );
2205
+ }
1734
2206
  async function runHermesSetup(creds, routingUrl, opts, deps) {
1735
2207
  const commands = hermesConfigSetArgs(routingUrl, creds.routing_key);
1736
2208
  try {
@@ -2561,21 +3033,38 @@ function buildRunSpec(ctx) {
2561
3033
  ANTHROPIC_DEFAULT_HAIKU_MODEL: ctx.model,
2562
3034
  // Populates the /model picker from GET /v1/models at startup. LunaRoute
2563
3035
  // already serves the Anthropic-native shape (spike-verified, kata nkey).
2564
- CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1"
3036
+ CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
3037
+ // Claude Code keeps only discovered ids containing "claude"/"anthropic"
3038
+ // (kata 4sak). The normal catalog has no such id, so discovery would
3039
+ // otherwise yield an empty picker and show only ANTHROPIC_MODEL.
3040
+ // X-LunaRoute-Client: claude-desktop selects the gateway's Claude-shaped
3041
+ // alias variant (kata d8qg); aliases translate back to canonical models
3042
+ // at ingress. Informational header only — it never affects
3043
+ // auth/entitlements/billing. Claude Code sends ANTHROPIC_CUSTOM_HEADERS
3044
+ // on the discovery GET too (vendor gateway guide).
3045
+ ANTHROPIC_CUSTOM_HEADERS: "X-LunaRoute-Client: claude-desktop",
3046
+ // LunaRoute fast-paths auxiliary requests (auto-mode classifier and
3047
+ // friends) that carry this hint instead of queueing them behind the
3048
+ // session's own requests. Mirrors setup's export and the Connect tab;
3049
+ // its absence here was the mirror image of the missing discovery flag
3050
+ // (kata d7fm).
3051
+ CLAUDE_CODE_GATEWAY_HINT_HEADERS: "1"
2565
3052
  }
2566
3053
  };
2567
3054
  }
2568
3055
 
2569
3056
  // src/run/adapters/codex.ts
2570
3057
  function buildRunSpec2(ctx) {
2571
- const provider = `{name="LunaRoute",base_url="${ctx.routingUrl}/v1",env_key="LUNAROUTE_API_KEY",wire_api="responses",supports_standalone_web_search=true}`;
3058
+ const provider = `{name="LunaRoute",base_url="${ctx.routingUrl}/v1",model_catalog_url="${ctx.routingUrl}/v1/codex/models",env_key="LUNAROUTE_API_KEY",wire_api="responses",supports_standalone_web_search=true}`;
2572
3059
  const args = [
2573
3060
  "-c",
2574
3061
  'model_provider="lunaroute"',
2575
3062
  "-c",
2576
3063
  `model_providers.lunaroute=${provider}`,
2577
3064
  "-c",
2578
- `model="${ctx.model}"`
3065
+ `model="${ctx.model}"`,
3066
+ "-c",
3067
+ "features.api_key_model_discovery=true"
2579
3068
  ];
2580
3069
  if (Number.isInteger(ctx.contextWindow) && (ctx.contextWindow ?? 0) > 0) {
2581
3070
  args.push("-c", `model_context_window=${ctx.contextWindow}`);
@@ -2694,7 +3183,7 @@ program.command("key").description('Print the stored routing key, for shell use
2694
3183
  program.command("logout").description("Remove stored credentials for the active profile.").action(() => {
2695
3184
  logout(program.opts().profile);
2696
3185
  });
2697
- program.command("setup <harness>").description("Configure a coding harness (opencode | pi | hermes | claude-code | codex | copilot-cli | openclaw | dsh | generic).").option("--print", "print the config instead of writing files", false).option("--routing-url <url>", "override the routing base URL").option("--yes", "accept all confirmation prompts without a TTY (for scripts)", false).option("--extension", "pi only: jump straight to installing the Pi extension").option("--models", "pi only: jump straight to writing the models.json provider block").option("--key <key>", "a LunaRoute routing key (lr_\u2026), e.g. from the dashboard's onboarding page \u2014 stores it and skips the browser login").action(async (harness, opts) => {
3186
+ program.command("setup <harness>").description("Configure a coding harness (opencode | pi | hermes | claude-code | claude-desktop | codex | copilot-cli | openclaw | dsh | generic).").option("--print", "print the config instead of writing files", false).option("--routing-url <url>", "override the routing base URL").option("--yes", "accept all confirmation prompts without a TTY (for scripts)", false).option("--extension", "pi only: jump straight to installing the Pi extension").option("--models", "pi only: jump straight to writing the models.json provider block").option("--remove", "claude-desktop: restore the profile from the snapshot taken at setup (writes nothing when no snapshot exists)").option("--key <key>", "a LunaRoute routing key (lr_\u2026), e.g. from the dashboard's onboarding page \u2014 stores it and skips the browser login").action(async (harness, opts) => {
2698
3187
  const code = await runSetup(harness, {
2699
3188
  profile: program.opts().profile,
2700
3189
  print: opts.print,
@@ -2702,7 +3191,8 @@ program.command("setup <harness>").description("Configure a coding harness (open
2702
3191
  yes: opts.yes,
2703
3192
  extension: opts.extension,
2704
3193
  models: opts.models,
2705
- key: opts.key
3194
+ key: opts.key,
3195
+ remove: opts.remove
2706
3196
  });
2707
3197
  if (code !== 0) process.exit(code);
2708
3198
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunaroute/cli",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "LunaRoute CLI — configure coding harnesses and manage your LunaRoute account.",
5
5
  "repository": {
6
6
  "type": "git",