@lunaroute/cli 0.8.0 → 0.10.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 +626 -50
  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.8.0";
7
+ var version = "0.10.0";
8
8
 
9
9
  // src/login.ts
10
10
  import { createServer } from "http";
@@ -522,6 +522,87 @@ function shQuote(value) {
522
522
  return `'${value.replace(/'/g, "'\\''")}'`;
523
523
  }
524
524
 
525
+ // src/setup/dialect.ts
526
+ var KEY_SENTINEL = "__KEY__";
527
+ var VAR_REF = /^\$([A-Za-z_][A-Za-z0-9_]*)$/;
528
+ function resolveDialect(opts = {}) {
529
+ const platform = opts.platform ?? process.platform;
530
+ const shell = opts.shell?.trim().toLowerCase();
531
+ if (!shell) return platform === "win32" ? "win32" : "posix";
532
+ if (shell === "posix") return "posix";
533
+ if (shell === "powershell") return "win32";
534
+ throw new Error(`Unknown --shell "${opts.shell}" \u2014 use posix (bash, zsh) or powershell.`);
535
+ }
536
+ function quoteArg(value, dialect) {
537
+ return dialect === "win32" ? `'${value.replaceAll("'", "''")}'` : shQuote(value);
538
+ }
539
+ function keyCommand(profile, dialect) {
540
+ const profileArg = profile && profile !== "default" ? ` -p ${quoteArg(profile, dialect)}` : "";
541
+ return `lunaroute key${profileArg}`;
542
+ }
543
+ function envBlockHeader(dialect) {
544
+ return dialect === "win32" ? "# Add these as user environment variables \u2014 GUI-launched processes do not read PowerShell profiles:" : "# Add these to your shell profile:";
545
+ }
546
+ function envBlockNotes(dialect, keyReferenced) {
547
+ if (!keyReferenced) return [];
548
+ if (dialect === "win32") {
549
+ return [
550
+ "# The lines above shell out to 'lunaroute key' \u2014 install the CLI first: npm install -g @lunaroute/cli",
551
+ '# If PowerShell blocks scripts ("running scripts is disabled"), allow them for your user: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned',
552
+ "# The persisted value is a snapshot \u2014 re-run lunaroute setup after rotating your key."
553
+ ];
554
+ }
555
+ return [
556
+ "# The line above shells out to 'lunaroute key' \u2014 install the CLI first: npm install -g @lunaroute/cli",
557
+ "# For non-shell config (systemd Environment=, docker .env), run 'lunaroute key' once and paste the value."
558
+ ];
559
+ }
560
+ function renderPosix(exports, opts) {
561
+ const substitution = `$(${keyCommand(opts.profile, "posix")})`;
562
+ return exports.map(
563
+ (e) => e.value === KEY_SENTINEL ? `export ${e.name}="${substitution}"` : `export ${e.name}=${e.value}`
564
+ );
565
+ }
566
+ function win32AssignmentLines(e, pad) {
567
+ const ref = VAR_REF.exec(e.value);
568
+ const value = e.value === KEY_SENTINEL ? "$lr_key" : ref ? `$env:${ref[1]}` : quoteArg(e.value, "win32");
569
+ return [
570
+ `${pad}$env:${e.name} = ${value}`,
571
+ `${pad}[Environment]::SetEnvironmentVariable('${e.name}', $env:${e.name}, 'User')`
572
+ ];
573
+ }
574
+ function renderWin32(exports, opts, keyIndex) {
575
+ if (keyIndex < 0) return exports.flatMap((e) => win32AssignmentLines(e, ""));
576
+ const pad = " ";
577
+ return [
578
+ `if ($lr_key = (${keyCommand(opts.profile, "win32")})) {`,
579
+ ...exports.flatMap((e) => win32AssignmentLines(e, pad)),
580
+ "} else {",
581
+ ` Write-Error "lunaroute key returned nothing \u2014 if PowerShell is blocking scripts, run: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned"`,
582
+ "}"
583
+ ];
584
+ }
585
+ function probeCommand(opts) {
586
+ const body = JSON.stringify({
587
+ model: opts.model,
588
+ max_tokens: 16,
589
+ messages: [{ role: "user", content: "ping" }]
590
+ });
591
+ if (opts.dialect === "win32") {
592
+ return `Invoke-RestMethod -Method Post -Uri ${quoteArg(opts.url, "win32")} -Headers @{ Authorization = "Bearer $env:${opts.keyEnvVar}"; "content-type" = "application/json" } -Body ${quoteArg(body, "win32")}`;
593
+ }
594
+ return `curl ${quoteArg(opts.url, "posix")} -H "Authorization: Bearer $${opts.keyEnvVar}" -H "content-type: application/json" -d ${quoteArg(body, "posix")}`;
595
+ }
596
+ function renderEnvBlock(exports, opts) {
597
+ const keyIndex = exports.findIndex((e) => e.value === KEY_SENTINEL);
598
+ const lines = opts.dialect === "win32" ? renderWin32(exports, opts, keyIndex) : renderPosix(exports, opts);
599
+ return {
600
+ header: envBlockHeader(opts.dialect),
601
+ lines,
602
+ notes: envBlockNotes(opts.dialect, keyIndex >= 0)
603
+ };
604
+ }
605
+
525
606
  // src/setup/apply.ts
