@lunaroute/cli 0.11.0 → 0.13.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 +271 -21
  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.11.0";
7
+ var version = "0.13.0";
8
8
 
9
9
  // src/login.ts
10
10
  import { createServer } from "http";
@@ -604,18 +604,77 @@ function renderEnvBlock(exports, opts) {
604
604
  }
605
605
 
606
606
  // src/setup/apply.ts
607
- function readExistingJson(path) {
608
- if (!existsSync3(path)) return null;
607
+ function readExistingJson(path, jsonc = false) {
608
+ if (!existsSync3(path)) return { value: null, droppedComments: false };
609
609
  const raw = readFileSync3(path, "utf8").trim();
610
- if (raw === "") return null;
610
+ if (raw === "") return { value: null, droppedComments: false };
611
+ const scanned = jsonc ? stripJsonc(raw) : { text: raw, hadComments: false };
611
612
  try {
612
- return JSON.parse(raw);
613
+ return { value: JSON.parse(scanned.text), droppedComments: scanned.hadComments };
613
614
  } catch {
614
615
  throw new Error(
615
- `refusing to modify ${path}: it exists but is not valid JSON (malformed). Fix or remove it, or re-run with --print to copy the config manually.`
616
+ `refusing to modify ${path}: it exists but is not valid JSON (malformed). Fix or remove it and re-run.`
616
617
  );
617
618
  }
618
619
  }
620
+ function stripJsonc(raw) {
621
+ let text = "";
622
+ let hadComments = false;
623
+ let i = 0;
624
+ while (i < raw.length) {
625
+ const c = raw[i];
626
+ if (c === '"') {
627
+ text += c;
628
+ i++;
629
+ while (i < raw.length) {
630
+ const s = raw[i];
631
+ text += s;
632
+ i++;
633
+ if (s === "\\") {
634
+ text += raw[i] ?? "";
635
+ i++;
636
+ } else if (s === '"') break;
637
+ }
638
+ continue;
639
+ }
640
+ if (c === "/" && raw[i + 1] === "/") {
641
+ hadComments = true;
642
+ while (i < raw.length && raw[i] !== "\n") i++;
643
+ continue;
644
+ }
645
+ if (c === "/" && raw[i + 1] === "*") {
646
+ hadComments = true;
647
+ i += 2;
648
+ while (i < raw.length && !(raw[i] === "*" && raw[i + 1] === "/")) i++;
649
+ i += 2;
650
+ continue;
651
+ }
652
+ if (c === ",") {
653
+ let j = i + 1;
654
+ for (; ; ) {
655
+ while (j < raw.length && /\s/.test(raw[j])) j++;
656
+ if (raw[j] === "/" && raw[j + 1] === "/") {
657
+ while (j < raw.length && raw[j] !== "\n") j++;
658
+ continue;
659
+ }
660
+ if (raw[j] === "/" && raw[j + 1] === "*") {
661
+ j += 2;
662
+ while (j < raw.length && !(raw[j] === "*" && raw[j + 1] === "/")) j++;
663
+ j += 2;
664
+ continue;
665
+ }
666
+ break;
667
+ }
668
+ if (raw[j] === "}" || raw[j] === "]") {
669
+ i++;
670
+ continue;
671
+ }
672
+ }
673
+ text += c;
674
+ i++;
675
+ }
676
+ return { text, hadComments };
677
+ }
619
678
  function resolveYamlContent(fw) {
620
679
  const curStr = existsSync3(fw.path) ? readFileSync3(fw.path, "utf8") : null;
621
680
  const doc = parseDocument(curStr ?? "", { logLevel: "silent" });
@@ -634,20 +693,25 @@ function resolveYamlContent(fw) {
634
693
  function resolveContent(fw) {
635
694
  if (fw.kind === "text") {
636
695
  const curStr2 = existsSync3(fw.path) ? readFileSync3(fw.path, "utf8") : null;
637
- return { nextStr: fw.content, curStr: curStr2 };
696
+ return { nextStr: fw.content, curStr: curStr2, droppedComments: false };
638
697
  }
639
- if (fw.kind === "yaml") return resolveYamlContent(fw);
640
- const existing = readExistingJson(fw.path);
698
+ if (fw.kind === "yaml") return { ...resolveYamlContent(fw), droppedComments: false };
699
+ const { value: existing, droppedComments } = readExistingJson(fw.path, fw.jsonc);
641
700
  const curStr = existing === null ? null : `${JSON.stringify(existing, null, 2)}
642
701
  `;
643
702
  const nextStr = `${JSON.stringify(fw.merge(existing), null, 2)}
644
703
  `;
645
- return { nextStr, curStr };
704
+ return { nextStr, curStr, droppedComments };
646
705
  }
647
706
  async function applyPlan(plan, opts) {
648
707
  const summary = { written: [], backedUp: [] };
649
708
  for (const fw of plan.fileWrites) {
650
- const { nextStr, curStr } = resolveContent(fw);
709
+ const { nextStr, curStr, droppedComments } = resolveContent(fw);
710
+ if (droppedComments) {
711
+ console.log(
712
+ opts.print ? `# ${fw.path}: the merged settings are plain JSON \u2014 comments are dropped` : `# ${fw.path}: comments are dropped by the rewrite${fw.backup !== false ? `; the original is kept at ${fw.path}.bak` : ""}`
713
+ );
714
+ }
651
715
  if (opts.print) {
652
716
  console.log(`
653
717
  # would write ${fw.path}:
@@ -807,7 +871,7 @@ function describeSpawnError(command, installHint, err) {
807
871
 
808
872
  // src/setup/paths.ts
809
873
  import { execSync } from "child_process";
810
- import { lstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
874
+ import { existsSync as existsSync4, lstatSync, readFileSync as readFileSync4, realpathSync } from "fs";
811
875
  import { homedir as homedir2 } from "os";
812
876
  import { dirname as dirname2, join as join3 } from "path";
813
877
  function configHome() {
@@ -842,6 +906,17 @@ function dshProfilePatchPath(profile = "web") {
842
906
  function dshHomePatchPath() {
843
907
  return join3(dshHome(), "cordis.patch.yml");
844
908
  }
909
+ function zedSettingsPath(platform = process.platform) {
910
+ if (platform === "win32") {
911
+ const appData = process.env.APPDATA || join3(homedir2(), "AppData", "Roaming");
912
+ return join3(appData, "Zed", "settings.json");
913
+ }
914
+ if (platform === "darwin") {
915
+ return join3(homedir2(), ".config", "zed", "settings.json");
916
+ }
917
+ const flatpak = join3(homedir2(), ".var", "app", "dev.zed.Zed", "config", "zed");
918
+ return existsSync4(flatpak) ? join3(flatpak, "settings.json") : join3(configHome(), "zed", "settings.json");
919
+ }
845
920
  var LUNAROUTE_SKILL_NAME = "lunaroute-memory";
846
921
  function claudeUserConfigPath() {
847
922
  return join3(homedir2(), ".claude.json");
@@ -922,6 +997,8 @@ function extensionPlan(ctx) {
922
997
  {
923
998
  kind: "json",
924
999
  path: opencodeConfigPath(),
1000
+ jsonc: true,
1001
+ // opencode documents JSONC config
925
1002
  merge: (existing) => {
926
1003
  const obj = existing ?? {};
927
1004
  const raw = obj.plugin;
@@ -977,6 +1054,8 @@ function providerPlan(ctx) {
977
1054
  {
978
1055
  kind: "json",
979
1056
  path: opencodeConfigPath(),
1057
+ jsonc: true,
1058
+ // opencode documents JSONC config
980
1059
  merge: (existing) => {
981
1060
  const obj = existing ?? {};
982
1061
  const existingProviders = objectOrEmpty(obj.provider);
@@ -1434,6 +1513,11 @@ function buildPlan8(ctx) {
1434
1513
  {
1435
1514
  kind: "json",
1436
1515
  path: openclawConfigPath(),
1516
+ // OpenClaw's config is JSON5 ("comments + trailing commas allowed"), so
1517
+ // a hand-edited file is read tolerantly.
1518
+ // shortcut: the JSON subset of JSON5 only — unquoted keys and single
1519
+ // quotes still refuse; widen it if a real openclaw.json needs it (kata tnhh).
1520
+ jsonc: true,
1437
1521
  merge: (existing) => {
1438
1522
  const obj = asRecord(existing);
1439
1523
  const modelsCfg = asRecord(obj.models);
@@ -1483,7 +1567,7 @@ openclaw: restart the gateway, then \`openclaw models list\` and \`openclaw mode
1483
1567
  }
1484
1568
 
1485
1569
  // src/setup/adapters/dsh.ts
1486
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
1570
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
1487
1571
  import { isMap, isSeq, parseDocument as parseDocument2 } from "yaml";
1488
1572
  var PI_AI_ROW_ID = "llm-pi-ai";
1489
1573
  var ROUTE_KEY = "lunaroute";
@@ -1575,7 +1659,7 @@ function mergeProvider(doc, provider) {
1575
1659
  }
1576
1660
  function homePatchOverridesPiAi() {
1577
1661
  const path = dshHomePatchPath();
1578
- if (!existsSync4(path)) return false;
1662
+ if (!existsSync5(path)) return false;
1579
1663
  try {
1580
1664
  const doc = parseDocument2(readFileSync6(path, "utf8"), { logLevel: "silent" });
1581
1665
  if (!isSeq(doc.contents)) return false;
@@ -1632,6 +1716,81 @@ function buildPlan9(ctx) {
1632
1716
  };
1633
1717
  }
1634
1718
 
1719
+ // src/setup/adapters/zed.ts
1720
+ var PROVIDER_ID = "lunaroute";
1721
+ function buildZedModelEntry(m) {
1722
+ if (!m.context_window_tokens || !m.max_output_tokens) return null;
1723
+ return {
1724
+ name: m.id,
1725
+ display_name: m.display_name ?? m.id,
1726
+ // /v1/models emits none today
1727
+ max_tokens: m.context_window_tokens,
1728
+ max_output_tokens: m.max_output_tokens,
1729
+ capabilities: {
1730
+ tools: m.capabilities?.tools ?? true,
1731
+ images: m.capabilities?.vision === true,
1732
+ parallel_tool_calls: false,
1733
+ prompt_cache_key: false,
1734
+ chat_completions: true,
1735
+ interleaved_reasoning: false,
1736
+ max_tokens_parameter: false
1737
+ }
1738
+ };
1739
+ }
1740
+ function objectOrEmpty2(v) {
1741
+ return typeof v === "object" && v !== null ? v : {};
1742
+ }
1743
+ function buildPlan10(ctx) {
1744
+ const skipped = [];
1745
+ const models = [];
1746
+ for (const m of ctx.models) {
1747
+ const entry = buildZedModelEntry(m);
1748
+ if (entry) models.push(entry);
1749
+ else skipped.push(m.id);
1750
+ }
1751
+ if (models.length === 0) {
1752
+ throw new Error(
1753
+ `no LunaRoute model has a context window in the catalog${skipped.length ? ` (skipped: ${skipped.join(", ")})` : ""}`
1754
+ );
1755
+ }
1756
+ const block = {
1757
+ api_url: `${ctx.routingUrl}/v1`,
1758
+ available_models: models
1759
+ };
1760
+ const notes = [
1761
+ "\nzed: restart Zed, then pick a LunaRoute model in the agent panel.",
1762
+ 'zed: to paste the key in Zed, run "agent: open settings" and open LLM Providers \u2192 LunaRoute \u2192 paste. Print the key with "lunaroute key" (or create one in the dashboard if you have none); Zed stores it in the OS keychain.',
1763
+ `zed: or set ${ctx.keyEnvVar} (the block above), which Zed reads at launch and which takes precedence over the keychain; or launch with "lunaroute run zed" to inject it for one session \u2014 quit a running Zed first.`
1764
+ ];
1765
+ if (skipped.length > 0) {
1766
+ notes.push(`Skipped (no context window or output limit in the catalog): ${skipped.join(", ")}`);
1767
+ }
1768
+ return {
1769
+ fileWrites: [
1770
+ {
1771
+ kind: "json",
1772
+ path: zedSettingsPath(),
1773
+ // Zed ships settings.json as JSONC (its template header is comments).
1774
+ jsonc: true,
1775
+ merge: (existing) => {
1776
+ const obj = objectOrEmpty2(existing);
1777
+ const languageModels = objectOrEmpty2(obj.language_models);
1778
+ const openaiCompatible = objectOrEmpty2(languageModels.openai_compatible);
1779
+ return {
1780
+ ...obj,
1781
+ language_models: {
1782
+ ...languageModels,
1783
+ openai_compatible: { ...openaiCompatible, [PROVIDER_ID]: block }
1784
+ }
1785
+ };
1786
+ }
1787
+ }
1788
+ ],
1789
+ exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
1790
+ notes
1791
+ };
1792
+ }
1793
+
1635
1794
  // src/setup/snapshot.ts
1636
1795
  import {
1637
1796
  chmodSync as chmodSync4,
@@ -1826,6 +1985,7 @@ var ADAPTERS = {
1826
1985
  pi: buildPlan2,
1827
1986
  openclaw: buildPlan8,
1828
1987
  dsh: buildPlan9,
1988
+ zed: buildPlan10,
1829
1989
  "claude-code": buildPlan3,
1830
1990
  "claude-desktop": buildPlan4,
1831
1991
  codex: buildPlan5,
@@ -3078,17 +3238,102 @@ function buildRunSpec2(ctx) {
3078
3238
  };
3079
3239
  }
3080
3240
 
3241
+ // src/run/adapters/zed.ts
3242
+ import { accessSync, constants as constants2, existsSync as existsSync6, readFileSync as readFileSync8, realpathSync as realpathSync2 } from "fs";
3243
+ import { homedir as homedir3 } from "os";
3244
+ import { basename as basename2, dirname as dirname4, join as join5 } from "path";
3245
+ function which(cmd, env, platform) {
3246
+ const pathVar = env.PATH ?? env.Path ?? "";
3247
+ const exts = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
3248
+ const alreadyHasExt = cmd.includes(".");
3249
+ for (const dir of pathVar.split(platform === "win32" ? ";" : ":")) {
3250
+ if (!dir) continue;
3251
+ for (const ext of alreadyHasExt ? [""] : exts) {
3252
+ const candidate = join5(dir, cmd + ext);
3253
+ try {
3254
+ accessSync(candidate, platform === "win32" ? constants2.F_OK : constants2.X_OK);
3255
+ return candidate;
3256
+ } catch {
3257
+ }
3258
+ }
3259
+ }
3260
+ return null;
3261
+ }
3262
+ function firstExisting(paths) {
3263
+ for (const path of paths) if (existsSync6(path)) return path;
3264
+ return null;
3265
+ }
3266
+ function resolveZedCommand(deps = {}) {
3267
+ const platform = deps.platform ?? process.platform;
3268
+ const env = deps.env ?? process.env;
3269
+ const home = env.HOME || env.USERPROFILE || homedir3();
3270
+ if (platform === "darwin") {
3271
+ const shim = which("zed", env, platform);
3272
+ if (shim) {
3273
+ try {
3274
+ const real = realpathSync2(shim);
3275
+ if (basename2(real) === "cli") {
3276
+ const app = join5(dirname4(real), "zed");
3277
+ if (existsSync6(app)) return app;
3278
+ }
3279
+ return real;
3280
+ } catch {
3281
+ return shim;
3282
+ }
3283
+ }
3284
+ return firstExisting([
3285
+ "/Applications/Zed.app/Contents/MacOS/zed",
3286
+ join5(home, "Applications", "Zed.app", "Contents", "MacOS", "zed"),
3287
+ "/Applications/Zed Preview.app/Contents/MacOS/zed",
3288
+ join5(home, "Applications", "Zed Preview.app", "Contents", "MacOS", "zed"),
3289
+ "/Applications/Zed Nightly.app/Contents/MacOS/zed"
3290
+ ]);
3291
+ }
3292
+ if (platform === "win32") {
3293
+ const onPath = which("zed", env, platform);
3294
+ if (onPath) return onPath;
3295
+ return env.LOCALAPPDATA ? firstExisting([join5(env.LOCALAPPDATA, "Programs", "Zed", "zed.exe")]) : null;
3296
+ }
3297
+ return which("zed", env, platform) ?? which("zed-x11", env, platform) ?? firstExisting([
3298
+ join5(home, ".local", "bin", "zed"),
3299
+ join5(home, ".local", "zed.app", "bin", "zed")
3300
+ ]);
3301
+ }
3302
+ function hasLunarouteProvider(settingsPath) {
3303
+ try {
3304
+ const parsed = JSON.parse(readFileSync8(settingsPath, "utf8"));
3305
+ return Boolean(parsed.language_models?.openai_compatible?.lunaroute);
3306
+ } catch {
3307
+ return false;
3308
+ }
3309
+ }
3310
+ function buildRunSpec3(ctx, deps = {}) {
3311
+ const settingsPath = deps.settingsPath ?? zedSettingsPath(deps.platform ?? process.platform);
3312
+ return {
3313
+ command: resolveZedCommand(deps) ?? "zed",
3314
+ args: [],
3315
+ // Read by Zed at launch; a non-empty env var takes precedence over the
3316
+ // keychain, so this overrides a previously pasted key for this process.
3317
+ env: { LUNAROUTE_API_KEY: ctx.apiKey },
3318
+ ...hasLunarouteProvider(settingsPath) ? {} : {
3319
+ notice: `zed: no "lunaroute" provider in ${settingsPath} \u2014 run "lunaroute setup zed" first. This launch injects only LUNAROUTE_API_KEY.`
3320
+ }
3321
+ };
3322
+ }
3323
+
3081
3324
  // src/commands/run.ts
3082
3325
  var ADAPTERS2 = {
3083
3326
  claude: buildRunSpec,
3084
3327
  "claude-code": buildRunSpec,
3085
- codex: buildRunSpec2
3328
+ codex: buildRunSpec2,
3329
+ zed: buildRunSpec3
3086
3330
  };
3087
3331
  var MODEL_LOOKUP_TIMEOUT_MS = 3e3;
3088
3332
  var INSTALL_HINT = {
3089
3333
  claude: "Install Claude Code: https://docs.anthropic.com/claude-code/install",
3090
3334
  "claude-code": "Install Claude Code: https://docs.anthropic.com/claude-code/install",
3091
- codex: "Install Codex: https://github.com/openai/codex#install"
3335
+ codex: "Install Codex: https://github.com/openai/codex#install",
3336
+ zed: "Install Zed: https://zed.dev/download (Windows: winget install -e --id ZedIndustries.Zed)"
3092
3337
  };
3093
3338
  var realDeps = {
3094
3339
  spawn: makeRealSpawn(),
@@ -3105,9 +3350,13 @@ async function runRun(harness, opts, deps = realDeps) {
3105
3350
  console.error('Not logged in. Run "lunaroute login" first.');
3106
3351
  return 1;
3107
3352
  }
3108
- let model = opts.model;
3353
+ const usesModel = harness !== "zed";
3354
+ if (!usesModel && opts.model) {
3355
+ console.error("# note: Zed picks its model in the agent panel \u2014 --model is ignored.");
3356
+ }
3357
+ let model = opts.model ?? "";
3109
3358
  let models = [];
3110
- if (!model) {
3359
+ if (usesModel && !model) {
3111
3360
  try {
3112
3361
  models = await deps.fetchModels(creds.routing_url, creds.routing_key);
3113
3362
  } catch (err) {
@@ -3120,7 +3369,7 @@ async function runRun(harness, opts, deps = realDeps) {
3120
3369
  return 1;
3121
3370
  }
3122
3371
  console.error(`# using model ${model} (pass --model to change)`);
3123
- } else if (harness === "codex") {
3372
+ } else if (usesModel && harness === "codex") {
3124
3373
  try {
3125
3374
  models = await deps.fetchModels(creds.routing_url, creds.routing_key, {
3126
3375
  signal: AbortSignal.timeout(MODEL_LOOKUP_TIMEOUT_MS)
@@ -3136,6 +3385,7 @@ async function runRun(harness, opts, deps = realDeps) {
3136
3385
  model,
3137
3386
  contextWindow
3138
3387
  });
3388
+ if (spec.notice) console.error(spec.notice);
3139
3389
  const args = spec.args.concat(opts.passthrough ?? []);
3140
3390
  const env = { ...process.env, ...spec.env };
3141
3391
  const child = deps.spawn(spec.command, args, env);
@@ -3183,7 +3433,7 @@ program.command("key").description('Print the stored routing key, for shell use
3183
3433
  program.command("logout").description("Remove stored credentials for the active profile.").action(() => {
3184
3434
  logout(program.opts().profile);
3185
3435
  });
3186
- program.command("setup <harness>").description("Configure a coding harness (opencode | pi | hermes | claude-code | claude-desktop | codex | copilot-cli | openclaw | dsh | generic).").option("--print", "print the config instead of writing files", false).option("--routing-url <url>", "override the routing base URL").option("--yes", "accept all confirmation prompts without a TTY (for scripts)", false).option("--extension", "pi only: jump straight to installing the Pi extension").option("--models", "pi only: jump straight to writing the models.json provider block").option("--remove", "claude-desktop: restore the profile from the snapshot taken at setup (writes nothing when no snapshot exists)").option("--key <key>", "a LunaRoute routing key (lr_\u2026), e.g. from the dashboard's onboarding page \u2014 stores it and skips the browser login").action(async (harness, opts) => {
3436
+ program.command("setup <harness>").description("Configure a coding harness (opencode | pi | hermes | claude-code | claude-desktop | codex | copilot-cli | openclaw | dsh | zed | 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) => {
3187
3437
  const code = await runSetup(harness, {
3188
3438
  profile: program.opts().profile,
3189
3439
  print: opts.print,
@@ -3196,7 +3446,7 @@ program.command("setup <harness>").description("Configure a coding harness (open
3196
3446
  });
3197
3447
  if (code !== 0) process.exit(code);
3198
3448
  });
3199
- program.command("run <harness>").description("Launch a coding harness (claude | claude-code | codex) configured to use LunaRoute for this session.").option("--model <id>", "model id to launch on (default: first model in the catalog)").argument("[extra...]").action(async (harness, extra, opts) => {
3449
+ program.command("run <harness>").description("Launch a coding harness (claude | claude-code | codex | zed) configured to use LunaRoute for this session.").option("--model <id>", "model id to launch on (default: first model in the catalog)").argument("[extra...]").action(async (harness, extra, opts) => {
3200
3450
  const sep = process.argv.indexOf("--");
3201
3451
  const post = sep !== -1 ? process.argv.slice(sep + 1) : [];
3202
3452
  const before = post.length <= extra.length ? extra.slice(0, extra.length - post.length) : extra;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunaroute/cli",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "LunaRoute CLI — configure coding harnesses and manage your LunaRoute account.",
5
5
  "repository": {
6
6
  "type": "git",