@lunaroute/cli 0.7.0 → 0.9.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 +147 -34
  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.7.0";
7
+ var version = "0.9.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;
@@ -589,25 +670,14 @@ ${nextStr}`);
589
670
  if (plan.exports.length > 0) {
590
671
  const printed = plan.exports.filter((e) => !process.env[e.name]);
591
672
  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
- }
673
+ const block = renderEnvBlock(printed, {
674
+ dialect: opts.dialect ?? resolveDialect(),
675
+ profile: opts.profile
676
+ });
677
+ console.log(`
678
+ ${block.header}`);
679
+ for (const line of block.lines) console.log(line);
680
+ for (const note of block.notes) console.log(note);
611
681
  }
612
682
  for (const e of plan.exports) {
613
683
  if (process.env[e.name]) {
@@ -1036,6 +1106,7 @@ function requireFirstModel(ctx, harness) {
1036
1106
  // src/setup/adapters/claudeCode.ts
1037
1107
  function buildPlan3(ctx) {
1038
1108
  const firstModel = requireFirstModel(ctx, "claude-code");
1109
+ const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1039
1110
  return {
1040
1111
  fileWrites: [],
1041
1112
  exports: [
@@ -1051,21 +1122,45 @@ function buildPlan3(ctx) {
1051
1122
  // 009h).
1052
1123
  { name: "ANTHROPIC_AUTH_TOKEN", value: `$${ctx.keyEnvVar}` },
1053
1124
  { name: "ANTHROPIC_MODEL", value: firstModel },
1125
+ // Pins Claude Code's background (Haiku-class) model — titles, summaries,
1126
+ // compaction, the auxiliary classifier — so those requests route through
1127
+ // LunaRoute instead of 404'ing against Anthropic's hardcoded Haiku id,
1128
+ // which LunaRoute does not serve. Mirrors the Connect page and the run
1129
+ // adapter (kata f59a).
1130
+ { name: "ANTHROPIC_DEFAULT_HAIKU_MODEL", value: firstModel },
1054
1131
  // Claude Code sends this hint header (x-claude-code-request-class:
1055
1132
  // auxiliary) only when asked to, and LunaRoute reads it to give
1056
- // auto-mode classifier and other auxiliary requests a fast dedicated
1057
- // lane instead of queueing them behind the session's own requests.
1133
+ // auto-mode classifier and other auxiliary requests a fast path
1134
+ // instead of queueing them behind the session's own requests.
1058
1135
  { name: "CLAUDE_CODE_GATEWAY_HINT_HEADERS", value: "1" }
1059
1136
  ],
1060
1137
  notes: [
1061
- "\nClaude Code: add the exports above to your shell profile, then restart Claude Code.",
1138
+ ...isWin ? [
1139
+ "\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.",
1140
+ "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."
1141
+ ] : ["\nClaude Code: add the exports above to your shell profile, then restart Claude Code."],
1142
+ // Blocker corrected in kata z2sw: Desktop routing does NOT come from these
1143
+ // variables. Saying so here is the whole point — the previous wording
1144
+ // 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.",
1146
+ ...isWin ? [
1147
+ "To restart Claude Desktop, quit it fully; if it will not quit, end the Claude process in Task Manager (Ctrl+Shift+Esc).",
1148
+ "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
+ ] : [],
1062
1150
  `Change ANTHROPIC_MODEL to any of: ${ctx.models.map((m) => m.id).join(", ")}`,
1151
+ "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
1152
  "(Auth travels in the Authorization: Bearer header via ANTHROPIC_AUTH_TOKEN.)",
1064
- "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 dedicated lane; without it they are still detected via their wire marker, just less directly.",
1153
+ "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
1154
  "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"}]}'`
1155
+ "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.",
1156
+ ...isWin ? [
1157
+ "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:",
1158
+ ` ${probeCommand({ dialect: "win32", url: `${ctx.routingUrl}/v1/messages`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`,
1159
+ "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."
1160
+ ] : [
1161
+ "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:",
1162
+ ` ${probeCommand({ dialect: "posix", url: `${ctx.routingUrl}/v1/messages`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`
1163
+ ]
1069
1164
  ]
1070
1165
  };
1071
1166
  }