526
607
  function readExistingJson(path) {
527
608
  if (!existsSync3(path)) return null;
@@ -575,8 +656,10 @@ ${nextStr}`);
575
656
  }
576
657
  if (curStr !== null) {
577
658
  if (curStr === nextStr) continue;
578
- copyFileSync(fw.path, `${fw.path}.bak`);
579
- 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
+ }
580
663
  }
581
664
  const dir = dirname(fw.path);
582
665
  const dirExisted = existsSync3(dir);
@@ -589,25 +672,14 @@ ${nextStr}`);
589
672
  if (plan.exports.length > 0) {
590
673
  const printed = plan.exports.filter((e) => !process.env[e.name]);
591
674
  if (printed.length > 0) {
592
- console.log("\n# Add these to your shell profile:");
593
- let referencedKey = false;
594
- for (const e of printed) {
595
- if (e.value === "__KEY__") {
596
- referencedKey = true;
597
- const profileArg = opts.profile && opts.profile !== "default" ? ` -p ${shQuote(opts.profile)}` : "";
598
- console.log(`export ${e.name}="$(lunaroute key${profileArg})"`);
599
- } else {
600
- console.log(`export ${e.name}=${e.value}`);
601
- }
602
- }
603
- if (referencedKey) {
604
- console.log(
605
- "# The line above shells out to 'lunaroute key' \u2014 install the CLI first: npm install -g @lunaroute/cli"
606
- );
607
- console.log(
608
- "# For non-shell config (systemd Environment=, docker .env), run 'lunaroute key' once and paste the value."
609
- );
610
- }
675
+ const block = renderEnvBlock(printed, {
676
+ dialect: opts.dialect ?? resolveDialect(),
677
+ profile: opts.profile
678
+ });
679
+ console.log(`
680
+ ${block.header}`);
681
+ for (const line of block.lines) console.log(line);
682
+ for (const note of block.notes) console.log(note);
611
683
  }
612
684
  for (const e of plan.exports) {
613
685
  if (process.env[e.name]) {
@@ -735,8 +807,9 @@ function describeSpawnError(command, installHint, err) {
735
807
 
736
808
  // src/setup/paths.ts
737
809
  import { execSync } from "child_process";
810
+ import { lstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
738
811
  import { homedir as homedir2 } from "os";
739
- import { join as join3 } from "path";
812
+ import { dirname as dirname2, join as join3 } from "path";
740
813
  function configHome() {
741
814
  return process.env.XDG_CONFIG_HOME || join3(homedir2(), ".config");
742
815
  }
@@ -794,6 +867,47 @@ function gitRepoRoot(cwd = process.cwd()) {
794
867
  return null;
795
868
  }
796
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
+ }
797
911
 
798
912
  // src/setup/adapters/opencode.ts
799
913
  var EXTENSION = "@lunaroute/opencode-extension";
@@ -898,7 +1012,7 @@ function buildKeyPlan(key2) {
898
1012
  }
899
1013
 
900
1014
  // src/setup/adapters/pi.ts
901
- import { readFileSync as readFileSync4 } from "fs";
1015
+ import { readFileSync as readFileSync5 } from "fs";
902
1016
  function buildPiModelEntry(m) {
903
1017
  if (!m.context_window_tokens || !m.max_output_tokens) return null;
904
1018
  const reasoning = m.capabilities?.reasoning === true;
@@ -972,7 +1086,7 @@ function buildPlan2(ctx) {
972
1086
  }
973
1087
  function stalePiProviderExists() {
974
1088
  try {
975
- const obj = JSON.parse(readFileSync4(piModelsPath(), "utf8"));
1089
+ const obj = JSON.parse(readFileSync5(piModelsPath(), "utf8"));
976
1090
  return Boolean(obj.providers?.lunaroute);
977
1091
  } catch {
978
1092
  return false;
@@ -1036,6 +1150,7 @@ function requireFirstModel(ctx, harness) {
1036
1150
  // src/setup/adapters/claudeCode.ts
1037
1151
  function buildPlan3(ctx) {
1038
1152
  const firstModel = requireFirstModel(ctx, "claude-code");
1153
+ const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1039
1154
  return {
1040
1155
  fileWrites: [],
1041
1156
  exports: [
@@ -1051,21 +1166,54 @@ function buildPlan3(ctx) {
1051
1166
  // 009h).
1052
1167
  { name: "ANTHROPIC_AUTH_TOKEN", value: `$${ctx.keyEnvVar}` },
1053
1168
  { name: "ANTHROPIC_MODEL", value: firstModel },
1169
+ // Pins Claude Code's background (Haiku-class) model — titles, summaries,
1170
+ // compaction, the auxiliary classifier — so those requests route through
1171
+ // LunaRoute instead of 404'ing against Anthropic's hardcoded Haiku id,
1172
+ // which LunaRoute does not serve. Mirrors the Connect page and the run
1173
+ // adapter (kata f59a).
1174
+ { name: "ANTHROPIC_DEFAULT_HAIKU_MODEL", value: firstModel },
1054
1175
  // Claude Code sends this hint header (x-claude-code-request-class:
1055
1176
  // auxiliary) only when asked to, and LunaRoute reads it to give
1056
1177
  // auto-mode classifier and other auxiliary requests a fast path
1057
1178
  // instead of queueing them behind the session's own requests.
1058
- { 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" }
1059
1188
  ],
1060
1189
  notes: [
1061
- "\nClaude Code: add the exports above to your shell profile, then restart Claude Code.",
1190
+ ...isWin ? [
1191
+ "\nClaude Code: add the lines above as user environment variables, then open a NEW window (user-scope variables do not reach shells that are already running) and restart Claude Code.",
1192
+ "The block uses the persistent user-scope form rather than a PowerShell profile: PowerShell profiles are not read by GUI-launched processes, and Claude Desktop never reads them at all."
1193
+ ] : ["\nClaude Code: add the exports above to your shell profile, then restart Claude Code."],
1194
+ // Blocker corrected in kata z2sw: Desktop routing does NOT come from these
1195
+ // variables. Saying so here is the whole point — the previous wording
1196
+ // implied env vars were the Desktop lever, which the vendor doc contradicts.
1197
+ "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.",
1198
+ ...isWin ? [
1199
+ "To restart Claude Desktop, quit it fully; if it will not quit, end the Claude process in Task Manager (Ctrl+Shift+Esc).",
1200
+ "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."
1201
+ ] : [],
1062
1202
  `Change ANTHROPIC_MODEL to any of: ${ctx.models.map((m) => m.id).join(", ")}`,
1203
+ "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.",
1204
+ "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.",
1063
1205
  "(Auth travels in the Authorization: Bearer header via ANTHROPIC_AUTH_TOKEN.)",
1064
1206
  "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.",
1065
1207
  "If your Claude Code build predates ANTHROPIC_AUTH_TOKEN support, set ANTHROPIC_API_KEY=$LUNAROUTE_API_KEY instead \u2014 LunaRoute also authenticates lr_ keys sent as x-api-key. Bearer wins whenever both are set.",
1066
- "To set these in ~/.claude/settings.json instead, note its env values are literal \u2014 the key would be baked into the file rather than read from $LUNAROUTE_API_KEY.",
1067
- "If Claude Code hangs or keeps retrying when connecting, your key is likely wrong \u2014 it retries auth errors silently. Debug with the curl below, which fails fast with the real error:",
1068
- ` curl ${ctx.routingUrl}/v1/messages -H "Authorization: Bearer $${ctx.keyEnvVar}" -H "content-type: application/json" -d '{"model":"${firstModel}","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}'`
1208
+ "To set these in ~/.claude/settings.json instead, note its env values are literal \u2014 the key would be baked into the file rather than read from $LUNAROUTE_API_KEY. That reaches the Claude Code CLI on any platform, but Claude Desktop routing comes from its third-party inference configuration, not from settings files.",
1209
+ ...isWin ? [
1210
+ "If Claude Code hangs or keeps retrying when connecting, your key is likely wrong \u2014 it retries auth errors silently. Debug with the command below, which fails fast with the real error:",
1211
+ ` ${probeCommand({ dialect: "win32", url: `${ctx.routingUrl}/v1/messages`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`,
1212
+ "Note the `$env:` form above. Inside a PowerShell double-quoted string, `$LUNAROUTE_API_KEY` interpolates a PowerShell variable, which is a different thing from an environment variable \u2014 the result is an empty token and a misleading 401."
1213
+ ] : [
1214
+ "If Claude Code hangs or keeps retrying when connecting, your key is likely wrong \u2014 it retries auth errors silently. Debug with the curl below, which fails fast with the real error:",
1215
+ ` ${probeCommand({ dialect: "posix", url: `${ctx.routingUrl}/v1/messages`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`
1216
+ ]
1069
1217
  ]
1070
1218
  };
1071
1219
  }
@@ -1093,8 +1241,83 @@ function validatedRoutingUrl(routingUrl) {
1093
1241
  return routingUrl;
1094
1242
  }
1095
1243
 
1096
- // src/setup/adapters/codex.ts
1244
+ // src/setup/adapters/claudeDesktop.ts
1097
1245
  function buildPlan4(ctx) {
1246
+ const dialect = ctx.dialect ?? resolveDialect();
1247
+ const isWin = dialect === "win32";
1248
+ const routingUrl = validatedRoutingUrl(ctx.routingUrl);
1249
+ const profile = {
1250
+ inferenceProvider: "gateway",
1251
+ inferenceGatewayBaseUrl: routingUrl,
1252
+ // A placeholder, never a live secret: a printed plan must not carry the
1253
+ // key (kata a6qg), and this adapter has no key in its context anyway — the
1254
+ // CLI passes one only to plans that WRITE a credential, which this one
1255
+ // deliberately does not.
1256
+ inferenceGatewayApiKey: "<your-lunaroute-key>",
1257
+ inferenceGatewayAuthScheme: "bearer",
1258
+ modelDiscoveryEnabled: true,
1259
+ inferenceCustomHeaders: { "X-LunaRoute-Client": "claude-desktop" }
1260
+ };
1261
+ 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"`;
1262
+ return {
1263
+ fileWrites: [],
1264
+ exports: [],
1265
+ notes: [
1266
+ "\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.",
1267
+ "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.",
1268
+ 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.",
1269
+ "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:",
1270
+ " ~/.config/Claude-3p/configLibrary/<your-profile>.json (verified on Linux; macOS and Windows use the same shape but their paths are unverified)",
1271
+ JSON.stringify(profile, null, 2),
1272
+ "Do NOT add an `inferenceModels` list. A pinned list turns model discovery off, and the picker will then show none of LunaRoute's models.",
1273
+ "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.",
1274
+ "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.",
1275
+ "With a gateway configured, Desktop runs local sessions only: no SSH or cloud environments, and no Remote Control.",
1276
+ "Confirm the key and preview the picker's catalog without opening the app:",
1277
+ ` ${probe}`
1278
+ ]
1279
+ };
1280
+ }
1281
+ function claudeDesktopKeys(routingUrl, key2) {
1282
+ return {
1283
+ inferenceProvider: "gateway",
1284
+ inferenceGatewayBaseUrl: routingUrl,
1285
+ inferenceGatewayApiKey: key2,
1286
+ inferenceGatewayAuthScheme: "bearer",
1287
+ modelDiscoveryEnabled: true,
1288
+ inferenceCustomHeaders: { "X-LunaRoute-Client": "claude-desktop" }
1289
+ };
1290
+ }
1291
+ function buildKeyPlan3(routingUrl, key2, appliedPath) {
1292
+ const ours = claudeDesktopKeys(routingUrl, key2);
1293
+ const ourHeaders = ours.inferenceCustomHeaders;
1294
+ return {
1295
+ fileWrites: [
1296
+ {
1297
+ kind: "json",
1298
+ path: appliedPath,
1299
+ backup: false,
1300
+ merge: (existing) => {
1301
+ if (existing === null) return ours;
1302
+ if (typeof existing !== "object" || Array.isArray(existing)) {
1303
+ throw new Error(
1304
+ `refusing to modify ${appliedPath}: it is valid JSON but not a JSON object.`
1305
+ );
1306
+ }
1307
+ const obj = existing;
1308
+ const existingHeaders = typeof obj.inferenceCustomHeaders === "object" && obj.inferenceCustomHeaders !== null && !Array.isArray(obj.inferenceCustomHeaders) ? obj.inferenceCustomHeaders : {};
1309
+ return { ...obj, ...ours, inferenceCustomHeaders: { ...existingHeaders, ...ourHeaders } };
1310
+ }
1311
+ }
1312
+ ],
1313
+ exports: [],
1314
+ notes: []
1315
+ };
1316
+ }
1317
+
1318
+ // src/setup/adapters/codex.ts
1319
+ function buildPlan5(ctx) {
1320
+ const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1098
1321
  const base = validatedRoutingUrl(ctx.routingUrl);
1099
1322
  const model = requireFirstModel(ctx, "codex");
1100
1323
  const contextWindow = ctx.models[0]?.context_window_tokens;
@@ -1117,7 +1340,7 @@ function buildPlan4(ctx) {
1117
1340
  fileWrites: [{ kind: "text", path: codexProfilePath(), content }],
1118
1341
  exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
1119
1342
  notes: [
1120
- "\nCodex: add the export above to your shell profile, then start Codex with `codex --profile lunaroute`.",
1343
+ isWin ? "\nCodex: add the line above as a user environment variable, then open a NEW window and start Codex with `codex --profile lunaroute`." : "\nCodex: add the export above to your shell profile, then start Codex with `codex --profile lunaroute`.",
1121
1344
  `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.`,
1122
1345
  "The key rides the Authorization: Bearer header via env_key; LunaRoute authenticates the lr_ key at the edge and never forwards it upstream.",
1123
1346
  "One file: the model and the named provider live in the profile file \u2014 your ~/.codex/config.toml is untouched.",
@@ -1127,8 +1350,9 @@ function buildPlan4(ctx) {
1127
1350
  }
1128
1351
 
1129
1352
  // src/setup/adapters/copilotCli.ts
1130
- function buildPlan5(ctx) {
1353
+ function buildPlan6(ctx) {
1131
1354
  const firstModel = requireFirstModel(ctx, "copilot-cli");
1355
+ const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1132
1356
  return {
1133
1357
  fileWrites: [],
1134
1358
  exports: [
@@ -1143,17 +1367,26 @@ function buildPlan5(ctx) {
1143
1367
  { name: "COPILOT_MODEL", value: firstModel }
1144
1368
  ],
1145
1369
  notes: [
1146
- "\nGitHub Copilot CLI: add the exports above to your shell profile, then restart Copilot CLI.",
1370
+ isWin ? "\nGitHub Copilot CLI: add the lines above as user environment variables, then open a NEW window and restart Copilot CLI." : "\nGitHub Copilot CLI: add the exports above to your shell profile, then restart Copilot CLI.",
1147
1371
  `Change COPILOT_MODEL to any of: ${ctx.models.map((m) => m.id).join(", ")}`,
1148
1372
  "Auth rides the Authorization header as a bearer token; LunaRoute recognizes the lr_ key prefix and authenticates it at the edge (it is never sent to the upstream provider).",
1149
- `Anthropic-style alternative: set COPILOT_PROVIDER_TYPE=anthropic and COPILOT_PROVIDER_BASE_URL=${ctx.routingUrl} (no /v1); the key then rides the x-api-key header.`,
1150
- `Verify with: curl ${ctx.routingUrl}/v1/chat/completions -H "Authorization: Bearer $${ctx.keyEnvVar}" -H "content-type: application/json" -d '{"model":"${firstModel}","max_tokens":16,"messages":[{"role":"user","content":"ping"}]}'`
1373
+ // The routing URL is untrusted here too: validatedRoutingUrl accepts
1374
+ // quotes and semicolons, so hand-wrapping it in single quotes left a
1375
+ // breakout. Quote it for the dialect like every other rendered value.
1376
+ isWin ? `Anthropic-style alternative: set $env:COPILOT_PROVIDER_TYPE = 'anthropic' and $env:COPILOT_PROVIDER_BASE_URL = ${quoteArg(ctx.routingUrl, "win32")} (no /v1); the key then rides the x-api-key header.` : `Anthropic-style alternative: set COPILOT_PROVIDER_TYPE=anthropic and COPILOT_PROVIDER_BASE_URL=${quoteArg(ctx.routingUrl, "posix")} (no /v1); the key then rides the x-api-key header.`,
1377
+ ...isWin ? [
1378
+ "Verify with:",
1379
+ ` ${probeCommand({ dialect: "win32", url: `${ctx.routingUrl}/v1/chat/completions`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`
1380
+ ] : [
1381
+ "Verify with:",
1382
+ ` ${probeCommand({ dialect: "posix", url: `${ctx.routingUrl}/v1/chat/completions`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`
1383
+ ]
1151
1384
  ]
1152
1385
  };
1153
1386
  }
1154
1387
 
1155
1388
  // src/setup/adapters/generic.ts
1156
- function buildPlan6(ctx) {
1389
+ function buildPlan7(ctx) {
1157
1390
  return {
1158
1391
  fileWrites: [],
1159
1392
  exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
@@ -1169,13 +1402,17 @@ function buildPlan6(ctx) {
1169
1402
  }
1170
1403
 
1171
1404
  // src/setup/adapters/openclaw.ts
1405
+ var PREFERRED_MODEL = "deepseek-4.1-flash";
1406
+ function primaryModel(ctx) {
1407
+ return ctx.models.find((m) => m.id === PREFERRED_MODEL)?.id ?? requireFirstModel(ctx, "openclaw");
1408
+ }
1172
1409
  function asRecord(v) {
1173
1410
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
1174
1411
  }
1175
- function buildPlan7(ctx) {
1412
+ function buildPlan8(ctx) {
1176
1413
  const base = validatedRoutingUrl(ctx.routingUrl);
1177
1414
  const models = ctx.models.map((m) => ({ id: m.id, name: m.id }));
1178
- const primary = requireFirstModel(ctx, "openclaw");
1415
+ const primary = primaryModel(ctx);
1179
1416
  return {
1180
1417
  fileWrites: [
1181
1418
  {
@@ -1230,7 +1467,7 @@ openclaw: restart the gateway, then \`openclaw models list\` and \`openclaw mode
1230
1467
  }
1231
1468
 
1232
1469
  // src/setup/adapters/dsh.ts
1233
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1470
+ import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
1234
1471
  import { isMap, isSeq, parseDocument as parseDocument2 } from "yaml";
1235
1472
  var PI_AI_ROW_ID = "llm-pi-ai";
1236
1473
  var ROUTE_KEY = "lunaroute";
@@ -1324,7 +1561,7 @@ function homePatchOverridesPiAi() {
1324
1561
  const path = dshHomePatchPath();
1325
1562
  if (!existsSync4(path)) return false;
1326
1563
  try {
1327
- const doc = parseDocument2(readFileSync5(path, "utf8"), { logLevel: "silent" });
1564
+ const doc = parseDocument2(readFileSync6(path, "utf8"), { logLevel: "silent" });
1328
1565
  if (!isSeq(doc.contents)) return false;
1329
1566
  return doc.contents.items.some(
1330
1567
  (item) => isMap(item) && item.get("id") === PI_AI_ROW_ID
@@ -1333,7 +1570,7 @@ function homePatchOverridesPiAi() {
1333
1570
  return false;
1334
1571
  }
1335
1572
  }
1336
- function buildPlan8(ctx) {
1573
+ function buildPlan9(ctx) {
1337
1574
  const base = validatedRoutingUrl(ctx.routingUrl);
1338
1575
  if (ctx.models.length === 0) {
1339
1576
  throw new Error("no LunaRoute chat models in the catalog \u2014 nothing to configure for dsh");
@@ -1379,16 +1616,205 @@ function buildPlan8(ctx) {
1379
1616
  };
1380
1617
  }
1381
1618
 
1619
+ // src/setup/snapshot.ts
1620
+ import {
1621
+ chmodSync as chmodSync4,
1622
+ closeSync,
1623
+ constants,
1624
+ fstatSync,
1625
+ linkSync,
1626
+ lstatSync as lstatSync2,
1627
+ mkdirSync as mkdirSync4,
1628
+ openSync,
1629
+ readFileSync as readFileSync7,
1630
+ renameSync as renameSync2,
1631
+ rmSync as rmSync2,
1632
+ statSync,
1633
+ writeFileSync as writeFileSync4
1634
+ } from "fs";
1635
+ import { randomBytes as randomBytes2 } from "crypto";
1636
+ import { basename, dirname as dirname3, join as join4 } from "path";
1637
+ function claudeDesktopSnapshotDir() {
1638
+ return join4(configDir(), "backups", "claude-desktop");
1639
+ }
1640
+ function claudeDesktopSnapshotPath(profilePath) {
1641
+ return join4(claudeDesktopSnapshotDir(), basename(profilePath));
1642
+ }
1643
+ function notRegular(path) {
1644
+ return new Error(`${path} is not a regular file \u2014 refusing to read it.`);
1645
+ }
1646
+ function readRegularFileNoFollow(path) {
1647
+ let fd;
1648
+ try {
1649
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
1650
+ } catch {
1651
+ throw notRegular(path);
1652
+ }
1653
+ try {
1654
+ if (!fstatSync(fd).isFile()) throw notRegular(path);
1655
+ return readFileSync7(fd);
1656
+ } finally {
1657
+ closeSync(fd);
1658
+ }
1659
+ }
1660
+ function writeFileAtomic(path, data, mode = 384) {
1661
+ const tmp = stageTemp(path, data, mode);
1662
+ renameSync2(tmp, path);
1663
+ }
1664
+ function stageTemp(path, data, mode = 384) {
1665
+ const tmp = join4(dirname3(path), `.${basename(path)}.${randomBytes2(6).toString("hex")}.tmp`);
1666
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
1667
+ try {
1668
+ writeFileSync4(fd, data);
1669
+ } finally {
1670
+ closeSync(fd);
1671
+ }
1672
+ return tmp;
1673
+ }
1674
+ function writeFileNoClobber(path, data, mode = 384) {
1675
+ const tmp = stageTemp(path, data, mode);
1676
+ try {
1677
+ linkSync(tmp, path);
1678
+ return true;
1679
+ } catch (err) {
1680
+ if (err.code === "EEXIST") return false;
1681
+ throw err;
1682
+ } finally {
1683
+ rmSync2(tmp, { force: true });
1684
+ }
1685
+ }
1686
+ function validateSnapshotDir() {
1687
+ const dir = claudeDesktopSnapshotDir();
1688
+ let st;
1689
+ try {
1690
+ st = lstatSync2(dir);
1691
+ } catch {
1692
+ return;
1693
+ }
1694
+ const ownedByUs = typeof process.getuid === "function" && st.uid === process.getuid();
1695
+ if (!st.isDirectory() || st.isSymbolicLink() || !ownedByUs) {
1696
+ throw new Error(
1697
+ `refusing to use ${dir} as the snapshot directory: it is not a directory owned by this user.`
1698
+ );
1699
+ }
1700
+ }
1701
+ function ensureSnapshotDir() {
1702
+ const dir = claudeDesktopSnapshotDir();
1703
+ mkdirSync4(dirname3(dir), { recursive: true, mode: 448 });
1704
+ let st;
1705
+ try {
1706
+ st = lstatSync2(dir);
1707
+ } catch {
1708
+ mkdirSync4(dir, { recursive: true, mode: 448 });
1709
+ st = lstatSync2(dir);
1710
+ }
1711
+ const ownedByUs = typeof process.getuid === "function" && st.uid === process.getuid();
1712
+ if (!st.isDirectory() || st.isSymbolicLink() || !ownedByUs) {
1713
+ throw new Error(
1714
+ `refusing to use ${dir} as the snapshot directory: it is not a directory owned by this user.`
1715
+ );
1716
+ }
1717
+ if ((st.mode & 511) !== 448) chmodSync4(dir, 448);
1718
+ return dir;
1719
+ }
1720
+ function alreadyConfigured(existing, keys) {
1721
+ if (typeof existing !== "object" || existing === null || Array.isArray(existing)) return false;
1722
+ const obj = existing;
1723
+ for (const [k, v] of Object.entries(keys)) {
1724
+ if (k === "inferenceCustomHeaders") {
1725
+ const ours = v["X-LunaRoute-Client"];
1726
+ const theirs = obj.inferenceCustomHeaders?.["X-LunaRoute-Client"];
1727
+ if (theirs !== ours) return false;
1728
+ continue;
1729
+ }
1730
+ if (obj[k] !== v) return false;
1731
+ }
1732
+ return true;
1733
+ }
1734
+ function snapshotClaudeDesktopProfile(profilePath, keys) {
1735
+ ensureSnapshotDir();
1736
+ const path = claudeDesktopSnapshotPath(profilePath);
1737
+ const existing = inspectSnapshotPath(path);
1738
+ if (existing.kind === "invalid") {
1739
+ throw new Error(`refusing to reuse a snapshot at ${path}: ${existing.why}.`);
1740
+ }
1741
+ if (existing.kind === "regular") {
1742
+ readRegularFileNoFollow(path);
1743
+ return { taken: false, path, reason: "exists" };
1744
+ }
1745
+ const bytes = readRegularFileNoFollow(profilePath);
1746
+ let parsed;
1747
+ try {
1748
+ parsed = JSON.parse(bytes.toString("utf8"));
1749
+ } catch {
1750
+ throw new Error(`refusing to snapshot ${profilePath}: it is not valid JSON.`);
1751
+ }
1752
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1753
+ throw new Error(`refusing to snapshot ${profilePath}: it is not a JSON object.`);
1754
+ }
1755
+ if (alreadyConfigured(parsed, keys)) return { taken: false, path, reason: "already-configured" };
1756
+ if (!writeFileNoClobber(path, bytes)) {
1757
+ const winner = inspectSnapshotPath(path);
1758
+ if (winner.kind === "invalid") {
1759
+ throw new Error(`refusing to reuse a snapshot at ${path}: ${winner.why}.`);
1760
+ }
1761
+ if (winner.kind === "none") {
1762
+ throw new Error(
1763
+ `refusing to continue: an entry appeared at ${path} during publication and is now gone \u2014 re-run setup.`
1764
+ );
1765
+ }
1766
+ readRegularFileNoFollow(path);
1767
+ return { taken: false, path, reason: "exists" };
1768
+ }
1769
+ return { taken: true, path };
1770
+ }
1771
+ function inspectSnapshotPath(path) {
1772
+ let st;
1773
+ try {
1774
+ st = lstatSync2(path);
1775
+ } catch (err) {
1776
+ const code = err.code;
1777
+ if (code === "ENOENT") return { kind: "none" };
1778
+ return { kind: "invalid", why: `cannot read ${path} (${code ?? "unknown error"})` };
1779
+ }
1780
+ if (st.isFile() && !st.isSymbolicLink()) return { kind: "regular", stats: st };
1781
+ return { kind: "invalid", why: `${path} is not a regular file (a symlink, directory or FIFO)` };
1782
+ }
1783
+ function claudeDesktopSnapshotStatus(profilePath) {
1784
+ return inspectSnapshotPath(claudeDesktopSnapshotPath(profilePath)).kind;
1785
+ }
1786
+ function claudeDesktopSnapshotTakenAt(profilePath) {
1787
+ try {
1788
+ const st = statSync(claudeDesktopSnapshotPath(profilePath));
1789
+ return st.mtime.toISOString().slice(0, 16).replace("T", " ");
1790
+ } catch {
1791
+ return null;
1792
+ }
1793
+ }
1794
+ function restoreClaudeDesktopProfile(profilePath) {
1795
+ validateSnapshotDir();
1796
+ const path = claudeDesktopSnapshotPath(profilePath);
1797
+ const entry = inspectSnapshotPath(path);
1798
+ if (entry.kind === "none") return { restored: false, reason: "no-snapshot" };
1799
+ if (entry.kind === "invalid") throw new Error(`refusing to restore from ${path}: ${entry.why}.`);
1800
+ const snapshot = readRegularFileNoFollow(path);
1801
+ const current = readRegularFileNoFollow(profilePath);
1802
+ if (snapshot.equals(current)) return { restored: false };
1803
+ writeFileAtomic(profilePath, snapshot);
1804
+ return { restored: true };
1805
+ }
1806
+
1382
1807
  // src/commands/setup.ts
1383
1808
  var ADAPTERS = {
1384
1809
  opencode: buildPlan,
1385
1810
  pi: buildPlan2,
1386
- openclaw: buildPlan7,
1387
- dsh: buildPlan8,
1811
+ openclaw: buildPlan8,
1812
+ dsh: buildPlan9,
1388
1813
  "claude-code": buildPlan3,
1389
- codex: buildPlan4,
1390
- "copilot-cli": buildPlan5,
1391
- generic: buildPlan6
1814
+ "claude-desktop": buildPlan4,
1815
+ codex: buildPlan5,
1816
+ "copilot-cli": buildPlan6,
1817
+ generic: buildPlan7
1392
1818
  };
1393
1819
  var PI_INSTALL_PACKAGES = ["npm:@lunaroute/pi-extension"];
1394
1820
  var PI_INSTALL_HINT = "Install pi first: npm install -g --ignore-scripts @earendil-works/pi-coding-agent (https://pi.dev)";
@@ -1412,6 +1838,7 @@ async function runSetup(harness, opts, deps = {
1412
1838
  );
1413
1839
  return 1;
1414
1840
  }
1841
+ if (opts.remove) return runRemove(harness, opts, deps);
1415
1842
  let stored = loadProfile(opts.profile);
1416
1843
  const settings = resolveSettings(opts.profile);
1417
1844
  if (opts.key && !LR_KEY_RE.test(opts.key)) {
@@ -1463,6 +1890,7 @@ async function runSetup(harness, opts, deps = {
1463
1890
  }
1464
1891
  const creds = await requireCreds(opts, deps, stored);
1465
1892
  if (!creds) return 1;
1893
+ if (harness === "claude-desktop") return runClaudeDesktopSetup(creds, routingUrl, opts, deps);
1466
1894
  if (harness === "hermes") {
1467
1895
  return runHermesSetup(creds, routingUrl, opts, deps);
1468
1896
  }
@@ -1621,6 +2049,144 @@ async function runPiSetup(opts, stored, routingUrl, deps) {
1621
2049
  return 1;
1622
2050
  }
1623
2051
  }
2052
+ 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.";
2053
+ 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.";
2054
+ function claudeDesktopRefusal() {
2055
+ return process.platform === "linux" ? CLAUDE_DESKTOP_NO_PROFILE : CLAUDE_DESKTOP_UNVERIFIED_PLATFORM;
2056
+ }
2057
+ async function runClaudeDesktopSetup(creds, routingUrl, opts, deps) {
2058
+ const profilePath = resolveClaudeDesktopAppliedProfile();
2059
+ if (!profilePath) {
2060
+ if (opts.print) {
2061
+ return applyAndReport(
2062
+ buildPlan4({ routingUrl, orgId: creds.org_id, models: [], keyEnvVar: "LUNAROUTE_API_KEY" }),
2063
+ "",
2064
+ false,
2065
+ opts.profile
2066
+ );
2067
+ }
2068
+ console.error(claudeDesktopRefusal());
2069
+ return 1;
2070
+ }
2071
+ if (opts.print) {
2072
+ printClaudeDesktopPreview(profilePath, routingUrl);
2073
+ return 0;
2074
+ }
2075
+ try {
2076
+ if (!await deps.confirm(`Merge LunaRoute's gateway keys into ${profilePath}?`, { yes: opts.yes })) {
2077
+ console.log("Skipped. Nothing written.");
2078
+ return 0;
2079
+ }
2080
+ } catch (err) {
2081
+ if (err instanceof NonInteractiveTerminalError) {
2082
+ console.error(
2083
+ "No interactive terminal available. Re-run with --yes to accept prompts, or --print to preview without writing."
2084
+ );
2085
+ return 1;
2086
+ }
2087
+ throw err;
2088
+ }
2089
+ const keys = claudeDesktopKeys(routingUrl, creds.routing_key);
2090
+ try {
2091
+ const snap = snapshotClaudeDesktopProfile(profilePath, keys);
2092
+ if (snap.taken) console.log(`Snapshot: ${snap.path} (restores this profile on --remove)`);
2093
+ else if (snap.reason === "exists") console.log(`Snapshot: keeping the existing ${snap.path}`);
2094
+ else
2095
+ console.log(
2096
+ `Snapshot: none taken \u2014 ${profilePath} already holds LunaRoute's keys, so there is no pre-LunaRoute state to record.`
2097
+ );
2098
+ } catch (err) {
2099
+ console.error(err instanceof Error ? err.message : String(err));
2100
+ return 1;
2101
+ }
2102
+ const plan = buildKeyPlan3(routingUrl, creds.routing_key, profilePath);
2103
+ return applyAndReport(plan, creds.routing_key, true, opts.profile);
2104
+ }
2105
+ function printClaudeDesktopPreview(profilePath, routingUrl) {
2106
+ const status = claudeDesktopSnapshotStatus(profilePath);
2107
+ const snapPath = claudeDesktopSnapshotPath(profilePath);
2108
+ console.log(`# would merge LunaRoute's gateway keys into ${profilePath}`);
2109
+ console.log(
2110
+ status === "regular" ? `# snapshot: keeping the existing ${snapPath}` : `# snapshot: ${snapPath} (taken before the write)`
2111
+ );
2112
+ console.log(`# the API key is stored literally in that file, never printed here`);
2113
+ for (const [k, v] of Object.entries(claudeDesktopKeys(routingUrl, "<your-lr_\u2026-key>"))) {
2114
+ if (k === "inferenceCustomHeaders") continue;
2115
+ console.log(`# ${k} = ${JSON.stringify(v)}`);
2116
+ }
2117
+ console.log(`# inferenceCustomHeaders["X-LunaRoute-Client"] = "claude-desktop" (your other entries are kept)`);
2118
+ }
2119
+ var REVERSIBLE = ["claude-desktop"];
2120
+ async function runRemove(harness, opts, deps) {
2121
+ if (!REVERSIBLE.includes(harness)) {
2122
+ console.error(`${harness} has no reverse; supports: ${REVERSIBLE.join(", ")}.`);
2123
+ return 1;
2124
+ }
2125
+ const profilePath = resolveClaudeDesktopAppliedProfile();
2126
+ if (!profilePath) {
2127
+ console.error(claudeDesktopRefusal());
2128
+ return 1;
2129
+ }
2130
+ const snapPath = claudeDesktopSnapshotPath(profilePath);
2131
+ const status = claudeDesktopSnapshotStatus(profilePath);
2132
+ const hasSnapshot = status === "regular";
2133
+ const takenAt = hasSnapshot ? claudeDesktopSnapshotTakenAt(profilePath) : null;
2134
+ if (opts.print) {
2135
+ console.log(
2136
+ 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)`
2137
+ );
2138
+ if (!hasSnapshot) printClaudeDesktopKeysByHand(profilePath);
2139
+ return 0;
2140
+ }
2141
+ if (status === "invalid") {
2142
+ console.error(
2143
+ `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.`
2144
+ );
2145
+ return 1;
2146
+ }
2147
+ if (!hasSnapshot) {
2148
+ console.log(
2149
+ "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:"
2150
+ );
2151
+ printClaudeDesktopKeysByHand(profilePath);
2152
+ return 0;
2153
+ }
2154
+ try {
2155
+ const question = `Restore ${profilePath} from the snapshot at ${snapPath}${takenAt ? ` taken ${takenAt}` : ""}?`;
2156
+ if (!await deps.confirm(question, { yes: opts.yes })) {
2157
+ console.log("Skipped. Nothing written.");
2158
+ return 0;
2159
+ }
2160
+ } catch (err) {
2161
+ if (err instanceof NonInteractiveTerminalError) {
2162
+ console.error(
2163
+ "No interactive terminal available. Re-run with --yes to accept prompts, or --print to preview without writing."
2164
+ );
2165
+ return 1;
2166
+ }
2167
+ throw err;
2168
+ }
2169
+ try {
2170
+ const { restored } = restoreClaudeDesktopProfile(profilePath);
2171
+ console.log(
2172
+ restored ? `Restored ${profilePath} from ${snapPath}.` : `Already restored \u2014 ${profilePath} matches the snapshot; nothing written.`
2173
+ );
2174
+ return 0;
2175
+ } catch (err) {
2176
+ console.error(err instanceof Error ? err.message : String(err));
2177
+ return 1;
2178
+ }
2179
+ }
2180
+ function printClaudeDesktopKeysByHand(profilePath) {
2181
+ console.log(` in ${profilePath}:`);
2182
+ for (const [k, v] of Object.entries(claudeDesktopKeys("<your-routing-url>", "<your-lr_\u2026-key>"))) {
2183
+ if (k === "inferenceCustomHeaders") continue;
2184
+ console.log(` delete ${k} only if it is ${JSON.stringify(v)}`);
2185
+ }
2186
+ console.log(
2187
+ ' inside inferenceCustomHeaders, delete ONLY the "X-LunaRoute-Client": "claude-desktop" entry \u2014 keep your other header entries'
2188
+ );
2189
+ }
1624
2190
  async function runHermesSetup(creds, routingUrl, opts, deps) {
1625
2191
  const commands = hermesConfigSetArgs(routingUrl, creds.routing_key);
1626
2192
  try {
@@ -2451,7 +3017,16 @@ function buildRunSpec(ctx) {
2451
3017
  ANTHROPIC_DEFAULT_HAIKU_MODEL: ctx.model,
2452
3018
  // Populates the /model picker from GET /v1/models at startup. LunaRoute
2453
3019
  // already serves the Anthropic-native shape (spike-verified, kata nkey).
2454
- CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1"
3020
+ CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: "1",
3021
+ // Claude Code keeps only discovered ids containing "claude"/"anthropic"
3022
+ // (kata 4sak). The normal catalog has no such id, so discovery would
3023
+ // otherwise yield an empty picker and show only ANTHROPIC_MODEL.
3024
+ // X-LunaRoute-Client: claude-desktop selects the gateway's Claude-shaped
3025
+ // alias variant (kata d8qg); aliases translate back to canonical models
3026
+ // at ingress. Informational header only — it never affects
3027
+ // auth/entitlements/billing. Claude Code sends ANTHROPIC_CUSTOM_HEADERS
3028
+ // on the discovery GET too (vendor gateway guide).
3029
+ ANTHROPIC_CUSTOM_HEADERS: "X-LunaRoute-Client: claude-desktop"
2455
3030
  }
2456
3031
  };
2457
3032
  }
@@ -2584,7 +3159,7 @@ program.command("key").description('Print the stored routing key, for shell use
2584
3159
  program.command("logout").description("Remove stored credentials for the active profile.").action(() => {
2585
3160
  logout(program.opts().profile);
2586
3161
  });
2587
- 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) => {
3162
+ 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) => {
2588
3163
  const code = await runSetup(harness, {
2589
3164
  profile: program.opts().profile,
2590
3165
  print: opts.print,
@@ -2592,7 +3167,8 @@ program.command("setup <harness>").description("Configure a coding harness (open
2592
3167
  yes: opts.yes,
2593
3168
  extension: opts.extension,
2594
3169
  models: opts.models,
2595
- key: opts.key
3170
+ key: opts.key,
3171
+ remove: opts.remove
2596
3172
  });
2597
3173
  if (code !== 0) process.exit(code);
2598
3174
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunaroute/cli",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "LunaRoute CLI — configure coding harnesses and manage your LunaRoute account.",
5
5
  "repository": {
6
6
  "type": "git",