@lunaroute/cli 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +267 -79
  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.4.0";
7
+ var version = "0.6.0";
8
8
 
9
9
  // src/login.ts
10
10
  import { createServer } from "http";
@@ -236,6 +236,34 @@ function resolveSettings(name) {
236
236
  };
237
237
  }
238
238
 
239
+ // src/pending.ts
240
+ import { chmodSync as chmodSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
241
+ import { join as join2 } from "path";
242
+ function pendingPath(profile) {
243
+ const safe = profile.replace(/[^A-Za-z0-9_-]/g, "_");
244
+ return join2(configDir(), `pending-login-${safe}.json`);
245
+ }
246
+ function savePending(profile, p) {
247
+ mkdirSync2(configDir(), { recursive: true, mode: 448 });
248
+ const path = pendingPath(profile);
249
+ writeFileSync2(path, JSON.stringify(p, null, 2), { mode: 384 });
250
+ chmodSync2(path, 384);
251
+ }
252
+ function loadPending(profile) {
253
+ const path = pendingPath(profile);
254
+ if (!existsSync2(path)) return null;
255
+ try {
256
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
257
+ if (!parsed?.verifier || !parsed?.challenge || !parsed?.api_url) return null;
258
+ return parsed;
259
+ } catch {
260
+ return null;
261
+ }
262
+ }
263
+ function clearPending(profile) {
264
+ rmSync(pendingPath(profile), { force: true });
265
+ }
266
+
239
267
  // src/login.ts
240
268
  var LOGIN_TIMEOUT_MS = 3 * 6e4;
241
269
  async function waitWithTimeout(server, ms) {
@@ -324,14 +352,80 @@ async function runLogin(profile) {
324
352
  \u2713 Logged in as ${result.user_email} (org ${result.org_id}).`);
325
353
  console.log(` Routing key saved to profile "${profile}".`);
326
354
  }
355
+ async function runLoginStart(profile) {
356
+ const settings = resolveSettings(profile);
357
+ const state = genState();
358
+ const verifier = genVerifier();
359
+ const challenge = challengeFor(verifier);
360
+ savePending(profile, {
361
+ verifier,
362
+ challenge,
363
+ state,
364
+ api_url: settings.api_url
365
+ });
366
+ const url = `${settings.front_url}/cli-auth?challenge=${challenge}&state=${state}&mode=code`;
367
+ console.log("Open this URL on any device to authorize:\n " + url + "\n");
368
+ console.log("Then paste the code it shows back here with:");
369
+ console.log(" lunaroute login --finish <code>");
370
+ }
371
+ async function runLoginFinish(profile, code) {
372
+ const pending = loadPending(profile);
373
+ if (!pending) {
374
+ throw new Error(
375
+ "no pending login for this profile \u2014 run `lunaroute login --start` first"
376
+ );
377
+ }
378
+ const settings = resolveSettings(profile);
379
+ let result;
380
+ try {
381
+ result = await exchangeCode(pending.api_url, {
382
+ code,
383
+ verifier: pending.verifier,
384
+ label: hostname()
385
+ });
386
+ } catch (err) {
387
+ const msg = err instanceof Error ? err.message : String(err);
388
+ if (/INVALID_CODE|PKCE_MISMATCH/.test(msg)) clearPending(profile);
389
+ throw err;
390
+ }
391
+ saveProfile(profile, {
392
+ api_url: pending.api_url,
393
+ routing_url: settings.routing_url,
394
+ front_url: settings.front_url,
395
+ org_id: result.org_id,
396
+ routing_key: result.full_key,
397
+ user_email: result.user_email
398
+ });
399
+ clearPending(profile);
400
+ console.log(`
401
+ \u2713 Logged in as ${result.user_email} (org ${result.org_id}).`);
402
+ console.log(` Routing key saved to profile "${profile}".`);
403
+ }
327
404
 
328
405
  // src/commands/login.ts
406
+ function report(err) {
407
+ console.error(`Login failed: ${err.message}`);
408
+ process.exitCode = 1;
409
+ }
329
410
  async function login(profile) {
330
411
  try {
331
412
  await runLogin(profile);
332
413
  } catch (err) {
333
- console.error(`Login failed: ${err.message}`);
334
- process.exitCode = 1;
414
+ report(err);
415
+ }
416
+ }
417
+ async function loginStart(profile) {
418
+ try {
419
+ await runLoginStart(profile);
420
+ } catch (err) {
421
+ report(err);
422
+ }
423
+ }
424
+ async function loginFinish(profile, code) {
425
+ try {
426
+ await runLoginFinish(profile, code);
427
+ } catch (err) {
428
+ report(err);
335
429
  }
336
430
  }
337
431
 
@@ -348,6 +442,17 @@ function whoami(profile) {
348
442
  console.log(` API: ${creds.api_url}`);
349
443
  }
350
444
 
445
+ // src/commands/key.ts
446
+ function key(profile) {
447
+ const creds = loadProfile(profile);
448
+ if (!creds?.routing_key) {
449
+ console.error('Not logged in. Run "lunaroute login" to get started.');
450
+ process.exitCode = 1;
451
+ return;
452
+ }
453
+ console.log(creds.routing_key);
454
+ }
455
+
351
456
  // src/commands/logout.ts
352
457
  function logout(profile) {
353
458
  if (!loadProfile(profile)) {
@@ -372,14 +477,14 @@ function isChatModel(m) {
372
477
  }
373
478
  return true;
374
479
  }
375
- async function fetchModels(routingUrl, key, opts) {
480
+ async function fetchModels(routingUrl, key2, opts) {
376
481
  const url = `${routingUrl}/v1/models`;
377
- const headers = key ? { Authorization: `Bearer ${key}` } : {};
482
+ const headers = key2 ? { Authorization: `Bearer ${key2}` } : {};
378
483
  const res = await fetch(url, { method: "GET", headers, signal: opts?.signal });
379
484
  if (!res.ok) {
380
485
  if (res.status === 401) {
381
486
  throw new KeyRejectedError(
382
- key ? `the routing service rejected that key (HTTP 401) \u2014 check that you copied the whole lr_ key` : `the routing service requires a key for /v1/models (HTTP 401) \u2014 run "lunaroute login" or pass --key`
487
+ key2 ? `the routing service rejected that key (HTTP 401) \u2014 check that you copied the whole lr_ key` : `the routing service requires a key for /v1/models (HTTP 401) \u2014 run "lunaroute login" or pass --key`
383
488
  );
384
489
  }
385
490
  throw new Error(`failed to fetch models: HTTP ${res.status} from ${url}`);
@@ -401,18 +506,25 @@ async function fetchModels(routingUrl, key, opts) {
401
506
 
402
507
  // src/setup/apply.ts
403
508
  import {
404
- mkdirSync as mkdirSync2,
405
- readFileSync as readFileSync2,
406
- writeFileSync as writeFileSync2,
509
+ mkdirSync as mkdirSync3,
510
+ readFileSync as readFileSync3,
511
+ writeFileSync as writeFileSync3,
407
512
  copyFileSync,
408
- existsSync as existsSync2,
409
- chmodSync as chmodSync2
513
+ existsSync as existsSync3,
514
+ chmodSync as chmodSync3
410
515
  } from "fs";
411
516
  import { dirname } from "path";
412
517
  import { parseDocument } from "yaml";
518
+
519
+ // src/shell.ts
520
+ function shQuote(value) {
521
+ return `'${value.replace(/'/g, "'\\''")}'`;
522
+ }
523
+
524
+ // src/setup/apply.ts
413
525
  function readExistingJson(path) {
414
- if (!existsSync2(path)) return null;
415
- const raw = readFileSync2(path, "utf8").trim();
526
+ if (!existsSync3(path)) return null;
527
+ const raw = readFileSync3(path, "utf8").trim();
416
528
  if (raw === "") return null;
417
529
  try {
418
530
  return JSON.parse(raw);
@@ -423,7 +535,7 @@ function readExistingJson(path) {
423
535
  }
424
536
  }
425
537
  function resolveYamlContent(fw) {
426
- const curStr = existsSync2(fw.path) ? readFileSync2(fw.path, "utf8") : null;
538
+ const curStr = existsSync3(fw.path) ? readFileSync3(fw.path, "utf8") : null;
427
539
  const doc = parseDocument(curStr ?? "", { logLevel: "silent" });
428
540
  if (doc.errors.length > 0) {
429
541
  const first = doc.errors[0];
@@ -439,7 +551,7 @@ function resolveYamlContent(fw) {
439
551
  }
440
552
  function resolveContent(fw) {
441
553
  if (fw.kind === "text") {
442
- const curStr2 = existsSync2(fw.path) ? readFileSync2(fw.path, "utf8") : null;
554
+ const curStr2 = existsSync3(fw.path) ? readFileSync3(fw.path, "utf8") : null;
443
555
  return { nextStr: fw.content, curStr: curStr2 };
444
556
  }
445
557
  if (fw.kind === "yaml") return resolveYamlContent(fw);
@@ -466,18 +578,40 @@ ${nextStr}`);
466
578
  summary.backedUp.push(`${fw.path}.bak`);
467
579
  }
468
580
  const dir = dirname(fw.path);
469
- const dirExisted = existsSync2(dir);
470
- mkdirSync2(dir, { recursive: true });
471
- if (!dirExisted) chmodSync2(dir, fw.dirMode ?? 448);
472
- writeFileSync2(fw.path, nextStr, { mode: fw.fileMode ?? 384 });
473
- chmodSync2(fw.path, fw.fileMode ?? 384);
581
+ const dirExisted = existsSync3(dir);
582
+ mkdirSync3(dir, { recursive: true });
583
+ if (!dirExisted) chmodSync3(dir, fw.dirMode ?? 448);
584
+ writeFileSync3(fw.path, nextStr, { mode: fw.fileMode ?? 384 });
585
+ chmodSync3(fw.path, fw.fileMode ?? 384);
474
586
  summary.written.push(fw.path);
475
587
  }
476
588
  if (plan.exports.length > 0) {
477
- console.log("\n# Add these to your shell profile:");
589
+ const printed = plan.exports.filter((e) => !process.env[e.name]);
590
+ if (printed.length > 0) {
591
+ console.log("\n# Add these to your shell profile:");
592
+ let referencedKey = false;
593
+ for (const e of printed) {
594
+ if (e.value === "__KEY__") {
595
+ referencedKey = true;
596
+ const profileArg = opts.profile && opts.profile !== "default" ? ` -p ${shQuote(opts.profile)}` : "";
597
+ console.log(`export ${e.name}="$(lunaroute key${profileArg})"`);
598
+ } else {
599
+ console.log(`export ${e.name}=${e.value}`);
600
+ }
601
+ }
602
+ if (referencedKey) {
603
+ console.log(
604
+ "# The line above shells out to 'lunaroute key' \u2014 install the CLI first: npm install -g @lunaroute/cli"
605
+ );
606
+ console.log(
607
+ "# For non-shell config (systemd Environment=, docker .env), run 'lunaroute key' once and paste the value."
608
+ );
609
+ }
610
+ }
478
611
  for (const e of plan.exports) {
479
- const value = e.value === "__KEY__" ? opts.key : e.value;
480
- console.log(`export ${e.name}=${value}`);
612
+ if (process.env[e.name]) {
613
+ console.log(`# ${e.name} is already set in your environment \u2014 not printing its value.`);
614
+ }
481
615
  }
482
616
  }
483
617
  for (const note of plan.notes) console.log(note);
@@ -601,51 +735,51 @@ function describeSpawnError(command, installHint, err) {
601
735
  // src/setup/paths.ts
602
736
  import { execSync } from "child_process";
603
737
  import { homedir as homedir2 } from "os";
604
- import { join as join2 } from "path";
738
+ import { join as join3 } from "path";
605
739
  function configHome() {
606
- return process.env.XDG_CONFIG_HOME || join2(homedir2(), ".config");
740
+ return process.env.XDG_CONFIG_HOME || join3(homedir2(), ".config");
607
741
  }
608
742
  function opencodeConfigPath() {
609
- return join2(configHome(), "opencode", "opencode.json");
743
+ return join3(configHome(), "opencode", "opencode.json");
610
744
  }
611
745
  function opencodeAuthPath() {
612
- const dataHome = process.env.XDG_DATA_HOME || join2(homedir2(), ".local", "share");
613
- return join2(dataHome, "opencode", "auth.json");
746
+ const dataHome = process.env.XDG_DATA_HOME || join3(homedir2(), ".local", "share");
747
+ return join3(dataHome, "opencode", "auth.json");
614
748
  }
615
749
  function openclawConfigPath() {
616
- return join2(homedir2(), ".openclaw", "openclaw.json");
750
+ return join3(homedir2(), ".openclaw", "openclaw.json");
617
751
  }
618
752
  function codexProfilePath() {
619
- const home = process.env.CODEX_HOME || join2(homedir2(), ".codex");
620
- return join2(home, "lunaroute.config.toml");
753
+ const home = process.env.CODEX_HOME || join3(homedir2(), ".codex");
754
+ return join3(home, "lunaroute.config.toml");
621
755
  }
622
756
  function piModelsPath() {
623
- return join2(homedir2(), ".pi", "agent", "models.json");
757
+ return join3(homedir2(), ".pi", "agent", "models.json");
624
758
  }
625
759
  function piAuthPath() {
626
- return join2(homedir2(), ".pi", "agent", "auth.json");
760
+ return join3(homedir2(), ".pi", "agent", "auth.json");
627
761
  }
628
762
  function dshHome() {
629
- return process.env.DSH_HOME || join2(homedir2(), ".dsh");
763
+ return process.env.DSH_HOME || join3(homedir2(), ".dsh");
630
764
  }
631
765
  function dshProfilePatchPath(profile = "web") {
632
- return join2(dshHome(), "profiles", profile, "cordis.patch.yml");
766
+ return join3(dshHome(), "profiles", profile, "cordis.patch.yml");
633
767
  }
634
768
  function dshHomePatchPath() {
635
- return join2(dshHome(), "cordis.patch.yml");
769
+ return join3(dshHome(), "cordis.patch.yml");
636
770
  }
637
771
  var LUNAROUTE_SKILL_NAME = "lunaroute-memory";
638
772
  function claudeUserConfigPath() {
639
- return join2(homedir2(), ".claude.json");
773
+ return join3(homedir2(), ".claude.json");
640
774
  }
641
775
  function claudeUserSkillPath(name = LUNAROUTE_SKILL_NAME) {
642
- return join2(homedir2(), ".claude", "skills", name, "SKILL.md");
776
+ return join3(homedir2(), ".claude", "skills", name, "SKILL.md");
643
777
  }
644
778
  function claudeProjectMcpPath(root) {
645
- return join2(root, ".mcp.json");
779
+ return join3(root, ".mcp.json");
646
780
  }
647
781
  function claudeProjectSkillPath(root, name = LUNAROUTE_SKILL_NAME) {
648
- return join2(root, ".claude", "skills", name, "SKILL.md");
782
+ return join3(root, ".claude", "skills", name, "SKILL.md");
649
783
  }
650
784
  function gitRepoRoot(cwd = process.cwd()) {
651
785
  try {
@@ -742,7 +876,7 @@ function providerPlan(ctx) {
742
876
  ]
743
877
  };
744
878
  }
745
- function buildKeyPlan(key) {
879
+ function buildKeyPlan(key2) {
746
880
  return {
747
881
  fileWrites: [
748
882
  {
@@ -751,7 +885,7 @@ function buildKeyPlan(key) {
751
885
  merge: (existing) => {
752
886
  const obj = existing ?? {};
753
887
  delete obj["lunaroute/"];
754
- return { ...obj, lunaroute: { type: "api", key } };
888
+ return { ...obj, lunaroute: { type: "api", key: key2 } };
755
889
  }
756
890
  }
757
891
  ],
@@ -763,7 +897,7 @@ function buildKeyPlan(key) {
763
897
  }
764
898
 
765
899
  // src/setup/adapters/pi.ts
766
- import { readFileSync as readFileSync3 } from "fs";
900
+ import { readFileSync as readFileSync4 } from "fs";
767
901
  function buildPiModelEntry(m) {
768
902
  if (!m.context_window_tokens || !m.max_output_tokens) return null;
769
903
  const reasoning = m.capabilities?.reasoning === true;
@@ -837,7 +971,7 @@ function buildPlan2(ctx) {
837
971
  }
838
972
  function stalePiProviderExists() {
839
973
  try {
840
- const obj = JSON.parse(readFileSync3(piModelsPath(), "utf8"));
974
+ const obj = JSON.parse(readFileSync4(piModelsPath(), "utf8"));
841
975
  return Boolean(obj.providers?.lunaroute);
842
976
  } catch {
843
977
  return false;
@@ -867,7 +1001,7 @@ function buildStaleProviderCleanupPlan() {
867
1001
  };
868
1002
  }
869
1003
  var KEY_EXPIRES_MS = 10 * 365 * 24 * 60 * 60 * 1e3;
870
- function buildKeyPlan2(key) {
1004
+ function buildKeyPlan2(key2) {
871
1005
  return {
872
1006
  fileWrites: [
873
1007
  {
@@ -877,7 +1011,7 @@ function buildKeyPlan2(key) {
877
1011
  const obj = existing ?? {};
878
1012
  return {
879
1013
  ...obj,
880
- lunaroute: { type: "oauth", access: key, refresh: "", expires: Date.now() + KEY_EXPIRES_MS }
1014
+ lunaroute: { type: "oauth", access: key2, refresh: "", expires: Date.now() + KEY_EXPIRES_MS }
881
1015
  };
882
1016
  }
883
1017
  }
@@ -1074,13 +1208,30 @@ openclaw: restart the gateway, then \`openclaw models list\` and \`openclaw mode
1074
1208
  }
1075
1209
 
1076
1210
  // src/setup/adapters/dsh.ts
1077
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
1211
+ import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1078
1212
  import { isMap, isSeq, parseDocument as parseDocument2 } from "yaml";
1079
1213
  var PI_AI_ROW_ID = "llm-pi-ai";
1080
1214
  var ROUTE_KEY = "lunaroute";
1081
1215
  function asRecord2(v) {
1082
1216
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
1083
1217
  }
1218
+ var DSH_THINKING_FORMATS = /* @__PURE__ */ new Set([
1219
+ "openai",
1220
+ "deepseek",
1221
+ "openrouter",
1222
+ "together",
1223
+ "baseten",
1224
+ "zai",
1225
+ "qwen",
1226
+ "chat-template",
1227
+ "qwen-chat-template",
1228
+ "string-thinking",
1229
+ "ant-ling"
1230
+ ]);
1231
+ function thinkingFormatOf(m) {
1232
+ const pi = asRecord2(m.client_compat?.pi);
1233
+ return typeof pi.thinkingFormat === "string" ? pi.thinkingFormat : void 0;
1234
+ }
1084
1235
  function buildReasoning(m) {
1085
1236
  if (m.capabilities?.reasoning !== true) return null;
1086
1237
  const pi = asRecord2(m.client_compat?.pi);
@@ -1094,7 +1245,9 @@ function buildReasoning(m) {
1094
1245
  }
1095
1246
  if (Object.keys(efforts).length < 2) return null;
1096
1247
  const compat = {};
1097
- if (typeof pi.thinkingFormat === "string") compat.thinkingFormat = pi.thinkingFormat;
1248
+ if (typeof pi.thinkingFormat === "string" && DSH_THINKING_FORMATS.has(pi.thinkingFormat)) {
1249
+ compat.thinkingFormat = pi.thinkingFormat;
1250
+ }
1098
1251
  if (typeof pi.maxTokensField === "string") compat.maxTokensField = pi.maxTokensField;
1099
1252
  if (typeof pi.supportsReasoningEffort === "boolean") {
1100
1253
  compat.supportsReasoningEffort = pi.supportsReasoningEffort;
@@ -1132,11 +1285,11 @@ function ensureProviderRow(doc) {
1132
1285
  seq.add(row);
1133
1286
  return row;
1134
1287
  }
1135
- function ensureMap(doc, parent, key) {
1136
- const existing = parent.get(key);
1288
+ function ensureMap(doc, parent, key2) {
1289
+ const existing = parent.get(key2);
1137
1290
  if (isMap(existing)) return existing;
1138
1291
  const created = doc.createNode({});
1139
- parent.set(key, created);
1292
+ parent.set(key2, created);
1140
1293
  return created;
1141
1294
  }
1142
1295
  function mergeProvider(doc, provider) {
@@ -1147,9 +1300,9 @@ function mergeProvider(doc, provider) {
1147
1300
  }
1148
1301
  function homePatchOverridesPiAi() {
1149
1302
  const path = dshHomePatchPath();
1150
- if (!existsSync3(path)) return false;
1303
+ if (!existsSync4(path)) return false;
1151
1304
  try {
1152
- const doc = parseDocument2(readFileSync4(path, "utf8"), { logLevel: "silent" });
1305
+ const doc = parseDocument2(readFileSync5(path, "utf8"), { logLevel: "silent" });
1153
1306
  if (!isSeq(doc.contents)) return false;
1154
1307
  return doc.contents.items.some(
1155
1308
  (item) => isMap(item) && item.get("id") === PI_AI_ROW_ID
@@ -1176,6 +1329,16 @@ function buildPlan8(ctx) {
1176
1329
  "The key rides `Authorization: Bearer lr_\u2026` via apiKeyEnv; LunaRoute authenticates it at the edge and never forwards it upstream.",
1177
1330
  "Or paste the key in Settings \u2192 Models instead \u2014 dsh stores it in $DSH_HOME/.credentials.yaml."
1178
1331
  ];
1332
+ const unsupportedFormats = [
1333
+ ...new Set(
1334
+ ctx.models.map(thinkingFormatOf).filter((f) => f !== void 0 && !DSH_THINKING_FORMATS.has(f))
1335
+ )
1336
+ ];
1337
+ if (unsupportedFormats.length > 0) {
1338
+ notes.push(
1339
+ `dsh does not accept thinkingFormat value(s): ${unsupportedFormats.join(", ")} \u2014 omitted from the config. Fix client_compat.pi.thinkingFormat in the catalog.`
1340
+ );
1341
+ }
1179
1342
  if (homePatchOverridesPiAi()) {
1180
1343
  notes.push(
1181
1344
  `WARNING: $DSH_HOME/cordis.patch.yml also has an \`llm-pi-ai\` row. It is a later config layer, so it REPLACES the row setup just wrote \u2014 remove it, or move the lunaroute provider there.`
@@ -1304,7 +1467,7 @@ async function runSetup(harness, opts, deps = {
1304
1467
  return 1;
1305
1468
  }
1306
1469
  try {
1307
- const summary = await applyPlan(plan, { print: opts.print, key: creds.routing_key });
1470
+ const summary = await applyPlan(plan, { print: opts.print, key: creds.routing_key, profile: opts.profile });
1308
1471
  if (!opts.print && summary.written.length > 0) {
1309
1472
  console.log(`
1310
1473
  Wrote: ${summary.written.join(", ")}`);
@@ -1322,6 +1485,11 @@ var OPENCODE_LOGIN_HINT = "Or re-run and choose the extension \u2014 it logs in
1322
1485
  var PI_LOGIN_HINT = "Or re-run and choose the extension \u2014 login happens via /login lunaroute inside pi.";
1323
1486
  async function requireCreds(opts, deps, stored, hint) {
1324
1487
  if (stored?.routing_key) return stored;
1488
+ const envKey = process.env.LUNAROUTE_API_KEY?.trim();
1489
+ if (envKey) {
1490
+ const settings = resolveSettings(opts.profile);
1491
+ return { ...settings, routing_key: envKey };
1492
+ }
1325
1493
  const decline = [NOT_LOGGED_IN, hint].filter(Boolean).join(" ");
1326
1494
  try {
1327
1495
  const ok = await deps.confirm('Not logged in. Run "lunaroute login" now? (opens your browser)');
@@ -1362,7 +1530,8 @@ async function runPiSetup(opts, stored, routingUrl, deps) {
1362
1530
  return applyPiModels(
1363
1531
  creds2,
1364
1532
  routingUrl,
1365
- await deps.confirm("Merge LunaRoute provider into ~/.pi/agent/models.json (backup kept, other providers preserved)?", { yes: opts.yes })
1533
+ await deps.confirm("Merge LunaRoute provider into ~/.pi/agent/models.json (backup kept, other providers preserved)?", { yes: opts.yes }),
1534
+ opts.profile
1366
1535
  );
1367
1536
  }
1368
1537
  const code = await installPiPackages(deps);
@@ -1376,7 +1545,7 @@ async function runPiSetup(opts, stored, routingUrl, deps) {
1376
1545
  return 0;
1377
1546
  }
1378
1547
  const plan = combinePlans(buildKeyPlan2(creds2.routing_key), stalePiProviderExists() ? buildStaleProviderCleanupPlan() : null);
1379
- const wcode = await applyAndReport(plan, creds2.routing_key, true);
1548
+ const wcode = await applyAndReport(plan, creds2.routing_key, true, opts.profile);
1380
1549
  if (wcode !== 0) return wcode;
1381
1550
  console.log("\nDone. Start pi \u2014 it is signed in. Pick a model with /model.");
1382
1551
  return 0;
@@ -1399,7 +1568,8 @@ async function runPiSetup(opts, stored, routingUrl, deps) {
1399
1568
  return applyPiModels(
1400
1569
  creds2,
1401
1570
  routingUrl,
1402
- await deps.confirm("Merge LunaRoute provider into ~/.pi/agent/models.json (backup kept, other providers preserved)?", { yes: opts.yes })
1571
+ await deps.confirm("Merge LunaRoute provider into ~/.pi/agent/models.json (backup kept, other providers preserved)?", { yes: opts.yes }),
1572
+ opts.profile
1403
1573
  );
1404
1574
  }
1405
1575
  if (await deps.confirm(
@@ -1415,7 +1585,8 @@ async function runPiSetup(opts, stored, routingUrl, deps) {
1415
1585
  routingUrl,
1416
1586
  await deps.confirm("Merge LunaRoute provider into ~/.pi/agent/models.json (backup kept, other providers preserved)?", {
1417
1587
  yes: opts.yes
1418
- })
1588
+ }),
1589
+ opts.profile
1419
1590
  );
1420
1591
  } catch (err) {
1421
1592
  if (err instanceof NonInteractiveTerminalError) {
@@ -1433,7 +1604,7 @@ async function runHermesSetup(creds, routingUrl, opts, deps) {
1433
1604
  try {
1434
1605
  if (opts.print) {
1435
1606
  console.log("\n# would run:");
1436
- for (const args of commands) console.log(` hermes ${args.join(" ")}`);
1607
+ for (const args of commands) console.log(` hermes ${hermesCommandLine(args, creds.routing_key, opts.profile)}`);
1437
1608
  console.log(
1438
1609
  "\nThen start hermes and run /model custom:lunaroute:<model> to pick a LunaRoute model (models auto-discover from /v1/models)."
1439
1610
  );
@@ -1445,7 +1616,7 @@ async function runHermesSetup(creds, routingUrl, opts, deps) {
1445
1616
  return runHermesConfigSets(deps.spawn, routingUrl, creds.routing_key);
1446
1617
  }
1447
1618
  console.log("Skipped. Re-run with --yes, or configure manually:");
1448
- for (const args of commands) console.log(` hermes ${args.join(" ")}`);
1619
+ for (const args of commands) console.log(` hermes ${hermesCommandLine(args, creds.routing_key, opts.profile)}`);
1449
1620
  console.log("\nThen start hermes and run /model custom:lunaroute:<model> to pick a LunaRoute model.");
1450
1621
  return 0;
1451
1622
  } catch (err) {
@@ -1457,16 +1628,20 @@ async function runHermesSetup(creds, routingUrl, opts, deps) {
1457
1628
  return 1;
1458
1629
  }
1459
1630
  }
1460
- function hermesConfigSetArgs(routingUrl, key) {
1631
+ function hermesConfigSetArgs(routingUrl, key2) {
1461
1632
  return [
1462
1633
  ["config", "set", "providers.lunaroute.api", `${routingUrl}/v1`],
1463
1634
  ["config", "set", "providers.lunaroute.key_env", "LUNAROUTE_API_KEY"],
1464
1635
  ["config", "set", "providers.lunaroute.transport", "chat_completions"],
1465
- ["config", "set", "LUNAROUTE_API_KEY", key]
1636
+ ["config", "set", "LUNAROUTE_API_KEY", key2]
1466
1637
  ];
1467
1638
  }
1468
- async function runHermesConfigSets(spawn, routingUrl, key) {
1469
- const commands = hermesConfigSetArgs(routingUrl, key);
1639
+ function hermesCommandLine(args, key2, profile) {
1640
+ const profileArg = profile && profile !== "default" ? ` -p ${shQuote(profile)}` : "";
1641
+ return args.map((a) => a === key2 ? `"$(lunaroute key${profileArg})"` : a).join(" ");
1642
+ }
1643
+ async function runHermesConfigSets(spawn, routingUrl, key2) {
1644
+ const commands = hermesConfigSetArgs(routingUrl, key2);
1470
1645
  const setKeys = commands.map((c) => c[2]);
1471
1646
  for (let i = 0; i < commands.length; i++) {
1472
1647
  const code = await new Promise((resolve) => {
@@ -1507,7 +1682,7 @@ async function runOpencodeSetup(stored, settings, routingUrl, opts, deps) {
1507
1682
  ),
1508
1683
  opts.key ? buildKeyPlan("<your-api-key>") : null
1509
1684
  );
1510
- return applyAndReport(plan, stored?.routing_key ?? "", false);
1685
+ return applyAndReport(plan, stored?.routing_key ?? "", false, opts.profile);
1511
1686
  }
1512
1687
  if (opts.key) {
1513
1688
  const creds2 = await requireCreds(opts, deps, stored);
@@ -1521,14 +1696,15 @@ async function runOpencodeSetup(stored, settings, routingUrl, opts, deps) {
1521
1696
  routingUrl,
1522
1697
  await deps.confirm("Merge LunaRoute provider into opencode.json (backup kept, other providers preserved)?", {
1523
1698
  yes: opts.yes
1524
- })
1699
+ }),
1700
+ opts.profile
1525
1701
  );
1526
1702
  }
1527
1703
  const plan = buildPlan(
1528
1704
  { routingUrl, orgId: settings.org_id, models: [], keyEnvVar: "LUNAROUTE_API_KEY" },
1529
1705
  { extension: true }
1530
1706
  );
1531
- const code = await applyAndReport(plan, creds2.routing_key, true);
1707
+ const code = await applyAndReport(plan, creds2.routing_key, true, opts.profile);
1532
1708
  if (code !== 0) return code;
1533
1709
  const store = await deps.confirm(
1534
1710
  "Store the key in ~/.local/share/opencode/auth.json (replaces any existing LunaRoute login; other credentials preserved)?",
@@ -1538,7 +1714,7 @@ async function runOpencodeSetup(stored, settings, routingUrl, opts, deps) {
1538
1714
  console.log("\nSkipped. Inside opencode, run /connect to sign in.");
1539
1715
  return 0;
1540
1716
  }
1541
- const wcode = await applyAndReport(buildKeyPlan(creds2.routing_key), creds2.routing_key, true);
1717
+ const wcode = await applyAndReport(buildKeyPlan(creds2.routing_key), creds2.routing_key, true, opts.profile);
1542
1718
  if (wcode !== 0) return wcode;
1543
1719
  console.log("\nDone. Start opencode \u2014 it is signed in. Pick a model with /models.");
1544
1720
  return 0;
@@ -1551,7 +1727,7 @@ async function runOpencodeSetup(stored, settings, routingUrl, opts, deps) {
1551
1727
  { routingUrl, orgId: settings.org_id, models: [], keyEnvVar: "LUNAROUTE_API_KEY" },
1552
1728
  { extension: true }
1553
1729
  );
1554
- const code = await applyAndReport(plan, stored?.routing_key ?? "", true);
1730
+ const code = await applyAndReport(plan, stored?.routing_key ?? "", true, opts.profile);
1555
1731
  if (code !== 0) return code;
1556
1732
  if (await deps.confirm("Start opencode now? (if it's already open, quit and reopen it to load the extension)", {
1557
1733
  yes: opts.yes
@@ -1567,7 +1743,7 @@ async function runOpencodeSetup(stored, settings, routingUrl, opts, deps) {
1567
1743
  "Merge LunaRoute provider into opencode.json instead? (backup kept, other providers preserved)",
1568
1744
  { yes: opts.yes }
1569
1745
  );
1570
- return applyOpencodeProvider(creds, routingUrl, write);
1746
+ return applyOpencodeProvider(creds, routingUrl, write, opts.profile);
1571
1747
  } catch (err) {
1572
1748
  if (err instanceof NonInteractiveTerminalError) {
1573
1749
  console.error(
@@ -1579,7 +1755,7 @@ async function runOpencodeSetup(stored, settings, routingUrl, opts, deps) {
1579
1755
  return 1;
1580
1756
  }
1581
1757
  }
1582
- async function applyOpencodeProvider(creds, routingUrl, write) {
1758
+ async function applyOpencodeProvider(creds, routingUrl, write, profile = "default") {
1583
1759
  let models;
1584
1760
  try {
1585
1761
  models = await fetchModels(routingUrl, creds.routing_key);
@@ -1593,7 +1769,7 @@ async function applyOpencodeProvider(creds, routingUrl, write) {
1593
1769
  models,
1594
1770
  keyEnvVar: "LUNAROUTE_API_KEY"
1595
1771
  });
1596
- return applyAndReport(plan, creds.routing_key, write);
1772
+ return applyAndReport(plan, creds.routing_key, write, profile);
1597
1773
  }
1598
1774
  function combinePlans(a, b) {
1599
1775
  if (!b) return a;
@@ -1603,9 +1779,9 @@ function combinePlans(a, b) {
1603
1779
  notes: [...a.notes, ...b.notes]
1604
1780
  };
1605
1781
  }
1606
- async function applyAndReport(plan, key, write) {
1782
+ async function applyAndReport(plan, key2, write, profile = "default") {
1607
1783
  try {
1608
- const summary = await applyPlan(plan, { print: !write, key });
1784
+ const summary = await applyPlan(plan, { print: !write, key: key2, profile });
1609
1785
  if (write && summary.written.length > 0) {
1610
1786
  console.log(`
1611
1787
  Wrote: ${summary.written.join(", ")}`);
@@ -1666,7 +1842,7 @@ async function installPiExtension(deps, opts) {
1666
1842
  { yes: opts.yes }
1667
1843
  );
1668
1844
  if (remove) {
1669
- const ccode = await applyAndReport(buildStaleProviderCleanupPlan(), "", true);
1845
+ const ccode = await applyAndReport(buildStaleProviderCleanupPlan(), "", true, opts.profile);
1670
1846
  if (ccode !== 0) return ccode;
1671
1847
  }
1672
1848
  }
@@ -1691,7 +1867,7 @@ async function launchPi(spawn) {
1691
1867
  });
1692
1868
  });
1693
1869
  }
1694
- async function applyPiModels(creds, routingUrl, write) {
1870
+ async function applyPiModels(creds, routingUrl, write, profile = "default") {
1695
1871
  let models;
1696
1872
  try {
1697
1873
  models = await fetchModels(routingUrl, creds.routing_key);
@@ -1706,7 +1882,7 @@ async function applyPiModels(creds, routingUrl, write) {
1706
1882
  keyEnvVar: "LUNAROUTE_API_KEY"
1707
1883
  });
1708
1884
  try {
1709
- const summary = await applyPlan(plan, { print: !write, key: creds.routing_key });
1885
+ const summary = await applyPlan(plan, { print: !write, key: creds.routing_key, profile });
1710
1886
  if (write && summary.written.length > 0) {
1711
1887
  console.log(`
1712
1888
  Wrote: ${summary.written.join(", ")}`);
@@ -2365,12 +2541,24 @@ if (nodeMajor < MIN_NODE_MAJOR) {
2365
2541
  }
2366
2542
  var program = new Command();
2367
2543
  program.name("lunaroute").description("LunaRoute CLI \u2014 configure coding harnesses and manage your account.").version(version).option("-p, --profile <name>", "credential profile to use", "default");
2368
- program.command("login").description("Authorize this device via the browser and store a routing key.").action(async () => {
2369
- await login(program.opts().profile);
2544
+ program.command("login").description("Authorize this device via the browser and store a routing key.").option("--start", "headless: print an authorization URL and exit (paste the code back with --finish)", false).option("--finish <code>", "headless: exchange the code shown by --start for a routing key").action(async (opts) => {
2545
+ const profile = program.opts().profile;
2546
+ if (opts.finish) {
2547
+ await loginFinish(profile, opts.finish);
2548
+ return;
2549
+ }
2550
+ if (opts.start) {
2551
+ await loginStart(profile);
2552
+ return;
2553
+ }
2554
+ await login(profile);
2370
2555
  });
2371
2556
  program.command("whoami").description("Show the signed-in user and organization.").action(() => {
2372
2557
  whoami(program.opts().profile);
2373
2558
  });
2559
+ program.command("key").description('Print the stored routing key, for shell use (e.g. "$(lunaroute key)").').action(() => {
2560
+ key(program.opts().profile);
2561
+ });
2374
2562
  program.command("logout").description("Remove stored credentials for the active profile.").action(() => {
2375
2563
  logout(program.opts().profile);
2376
2564
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunaroute/cli",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "LunaRoute CLI — configure coding harnesses and manage your LunaRoute account.",
5
5
  "repository": {
6
6
  "type": "git",