@@ -1095,6 +1190,7 @@ function validatedRoutingUrl(routingUrl) {
1095
1190
 
1096
1191
  // src/setup/adapters/codex.ts
1097
1192
  function buildPlan4(ctx) {
1193
+ const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1098
1194
  const base = validatedRoutingUrl(ctx.routingUrl);
1099
1195
  const model = requireFirstModel(ctx, "codex");
1100
1196
  const contextWindow = ctx.models[0]?.context_window_tokens;
@@ -1108,13 +1204,16 @@ function buildPlan4(ctx) {
1108
1204
  'name = "LunaRoute"',
1109
1205
  `base_url = "${base}/v1"`,
1110
1206
  'env_key = "LUNAROUTE_API_KEY"',
1111
- 'wire_api = "responses"'
1207
+ 'wire_api = "responses"',
1208
+ // Codex only calls /v1/alpha/search when the provider opts in; the
1209
+ // endpoint is derived from base_url by the /responses suffix swap.
1210
+ "supports_standalone_web_search = true"
1112
1211
  ]).join("\n") + "\n";
1113
1212
  return {
1114
1213
  fileWrites: [{ kind: "text", path: codexProfilePath(), content }],
1115
1214
  exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
1116
1215
  notes: [
1117
- "\nCodex: add the export above to your shell profile, then start Codex with `codex --profile lunaroute`.",
1216
+ 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`.",
1118
1217
  `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.`,
1119
1218
  "The key rides the Authorization: Bearer header via env_key; LunaRoute authenticates the lr_ key at the edge and never forwards it upstream.",
1120
1219
  "One file: the model and the named provider live in the profile file \u2014 your ~/.codex/config.toml is untouched.",
@@ -1126,6 +1225,7 @@ function buildPlan4(ctx) {
1126
1225
  // src/setup/adapters/copilotCli.ts
1127
1226
  function buildPlan5(ctx) {
1128
1227
  const firstModel = requireFirstModel(ctx, "copilot-cli");
1228
+ const isWin = (ctx.dialect ?? resolveDialect()) === "win32";
1129
1229
  return {
1130
1230
  fileWrites: [],
1131
1231
  exports: [
@@ -1140,11 +1240,20 @@ function buildPlan5(ctx) {
1140
1240
  { name: "COPILOT_MODEL", value: firstModel }
1141
1241
  ],
1142
1242
  notes: [
1143
- "\nGitHub Copilot CLI: add the exports above to your shell profile, then restart Copilot CLI.",
1243
+ 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.",
1144
1244
  `Change COPILOT_MODEL to any of: ${ctx.models.map((m) => m.id).join(", ")}`,
1145
1245
  "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).",
1146
- `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.`,
1147
- `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"}]}'`
1246
+ // The routing URL is untrusted here too: validatedRoutingUrl accepts
1247
+ // quotes and semicolons, so hand-wrapping it in single quotes left a
1248
+ // breakout. Quote it for the dialect like every other rendered value.
1249
+ 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.`,
1250
+ ...isWin ? [
1251
+ "Verify with:",
1252
+ ` ${probeCommand({ dialect: "win32", url: `${ctx.routingUrl}/v1/chat/completions`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`
1253
+ ] : [
1254
+ "Verify with:",
1255
+ ` ${probeCommand({ dialect: "posix", url: `${ctx.routingUrl}/v1/chat/completions`, model: firstModel, keyEnvVar: ctx.keyEnvVar })}`
1256
+ ]
1148
1257
  ]
1149
1258
  };
1150
1259
  }
@@ -1166,13 +1275,17 @@ function buildPlan6(ctx) {
1166
1275
  }
1167
1276
 
1168
1277
  // src/setup/adapters/openclaw.ts
1278
+ var PREFERRED_MODEL = "deepseek-4.1-flash";
1279
+ function primaryModel(ctx) {
1280
+ return ctx.models.find((m) => m.id === PREFERRED_MODEL)?.id ?? requireFirstModel(ctx, "openclaw");
1281
+ }
1169
1282
  function asRecord(v) {
1170
1283
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
1171
1284
  }
1172
1285
  function buildPlan7(ctx) {
1173
1286
  const base = validatedRoutingUrl(ctx.routingUrl);
1174
1287
  const models = ctx.models.map((m) => ({ id: m.id, name: m.id }));
1175
- const primary = requireFirstModel(ctx, "openclaw");
1288
+ const primary = primaryModel(ctx);
1176
1289
  return {
1177
1290
  fileWrites: [
1178
1291
  {
@@ -2455,7 +2568,7 @@ function buildRunSpec(ctx) {
2455
2568
 
2456
2569
  // src/run/adapters/codex.ts
2457
2570
  function buildRunSpec2(ctx) {
2458
- const provider = `{name="LunaRoute",base_url="${ctx.routingUrl}/v1",env_key="LUNAROUTE_API_KEY",wire_api="responses"}`;
2571
+ const provider = `{name="LunaRoute",base_url="${ctx.routingUrl}/v1",env_key="LUNAROUTE_API_KEY",wire_api="responses",supports_standalone_web_search=true}`;
2459
2572
  const args = [
2460
2573
  "-c",
2461
2574
  'model_provider="lunaroute"',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunaroute/cli",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "LunaRoute CLI — configure coding harnesses and manage your LunaRoute account.",
5
5
  "repository": {
6
6
  "type": "git",