@lunaroute/cli 0.3.0 → 0.4.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 +192 -22
  2. package/package.json +2 -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.3.0";
7
+ var version = "0.4.0";
8
8
 
9
9
  // src/login.ts
10
10
  import { createServer } from "http";
@@ -372,10 +372,10 @@ function isChatModel(m) {
372
372
  }
373
373
  return true;
374
374
  }
375
- async function fetchModels(routingUrl, key) {
375
+ async function fetchModels(routingUrl, key, opts) {
376
376
  const url = `${routingUrl}/v1/models`;
377
377
  const headers = key ? { Authorization: `Bearer ${key}` } : {};
378
- const res = await fetch(url, { method: "GET", headers });
378
+ const res = await fetch(url, { method: "GET", headers, signal: opts?.signal });
379
379
  if (!res.ok) {
380
380
  if (res.status === 401) {
381
381
  throw new KeyRejectedError(
@@ -409,6 +409,7 @@ import {
409
409
  chmodSync as chmodSync2
410
410
  } from "fs";
411
411
  import { dirname } from "path";
412
+ import { parseDocument } from "yaml";
412
413
  function readExistingJson(path) {
413
414
  if (!existsSync2(path)) return null;
414
415
  const raw = readFileSync2(path, "utf8").trim();
@@ -421,11 +422,27 @@ function readExistingJson(path) {
421
422
  );
422
423
  }
423
424
  }
425
+ function resolveYamlContent(fw) {
426
+ const curStr = existsSync2(fw.path) ? readFileSync2(fw.path, "utf8") : null;
427
+ const doc = parseDocument(curStr ?? "", { logLevel: "silent" });
428
+ if (doc.errors.length > 0) {
429
+ const first = doc.errors[0];
430
+ const detail = first ? first.message.split("\n")[0] : "parse error";
431
+ throw new Error(
432
+ `refusing to modify ${fw.path}: it exists but is not valid YAML (${detail}). Fix or remove it, or re-run with --print to copy the config manually.`
433
+ );
434
+ }
435
+ fw.merge(doc);
436
+ let nextStr = String(doc);
437
+ if (!nextStr.endsWith("\n")) nextStr += "\n";
438
+ return { nextStr, curStr };
439
+ }
424
440
  function resolveContent(fw) {
425
441
  if (fw.kind === "text") {
426
442
  const curStr2 = existsSync2(fw.path) ? readFileSync2(fw.path, "utf8") : null;
427
443
  return { nextStr: fw.content, curStr: curStr2 };
428
444
  }
445
+ if (fw.kind === "yaml") return resolveYamlContent(fw);
429
446
  const existing = readExistingJson(fw.path);
430
447
  const curStr = existing === null ? null : `${JSON.stringify(existing, null, 2)}
431
448
  `;
@@ -608,6 +625,15 @@ function piModelsPath() {
608
625
  function piAuthPath() {
609
626
  return join2(homedir2(), ".pi", "agent", "auth.json");
610
627
  }
628
+ function dshHome() {
629
+ return process.env.DSH_HOME || join2(homedir2(), ".dsh");
630
+ }
631
+ function dshProfilePatchPath(profile = "web") {
632
+ return join2(dshHome(), "profiles", profile, "cordis.patch.yml");
633
+ }
634
+ function dshHomePatchPath() {
635
+ return join2(dshHome(), "cordis.patch.yml");
636
+ }
611
637
  var LUNAROUTE_SKILL_NAME = "lunaroute-memory";
612
638
  function claudeUserConfigPath() {
613
639
  return join2(homedir2(), ".claude.json");
@@ -749,15 +775,18 @@ function buildPiModelEntry(m) {
749
775
  contextWindow: m.context_window_tokens,
750
776
  maxTokens: m.max_output_tokens
751
777
  };
752
- if (!reasoning) return entry;
753
778
  const pi = m.client_compat?.pi;
779
+ if (m.capabilities?.vision && pi?.inputLimits !== void 0) {
780
+ entry.inputLimits = pi.inputLimits;
781
+ }
782
+ if (!reasoning) return entry;
754
783
  if (!pi) return entry;
755
784
  if (pi.thinkingLevelMap && typeof pi.thinkingLevelMap === "object") {
756
785
  entry.thinkingLevelMap = pi.thinkingLevelMap;
757
786
  }
758
787
  const compat = {};
759
788
  for (const [k, v] of Object.entries(pi)) {
760
- if (k !== "thinkingLevelMap") compat[k] = v;
789
+ if (k !== "thinkingLevelMap" && k !== "inputLimits") compat[k] = v;
761
790
  }
762
791
  if (Object.keys(compat).length > 0) entry.compat = compat;
763
792
  return entry;
@@ -916,24 +945,28 @@ function validatedRoutingUrl(routingUrl) {
916
945
  function buildPlan4(ctx) {
917
946
  const base = validatedRoutingUrl(ctx.routingUrl);
918
947
  const model = ctx.models[0]?.id ?? "<model>";
919
- const content = [
920
- `model = "${model}"`,
921
- 'model_provider = "lunaroute"',
948
+ const contextWindow = ctx.models[0]?.context_window_tokens;
949
+ const lines = [`model = "${model}"`, 'model_provider = "lunaroute"'];
950
+ if (Number.isInteger(contextWindow) && (contextWindow ?? 0) > 0) {
951
+ lines.push(`model_context_window = ${contextWindow}`);
952
+ }
953
+ const content = lines.concat([
922
954
  "",
923
955
  "[model_providers.lunaroute]",
924
956
  'name = "LunaRoute"',
925
957
  `base_url = "${base}/v1"`,
926
958
  'env_key = "LUNAROUTE_API_KEY"',
927
959
  'wire_api = "responses"'
928
- ].join("\n") + "\n";
960
+ ]).join("\n") + "\n";
929
961
  return {
930
962
  fileWrites: [{ kind: "text", path: codexProfilePath(), content }],
931
963
  exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
932
964
  notes: [
933
965
  "\nCodex: add the export above to your shell profile, then start Codex with `codex --profile lunaroute`.",
934
- `Change model to any of: ${ctx.models.map((m) => m.id).join(", ")}, or pass \`--model <id>\` for one session.`,
966
+ `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.`,
935
967
  "The key rides the Authorization: Bearer header via env_key; LunaRoute authenticates the lr_ key at the edge and never forwards it upstream.",
936
- "One file: the model and the named provider live in the profile file \u2014 your ~/.codex/config.toml is untouched."
968
+ "One file: the model and the named provider live in the profile file \u2014 your ~/.codex/config.toml is untouched.",
969
+ "Codex logs a `Model metadata ... fallback metadata` warning for LunaRoute models (its /v1/models catalog shape differs); it is expected and harmless \u2014 model_context_window pins the real window above."
937
970
  ]
938
971
  };
939
972
  }
@@ -1040,11 +1073,133 @@ openclaw: restart the gateway, then \`openclaw models list\` and \`openclaw mode
1040
1073
  };
1041
1074
  }
1042
1075
 
1076
+ // src/setup/adapters/dsh.ts
1077
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
1078
+ import { isMap, isSeq, parseDocument as parseDocument2 } from "yaml";
1079
+ var PI_AI_ROW_ID = "llm-pi-ai";
1080
+ var ROUTE_KEY = "lunaroute";
1081
+ function asRecord2(v) {
1082
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
1083
+ }
1084
+ function buildReasoning(m) {
1085
+ if (m.capabilities?.reasoning !== true) return null;
1086
+ const pi = asRecord2(m.client_compat?.pi);
1087
+ const levelMap = asRecord2(pi.thinkingLevelMap);
1088
+ const efforts = {
1089
+ off: typeof levelMap.off === "string" ? levelMap.off : null
1090
+ };
1091
+ for (const [level, wire] of Object.entries(levelMap)) {
1092
+ if (level === "off") continue;
1093
+ if (typeof wire === "string") efforts[level] = wire;
1094
+ }
1095
+ if (Object.keys(efforts).length < 2) return null;
1096
+ const compat = {};
1097
+ if (typeof pi.thinkingFormat === "string") compat.thinkingFormat = pi.thinkingFormat;
1098
+ if (typeof pi.maxTokensField === "string") compat.maxTokensField = pi.maxTokensField;
1099
+ if (typeof pi.supportsReasoningEffort === "boolean") {
1100
+ compat.supportsReasoningEffort = pi.supportsReasoningEffort;
1101
+ }
1102
+ return Object.keys(compat).length > 0 ? { reasoningEfforts: efforts, compat } : { reasoningEfforts: efforts };
1103
+ }
1104
+ function buildModel(m) {
1105
+ const entry = { id: m.id, name: m.display_name || m.id };
1106
+ if (Number.isInteger(m.context_window_tokens) && (m.context_window_tokens ?? 0) > 0) {
1107
+ entry.contextWindow = m.context_window_tokens;
1108
+ }
1109
+ if (Number.isInteger(m.max_output_tokens) && (m.max_output_tokens ?? 0) > 0) {
1110
+ entry.maxTokens = m.max_output_tokens;
1111
+ }
1112
+ entry.input = m.capabilities?.vision === true ? ["text", "image"] : ["text"];
1113
+ const reasoning = buildReasoning(m);
1114
+ if (reasoning) {
1115
+ entry.reasoningEfforts = reasoning.reasoningEfforts;
1116
+ if (reasoning.compat) entry.compat = reasoning.compat;
1117
+ }
1118
+ return entry;
1119
+ }
1120
+ function ensureProviderRow(doc) {
1121
+ let seq;
1122
+ if (isSeq(doc.contents)) {
1123
+ seq = doc.contents;
1124
+ } else {
1125
+ seq = doc.createNode([]);
1126
+ doc.contents = seq;
1127
+ }
1128
+ for (const item of seq.items) {
1129
+ if (isMap(item) && item.get("id") === PI_AI_ROW_ID) return item;
1130
+ }
1131
+ const row = doc.createNode({ id: PI_AI_ROW_ID, config: { providers: {} } });
1132
+ seq.add(row);
1133
+ return row;
1134
+ }
1135
+ function ensureMap(doc, parent, key) {
1136
+ const existing = parent.get(key);
1137
+ if (isMap(existing)) return existing;
1138
+ const created = doc.createNode({});
1139
+ parent.set(key, created);
1140
+ return created;
1141
+ }
1142
+ function mergeProvider(doc, provider) {
1143
+ const row = ensureProviderRow(doc);
1144
+ const config = ensureMap(doc, row, "config");
1145
+ const providers = ensureMap(doc, config, "providers");
1146
+ providers.set(ROUTE_KEY, doc.createNode(provider));
1147
+ }
1148
+ function homePatchOverridesPiAi() {
1149
+ const path = dshHomePatchPath();
1150
+ if (!existsSync3(path)) return false;
1151
+ try {
1152
+ const doc = parseDocument2(readFileSync4(path, "utf8"), { logLevel: "silent" });
1153
+ if (!isSeq(doc.contents)) return false;
1154
+ return doc.contents.items.some(
1155
+ (item) => isMap(item) && item.get("id") === PI_AI_ROW_ID
1156
+ );
1157
+ } catch {
1158
+ return false;
1159
+ }
1160
+ }
1161
+ function buildPlan8(ctx) {
1162
+ const base = validatedRoutingUrl(ctx.routingUrl);
1163
+ if (ctx.models.length === 0) {
1164
+ throw new Error("no LunaRoute chat models in the catalog \u2014 nothing to configure for dsh");
1165
+ }
1166
+ const provider = {
1167
+ displayName: "LunaRoute",
1168
+ apiKeyEnv: ctx.keyEnvVar,
1169
+ api: "openai-completions",
1170
+ baseURL: `${base}/v1`,
1171
+ models: ctx.models.map(buildModel)
1172
+ };
1173
+ const notes = [
1174
+ "\ndsh: start `dsh web` (or plain `dsh`), then pick a `lunaroute/*` model in the model picker (Settings \u2192 Models).",
1175
+ "The profile patch hot-reloads, so a running `dsh web` picks it up without a restart.",
1176
+ "The key rides `Authorization: Bearer lr_\u2026` via apiKeyEnv; LunaRoute authenticates it at the edge and never forwards it upstream.",
1177
+ "Or paste the key in Settings \u2192 Models instead \u2014 dsh stores it in $DSH_HOME/.credentials.yaml."
1178
+ ];
1179
+ if (homePatchOverridesPiAi()) {
1180
+ notes.push(
1181
+ `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.`
1182
+ );
1183
+ }
1184
+ return {
1185
+ fileWrites: [
1186
+ {
1187
+ kind: "yaml",
1188
+ path: dshProfilePatchPath(),
1189
+ merge: (doc) => mergeProvider(doc, provider)
1190
+ }
1191
+ ],
1192
+ exports: [{ name: ctx.keyEnvVar, value: "__KEY__" }],
1193
+ notes
1194
+ };
1195
+ }
1196
+
1043
1197
  // src/commands/setup.ts
1044
1198
  var ADAPTERS = {
1045
1199
  opencode: buildPlan,
1046
1200
  pi: buildPlan2,
1047
1201
  openclaw: buildPlan7,
1202
+ dsh: buildPlan8,
1048
1203
  "claude-code": buildPlan3,
1049
1204
  codex: buildPlan4,
1050
1205
  "copilot-cli": buildPlan5,
@@ -2106,16 +2261,20 @@ function buildRunSpec(ctx) {
2106
2261
  // src/run/adapters/codex.ts
2107
2262
  function buildRunSpec2(ctx) {
2108
2263
  const provider = `{name="LunaRoute",base_url="${ctx.routingUrl}/v1",env_key="LUNAROUTE_API_KEY",wire_api="responses"}`;
2264
+ const args = [
2265
+ "-c",
2266
+ 'model_provider="lunaroute"',
2267
+ "-c",
2268
+ `model_providers.lunaroute=${provider}`,
2269
+ "-c",
2270
+ `model="${ctx.model}"`
2271
+ ];
2272
+ if (Number.isInteger(ctx.contextWindow) && (ctx.contextWindow ?? 0) > 0) {
2273
+ args.push("-c", `model_context_window=${ctx.contextWindow}`);
2274
+ }
2109
2275
  return {
2110
2276
  command: "codex",
2111
- args: [
2112
- "-c",
2113
- 'model_provider="lunaroute"',
2114
- "-c",
2115
- `model_providers.lunaroute=${provider}`,
2116
- "-c",
2117
- `model="${ctx.model}"`
2118
- ],
2277
+ args,
2119
2278
  env: {
2120
2279
  LUNAROUTE_API_KEY: ctx.apiKey
2121
2280
  }
@@ -2128,6 +2287,7 @@ var ADAPTERS2 = {
2128
2287
  "claude-code": buildRunSpec,
2129
2288
  codex: buildRunSpec2
2130
2289
  };
2290
+ var MODEL_LOOKUP_TIMEOUT_MS = 3e3;
2131
2291
  var INSTALL_HINT = {
2132
2292
  claude: "Install Claude Code: https://docs.anthropic.com/claude-code/install",
2133
2293
  "claude-code": "Install Claude Code: https://docs.anthropic.com/claude-code/install",
@@ -2149,8 +2309,8 @@ async function runRun(harness, opts, deps = realDeps) {
2149
2309
  return 1;
2150
2310
  }
2151
2311
  let model = opts.model;
2312
+ let models = [];
2152
2313
  if (!model) {
2153
- let models;
2154
2314
  try {
2155
2315
  models = await deps.fetchModels(creds.routing_url, creds.routing_key);
2156
2316
  } catch (err) {
@@ -2163,11 +2323,21 @@ async function runRun(harness, opts, deps = realDeps) {
2163
2323
  return 1;
2164
2324
  }
2165
2325
  console.error(`# using model ${model} (pass --model to change)`);
2326
+ } else if (harness === "codex") {
2327
+ try {
2328
+ models = await deps.fetchModels(creds.routing_url, creds.routing_key, {
2329
+ signal: AbortSignal.timeout(MODEL_LOOKUP_TIMEOUT_MS)
2330
+ });
2331
+ } catch {
2332
+ models = [];
2333
+ }
2166
2334
  }
2335
+ const contextWindow = models.find((m) => m.id === model)?.context_window_tokens;
2167
2336
  const spec = adapter({
2168
2337
  routingUrl: creds.routing_url,
2169
2338
  apiKey: creds.routing_key,
2170
- model
2339
+ model,
2340
+ contextWindow
2171
2341
  });
2172
2342
  const args = spec.args.concat(opts.passthrough ?? []);
2173
2343
  const env = { ...process.env, ...spec.env };
@@ -2204,7 +2374,7 @@ program.command("whoami").description("Show the signed-in user and organization.
2204
2374
  program.command("logout").description("Remove stored credentials for the active profile.").action(() => {
2205
2375
  logout(program.opts().profile);
2206
2376
  });
2207
- program.command("setup <harness>").description("Configure a coding harness (opencode | pi | hermes | claude-code | codex | copilot-cli | openclaw | 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) => {
2377
+ 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) => {
2208
2378
  const code = await runSetup(harness, {
2209
2379
  profile: program.opts().profile,
2210
2380
  print: opts.print,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunaroute/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "LunaRoute CLI — configure coding harnesses and manage your LunaRoute account.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,6 +32,7 @@
32
32
  "commander": "^15.0.0",
33
33
  "cross-spawn": "^7.0.6",
34
34
  "open": "^11.0.1",
35
+ "yaml": "^2.9.1",
35
36
  "zod": "^4.4.3"
36
37
  },
37
38
  "devDependencies": {