@moonmath-ai/zro 0.2.4 → 0.3.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.
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { ENDPOINT_ROOT, ZRO_MODELS, DEFAULT_MODEL, } from "./engine/constants.js";
3
+ import { ENDPOINT_ROOT, } from "./engine/constants.js";
4
4
  export class CatalogAuthenticationError extends Error {
5
5
  status;
6
6
  constructor(status) {
@@ -9,15 +9,17 @@ export class CatalogAuthenticationError extends Error {
9
9
  this.name = "CatalogAuthenticationError";
10
10
  }
11
11
  }
12
- export const BUNDLED_MODEL_CATALOG = {
13
- version: 1,
14
- default: DEFAULT_MODEL,
15
- models: ZRO_MODELS,
16
- };
12
+ export class CatalogUnavailableError extends Error {
13
+ constructor(reason) {
14
+ super(`Could not reach the Zro model catalog (${reason}). Check your connection and try again.`);
15
+ this.name = "CatalogUnavailableError";
16
+ }
17
+ }
17
18
  export async function loadModelCatalog(options) {
19
+ let fetchFailure;
18
20
  if (options.apiKey) {
19
21
  try {
20
- const catalog = await fetchModelCatalog(options);
22
+ const catalog = await fetchAuthenticatedCatalog(options, options.apiKey);
21
23
  if (options.cacheRemote !== false) {
22
24
  await writeCachedCatalog(options, catalog).catch(() => { });
23
25
  }
@@ -28,12 +30,16 @@ export async function loadModelCatalog(options) {
28
30
  await invalidateModelCatalog(options).catch(() => { });
29
31
  throw error;
30
32
  }
33
+ fetchFailure = error;
31
34
  }
32
35
  }
33
36
  const cached = await readCachedCatalog(options);
34
37
  if (cached)
35
38
  return { ...cached, source: "cache" };
36
- return { ...BUNDLED_MODEL_CATALOG, source: "bundled" };
39
+ if (fetchFailure) {
40
+ throw new CatalogUnavailableError(fetchFailure instanceof Error ? fetchFailure.message : String(fetchFailure));
41
+ }
42
+ throw new Error("No model catalog is available. Run zro login to load models.");
37
43
  }
38
44
  export async function invalidateModelCatalog(options) {
39
45
  try {
@@ -49,11 +55,11 @@ export function modelCatalogCachePath(options) {
49
55
  const cacheRoot = options.env.XDG_CACHE_HOME || path.join(options.homeDir, ".cache");
50
56
  return path.join(cacheRoot, "zro", "model-catalog.json");
51
57
  }
52
- async function fetchModelCatalog(options) {
58
+ async function fetchAuthenticatedCatalog(options, apiKey) {
53
59
  const fetcher = options.fetch ?? globalThis.fetch;
54
- const endpointRoot = (options.env.ZRO_AUTH_URL || options.env.ZRO_ENDPOINT_ROOT || ENDPOINT_ROOT).replace(/\/+$/, "");
60
+ const endpointRoot = catalogRoot(options.env);
55
61
  const response = await fetcher(`${endpointRoot}/api/cli/models`, {
56
- headers: { Authorization: `Bearer ${options.apiKey}` },
62
+ headers: { Authorization: `Bearer ${apiKey}` },
57
63
  signal: AbortSignal.timeout(5_000),
58
64
  });
59
65
  if (response.status === 401 || response.status === 403) {
@@ -66,6 +72,9 @@ async function fetchModelCatalog(options) {
66
72
  }
67
73
  return parseModelCatalog(await response.json());
68
74
  }
75
+ function catalogRoot(env) {
76
+ return (env.ZRO_AUTH_URL || env.ZRO_ENDPOINT_ROOT || ENDPOINT_ROOT).replace(/\/+$/, "");
77
+ }
69
78
  async function readCachedCatalog(options) {
70
79
  try {
71
80
  const contents = await fs.readFile(modelCatalogCachePath(options), "utf8");
@@ -1 +1 @@
1
- {"version":3,"file":"model-catalog.js","sourceRoot":"","sources":["../src/model-catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,aAAa,EACb,UAAU,EACV,aAAa,GAId,MAAM,uBAAuB,CAAC;AAsB/B,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IACvB;IAA5B,YAA4B,MAAc;QACxC,KAAK,CAAC,kCAAkC,MAAM,IAAI,CAAC,CAAC;QAD1B,WAAM,GAAN,MAAM,CAAQ;QAExC,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;IAC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AK,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC;IACrF,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,eAAe,CAAC,KAAc,EAAE,KAAa;IACpD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAC5E,MAAM,IAAI,KAAK,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC;IACvC,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,8 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ import type { SpawnOptions, SpawnProcess } from "./engine/types.js";
3
+ export declare function spawnCommand(spawn: SpawnProcess, platform: NodeJS.Platform, command: string, args: string[], options: SpawnOptions): ChildProcess;
4
+ export declare function isCommandShim(command: string): boolean;
5
+ export declare function windowsExecutableExtensions(pathExt: string | undefined): string[];
6
+ export declare function resolveWindowsCommand(command: string, env: NodeJS.ProcessEnv): string;
7
+ export declare function escapeShimArgument(argument: string): string;
8
+ export declare function escapeCommand(command: string): string;
@@ -0,0 +1,51 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ const META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
4
+ export function spawnCommand(spawn, platform, command, args, options) {
5
+ if (platform !== "win32")
6
+ return spawn(command, args, options);
7
+ const resolved = resolveWindowsCommand(command, options.env);
8
+ if (!isCommandShim(resolved))
9
+ return spawn(resolved, args, options);
10
+ // Spawning cmd.exe ourselves skips Node's refusal to run .cmd/.bat with arguments, so every
11
+ // token is escaped for cmd.exe's own parser. Otherwise `&` or `"` in an argument runs commands.
12
+ const line = [escapeCommand(resolved), ...args.map(escapeShimArgument)].join(" ");
13
+ return spawn(options.env.ComSpec || options.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", `"${line}"`], { ...options, windowsVerbatimArguments: true });
14
+ }
15
+ export function isCommandShim(command) {
16
+ return /\.(?:cmd|bat)$/i.test(command);
17
+ }
18
+ export function windowsExecutableExtensions(pathExt) {
19
+ return (pathExt || ".COM;.EXE;.BAT;.CMD")
20
+ .split(";")
21
+ .map((extension) => extension.trim().toLowerCase())
22
+ .filter(Boolean);
23
+ }
24
+ // Node's bare spawn does not apply PATHEXT, so `claude` never finds `claude.cmd`. PATH only: the
25
+ // current directory is deliberately not searched, so a repository cannot plant a binary.
26
+ export function resolveWindowsCommand(command, env) {
27
+ const extensions = windowsExecutableExtensions(env.PATHEXT);
28
+ if (extensions.some((extension) => command.toLowerCase().endsWith(extension)))
29
+ return command;
30
+ const directories = (env.PATH || env.Path || "").split(path.win32.delimiter).filter(Boolean);
31
+ for (const directory of directories) {
32
+ for (const extension of extensions) {
33
+ const candidate = path.win32.resolve(directory, `${command}${extension}`);
34
+ if (fs.existsSync(candidate))
35
+ return candidate;
36
+ }
37
+ }
38
+ return command;
39
+ }
40
+ // Quoting rules from https://qntm.org/cmd, applied twice because a .cmd shim re-parses its
41
+ // arguments (the same approach as cross-spawn).
42
+ export function escapeShimArgument(argument) {
43
+ const quoted = `"${argument
44
+ .replace(/(\\*)"/g, '$1$1\\"')
45
+ .replace(/(\\*)$/, "$1$1")}"`;
46
+ return quoted.replace(META_CHARS, "^$1").replace(META_CHARS, "^$1");
47
+ }
48
+ export function escapeCommand(command) {
49
+ return command.replace(META_CHARS, "^$1");
50
+ }
51
+ //# sourceMappingURL=process.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process.js","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAG7B,MAAM,UAAU,GAAG,0BAA0B,CAAC;AAE9C,MAAM,UAAU,YAAY,CAC1B,KAAmB,EACnB,QAAyB,EACzB,OAAe,EACf,IAAc,EACd,OAAqB;IAErB,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC,OAAO,EAAE,IA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AC,OAAO,CAAC,WAAW,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QAAE,OAAO,OAAO,CAAC;IAE9F,MAAM,WAAW,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC7F,KAAK,MAAM,SAAS,IAAI,WAAW,EAAE,CAAC;QACpC,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACnC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,OAAO,GAAG,SAAS,EAAE,CAAC,CAAC;YAC1E,IAAI,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC;gBAAE,OAAO,SAAS,CAAC;QACjD,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,2FAA2F;AAC3F,gDAAgD;AAChD,MAAM,UAAU,kBAAkB,CAAC,QAAgB;IACjD,MAAM,MAAM,GAAG,IAAI,QAAQ;SACxB,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC;SAC7B,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC;IAChC,OAAO,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;AACtE,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,OAAe;IAC3C,OAAO,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;AAC5C,CAAC"}
package/dist/run.js CHANGED
@@ -17,11 +17,12 @@ import { opencodeTool } from "./engine/tools/opencode.js";
17
17
  import { piTool } from "./engine/tools/pi.js";
18
18
  import { primeTool } from "./engine/tools/prime.js";
19
19
  import { parseArgs } from "./args.js";
20
- import { describeTool, TOOLS } from "./catalog.js";
20
+ import { describeTool } from "./catalog.js";
21
21
  import { commandExists, ensureHarnessInstalled, install } from "./install.js";
22
22
  import { readPreferences, writePreferences } from "./preferences.js";
23
23
  import { CatalogAuthenticationError, invalidateModelCatalog, loadModelCatalog, } from "./model-catalog.js";
24
- import { banner, chooseConnectMethod, chooseTool, helpText, isTty, modelName, promptLine, theme } from "./ui.js";
24
+ import { spawnCommand } from "./process.js";
25
+ import { banner, chooseConnectMethod, chooseInstall, chooseTool, helpText, isTty, modelName, promptLine, theme } from "./ui.js";
25
26
  const tools = {
26
27
  claude: claudeTool,
27
28
  codex: codexTool,
@@ -37,10 +38,6 @@ const tools = {
37
38
  };
38
39
  const PACKAGE_VERSION = JSON.parse(fsSync.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
39
40
  export async function run(argv, io = defaultIo()) {
40
- if ((io.platform ?? process.platform) === "win32") {
41
- io.stderr.write("zro supports macOS and Linux. Use WSL on Windows.\n");
42
- return 1;
43
- }
44
41
  let request;
45
42
  try {
46
43
  request = parseArgs(argv);
@@ -111,11 +108,6 @@ export async function run(argv, io = defaultIo()) {
111
108
  aliases: request.aliases
112
109
  };
113
110
  }
114
- if (request.install && !request.dryRun) {
115
- const ready = await ensureHarnessInstalled(request.tool, io, env);
116
- if (!ready)
117
- return 1;
118
- }
119
111
  return launch(request, io, env, colors);
120
112
  }
121
113
  async function launch(request, io, env, colors) {
@@ -123,27 +115,15 @@ async function launch(request, io, env, colors) {
123
115
  try {
124
116
  key = await resolveApiKey({ flagValue: request.apiKey, env, homeDir: io.homeDir });
125
117
  }
126
- catch (error) {
118
+ catch {
127
119
  if (!isTty(io.stdin) || !isTty(io.stdout)) {
128
120
  io.stderr.write("Not logged in. Run zro login or set ZRO_API_KEY.\n");
129
121
  return 1;
130
122
  }
131
- io.stdout.write(`${colors.strong("Connect once to keep going.")}\n\n`);
132
- const loggedIn = await loginWithWebsite({
133
- command: "login",
134
- method: "browser",
135
- openBrowser: true,
136
- output: "human",
137
- }, io, env, colors);
138
- if (loggedIn !== 0)
139
- return loggedIn;
140
- try {
141
- key = await resolveApiKey({ env, homeDir: io.homeDir });
142
- }
143
- catch (resolutionError) {
144
- io.stderr.write(`${messageOf(resolutionError)}\n`);
145
- return 1;
146
- }
123
+ const connected = await connectInteractively(io, env, colors);
124
+ if (typeof connected === "number")
125
+ return connected;
126
+ key = connected;
147
127
  }
148
128
  if (request.apiKey) {
149
129
  io.stderr.write(`Note: --api-key can land in shell history. Prefer zro login or ${ZRO_ENV_KEY}.\n`);
@@ -163,7 +143,7 @@ async function launch(request, io, env, colors) {
163
143
  io.stderr.write(`Authentication failed: ${error.message} Run zro login --manual with a valid API key. Agent was not started.\n`);
164
144
  return 1;
165
145
  }
166
- io.stderr.write(`Could not load the Zro model catalog: ${messageOf(error)}\n`);
146
+ io.stderr.write(`${messageOf(error)} Agent was not started.\n`);
167
147
  return 1;
168
148
  }
169
149
  const model = request.model ?? catalog.default;
@@ -171,6 +151,27 @@ async function launch(request, io, env, colors) {
171
151
  io.stderr.write(unknownModelMessage(model, catalog.source));
172
152
  return 1;
173
153
  }
154
+ const tool = describeTool(request.tool);
155
+ if (!request.dryRun &&
156
+ !await commandExists(tool.executable, env) &&
157
+ (request.install || (isTty(io.stdin) && isTty(io.stdout)))) {
158
+ if (!request.install) {
159
+ let choice;
160
+ try {
161
+ choice = await chooseInstall(tool.name, io.stdin, io.stdout, colors);
162
+ }
163
+ catch (error) {
164
+ if (messageOf(error) !== "Cancelled.")
165
+ io.stderr.write(`${messageOf(error)}\n`);
166
+ return messageOf(error) === "Cancelled." ? 0 : 1;
167
+ }
168
+ if (choice === "cancel")
169
+ return 0;
170
+ }
171
+ const ready = await ensureHarnessInstalled(request.tool, io, env);
172
+ if (!ready)
173
+ return 1;
174
+ }
174
175
  let modelAliases;
175
176
  for (const [slot, modelId] of Object.entries(request.aliases ?? {})) {
176
177
  if (request.tool !== "claude") {
@@ -204,6 +205,7 @@ async function launch(request, io, env, colors) {
204
205
  homeDir: io.homeDir,
205
206
  cwd: io.cwd,
206
207
  tempDir,
208
+ platform: io.platform ?? process.platform,
207
209
  stdin: io.stdin,
208
210
  stdout: io.stdout,
209
211
  stderr: io.stderr
@@ -215,7 +217,7 @@ async function launch(request, io, env, colors) {
215
217
  return 1;
216
218
  }
217
219
  if (request.dryRun) {
218
- printPreview(plan, request.output, io, key.apiKey, colors);
220
+ printPreview(plan, request.output, io, key.apiKey, colors, catalog.models);
219
221
  await fs.rm(tempDir, { recursive: true, force: true });
220
222
  return 0;
221
223
  }
@@ -245,8 +247,25 @@ async function launch(request, io, env, colors) {
245
247
  return 1;
246
248
  }
247
249
  finally {
248
- await fs.rm(tempDir, { recursive: true, force: true });
250
+ await removeSessionDir(tempDir, io);
251
+ }
252
+ }
253
+ // Windows keeps files locked briefly after a child exits (antivirus, plugin clones), so a
254
+ // single rm can fail with EBUSY/EPERM even though the session is over. Retry, then warn rather
255
+ // than crash after the session.
256
+ async function removeSessionDir(tempDir, io) {
257
+ for (const delayMs of [0, 250, 1000, 3000]) {
258
+ if (delayMs > 0)
259
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
260
+ try {
261
+ await fs.rm(tempDir, { recursive: true, force: true });
262
+ return;
263
+ }
264
+ catch {
265
+ // Retry.
266
+ }
249
267
  }
268
+ io.stderr.write(`Could not remove ${tempDir}; it may hold session files, so delete it manually.\n`);
250
269
  }
251
270
  async function verifyApiKey(apiKey, io, env) {
252
271
  const fetcher = io.fetch ?? globalThis.fetch;
@@ -282,12 +301,31 @@ async function verifyApiKey(apiKey, io, env) {
282
301
  "Agent was not started.\n");
283
302
  return false;
284
303
  }
285
- async function login(request, io, env, colors) {
304
+ async function connectInteractively(io, env, colors) {
305
+ io.stdout.write(`${colors.strong("Connect once to keep going.")}\n\n`);
306
+ const loggedIn = await login({
307
+ command: "login",
308
+ method: "choose",
309
+ openBrowser: true,
310
+ output: "human",
311
+ }, io, env, colors, false);
312
+ if (loggedIn !== 0)
313
+ return loggedIn;
314
+ try {
315
+ return await resolveApiKey({ env, homeDir: io.homeDir });
316
+ }
317
+ catch (error) {
318
+ io.stderr.write(`${messageOf(error)}\n`);
319
+ return 1;
320
+ }
321
+ }
322
+ async function login(request, io, env, colors, showBanner = true) {
286
323
  let method = request.method;
287
- let showWebsiteBanner = true;
324
+ let showWebsiteBanner = showBanner;
288
325
  if (method === "choose") {
289
326
  if (request.output === "human" && isTty(io.stdin) && isTty(io.stdout)) {
290
- io.stdout.write(`${banner(colors)}\n\n`);
327
+ if (showBanner)
328
+ io.stdout.write(`${banner(colors)}\n\n`);
291
329
  try {
292
330
  method = await chooseConnectMethod(io.stdin, io.stdout, colors);
293
331
  }
@@ -467,16 +505,9 @@ async function status(output, io, env, colors) {
467
505
  const source = envKey ? "environment" : stored ? "stored" : "none";
468
506
  const credential = envKey ?? stored;
469
507
  const preferences = await readPreferences({ homeDir: io.homeDir, env });
470
- const [installed, accountResult] = await Promise.all([
471
- Promise.all(TOOLS.map(async (tool) => ({
472
- id: tool.id,
473
- name: tool.name,
474
- installed: await commandExists(tool.executable, env)
475
- }))),
476
- credential
477
- ? fetchAccountStatus(credential, io, env)
478
- : Promise.resolve({ state: "not_connected" }),
479
- ]);
508
+ const accountResult = credential
509
+ ? await fetchAccountStatus(credential, io, env)
510
+ : { state: "not_connected" };
480
511
  const connected = source !== "none" && accountResult.state !== "rejected";
481
512
  if (accountResult.state === "rejected") {
482
513
  await invalidateModelCatalog({ homeDir: io.homeDir, env }).catch(() => { });
@@ -491,32 +522,37 @@ async function status(output, io, env, colors) {
491
522
  lastSession: preferences.lastTool && preferences.lastModel
492
523
  ? { tool: preferences.lastTool, model: preferences.lastModel }
493
524
  : null,
494
- tools: installed
495
525
  }, null, 2)}\n`);
496
526
  return 0;
497
527
  }
498
- io.stdout.write(`${banner(colors)}\n\n`);
499
- io.stdout.write(`${!connected ? colors.muted("◇") : colors.good("◆")} Connection `);
500
- io.stdout.write(source === "none"
501
- ? `${colors.muted("not logged in")}\n Run zro login\n`
502
- : accountResult.state === "rejected"
503
- ? `${colors.muted("API key rejected")}\n Run zro login --manual\n`
504
- : `${colors.strong(source)} ${colors.muted(`· ${maskKey(credential)}`)}\n`);
528
+ io.stdout.write(`${banner(colors)}\n`);
529
+ io.stdout.write(`\n${colors.muted("CONNECTION")}\n`);
530
+ if (source === "none") {
531
+ io.stdout.write(` ${colors.muted("◇")} Not logged in\n`);
532
+ io.stdout.write(` ${colors.muted("Run")} zro login ${colors.muted("to connect")}\n`);
533
+ }
534
+ else if (accountResult.state === "rejected") {
535
+ io.stdout.write(` ${colors.muted("◇")} API key rejected\n`);
536
+ io.stdout.write(` ${colors.muted("Run")} zro login --manual ${colors.muted("with a valid key")}\n`);
537
+ }
538
+ else {
539
+ io.stdout.write(` ${colors.good("◆")} ${colors.strong(source)} ${colors.muted(maskKey(credential))}\n`);
540
+ }
505
541
  if (accountResult.state === "available") {
506
542
  printAccountStatus(accountResult.account, io, colors);
507
543
  }
508
544
  else if (accountResult.state === "unavailable") {
509
- io.stdout.write(`${colors.muted("◇")} Account ${colors.muted("details unavailable")}\n`);
545
+ io.stdout.write(`\n${colors.muted("ACCOUNT")}\n`);
546
+ io.stdout.write(` ${colors.muted("◇")} Details unavailable\n`);
510
547
  }
548
+ io.stdout.write(`\n${colors.muted("LAST SESSION")}\n`);
511
549
  if (preferences.lastTool && preferences.lastModel) {
512
- io.stdout.write(`${colors.accent("◆")} Last session ${describeTool(preferences.lastTool).name} ${colors.muted(`· ${preferences.lastModel}`)}\n`);
550
+ io.stdout.write(` ${colors.accent("◆")} ${colors.strong(describeTool(preferences.lastTool).name)} ` +
551
+ `${colors.muted(preferences.lastModel)}\n`);
552
+ io.stdout.write(` ${colors.muted("Reopen with")} zro again\n`);
513
553
  }
514
554
  else {
515
- io.stdout.write(`${colors.muted("◇")} Last session ${colors.muted("none yet")}\n`);
516
- }
517
- io.stdout.write("\nTools\n");
518
- for (const tool of installed) {
519
- io.stdout.write(` ${tool.installed ? colors.good("◆") : colors.muted("◇")} ${pad(tool.name, 13)} ${tool.installed ? "ready" : colors.muted("not installed")}\n`);
555
+ io.stdout.write(` ${colors.muted("◇")} None yet — start with ${colors.muted("zro claude")}\n`);
520
556
  }
521
557
  return 0;
522
558
  }
@@ -579,19 +615,24 @@ function hasNumbers(value, keys) {
579
615
  }
580
616
  function printAccountStatus(account, io, colors) {
581
617
  const plan = account.billing.plan;
582
- io.stdout.write("\nAccount\n");
583
- io.stdout.write(` ${colors.good("◆")} Plan ${plan ? colors.strong(plan.name) : colors.muted("none")} ` +
584
- `${colors.muted(`· ${account.billing.status}`)}\n`);
618
+ const currency = account.billing.currency;
619
+ const packs = account.billing.usagePacks;
620
+ const activity = account.activity30d;
621
+ io.stdout.write(`\n${colors.muted("ACCOUNT")}\n`);
622
+ io.stdout.write(` ${plan ? colors.good("◆") : colors.muted("◇")} Plan ` +
623
+ `${plan ? colors.strong(plan.name) : colors.muted("none")} ` +
624
+ `${colors.muted(account.billing.status)}\n`);
585
625
  if (plan) {
586
- io.stdout.write(` ${colors.good("◆")} Plan usage ${money(plan.used, account.billing.currency)} of ` +
587
- `${money(plan.allowance, account.billing.currency)} · ${money(plan.remaining, account.billing.currency)} left\n`);
626
+ const ratio = plan.allowance > 0 ? Math.min(Math.max(plan.used / plan.allowance, 0), 1) : 0;
627
+ const width = 24;
628
+ const filled = Math.round(ratio * width);
629
+ const bar = colors.good("█".repeat(filled)) + colors.muted("░".repeat(width - filled));
630
+ io.stdout.write(` ${bar} ${colors.strong(`${Math.round(ratio * 100)}%`)} ${colors.muted("used")}\n`);
588
631
  }
589
- const packs = account.billing.usagePacks;
590
- io.stdout.write(` ${packs.remaining > 0 ? colors.good("◆") : colors.muted("◇")} Usage packs ` +
591
- `${money(packs.remaining, account.billing.currency)} left · ${money(packs.total, account.billing.currency)} total\n`);
592
- io.stdout.write(` ${colors.good("◆")} Available ${money(account.billing.totalRemaining, account.billing.currency)} total\n`);
593
- io.stdout.write(` ${colors.muted("◇")} Last 30 days ${formatInteger(account.activity30d.requests)} requests · ` +
594
- `${formatInteger(account.activity30d.totalTokens)} tokens\n`);
632
+ io.stdout.write(` ${packs.remaining > 0 ? colors.good("◆") : colors.muted("◇")} Top-up credits ` +
633
+ `${colors.strong(money(packs.remaining, currency))} ${colors.muted(`left · ${money(packs.total, currency)} total`)}\n`);
634
+ io.stdout.write(` ${colors.muted("◇")} Activity ${formatInteger(activity.requests)} ${colors.muted("requests ·")} ` +
635
+ `${formatTokens(activity.totalTokens)} ${colors.muted("tokens")} ${colors.muted("(30d)")}\n`);
595
636
  }
596
637
  function money(value, currency) {
597
638
  return new Intl.NumberFormat("en-US", {
@@ -610,7 +651,7 @@ async function models(output, io, env, colors) {
610
651
  apiKey = (await resolveApiKey({ env, homeDir: io.homeDir })).apiKey;
611
652
  }
612
653
  catch {
613
- // A cached or bundled catalog remains useful before the user signs in.
654
+ // A cached catalog remains useful before the user signs in.
614
655
  }
615
656
  let catalog;
616
657
  try {
@@ -621,8 +662,27 @@ async function models(output, io, env, colors) {
621
662
  io.stderr.write(`Authentication failed: ${error.message} Run zro login --manual with a valid API key.\n`);
622
663
  return 1;
623
664
  }
624
- io.stderr.write(`Could not load the Zro model catalog: ${messageOf(error)}\n`);
625
- return 1;
665
+ if (output === "human" && isTty(io.stdin) && isTty(io.stdout)) {
666
+ const connected = await connectInteractively(io, env, colors);
667
+ if (typeof connected === "number")
668
+ return connected;
669
+ try {
670
+ catalog = await loadModelCatalog({
671
+ apiKey: connected.apiKey,
672
+ env,
673
+ homeDir: io.homeDir,
674
+ fetch: io.fetch,
675
+ });
676
+ }
677
+ catch (retryError) {
678
+ io.stderr.write(`Could not load the Zro model catalog: ${messageOf(retryError)}\n`);
679
+ return 1;
680
+ }
681
+ }
682
+ else {
683
+ io.stderr.write(`Could not load the Zro model catalog: ${messageOf(error)}\n`);
684
+ return 1;
685
+ }
626
686
  }
627
687
  if (output === "json") {
628
688
  io.stdout.write(`${JSON.stringify(catalog, null, 2)}\n`);
@@ -634,7 +694,7 @@ async function models(output, io, env, colors) {
634
694
  io.stdout.write(`\n ${isDefault ? colors.accent("◆") : colors.muted("◇")} ${colors.strong(model.displayName)} ${colors.muted(model.id)}${isDefault ? colors.accent(" default") : ""}\n`);
635
695
  io.stdout.write(` ${formatTokens(model.contextWindow)} context · ${formatTokens(model.maxOutputTokens)} max output · ${model.reasoning.levels.map((level) => level.id).join(" / ")}\n`);
636
696
  }
637
- io.stdout.write("\nChoose per session with -m, for example: zro codex -m glm-5.3\n");
697
+ io.stdout.write(`\nChoose per session with -m, for example: zro codex -m ${catalog.default}\n`);
638
698
  return 0;
639
699
  }
640
700
  async function feedback(request, io, env, colors) {
@@ -702,7 +762,7 @@ async function feedback(request, io, env, colors) {
702
762
  : `${colors.good("Thanks!")} Your feedback is on its way.\n`);
703
763
  return 0;
704
764
  }
705
- function printPreview(plan, output, io, secret, colors) {
765
+ function printPreview(plan, output, io, secret, colors, models) {
706
766
  const safeEnv = Object.fromEntries(Object.entries(plan.env ?? {}).map(([key, value]) => [key, redact(key, value, secret)]));
707
767
  const result = {
708
768
  tool: plan.tool,
@@ -718,7 +778,7 @@ function printPreview(plan, output, io, secret, colors) {
718
778
  }
719
779
  io.stdout.write(`${banner(colors)}\n\n${colors.strong("Session preview")}\n`);
720
780
  io.stdout.write(` Tool ${describeTool(plan.tool).name}\n`);
721
- io.stdout.write(` Model ${modelName(plan.model)} ${colors.muted(`· ${plan.model}`)}\n`);
781
+ io.stdout.write(` Model ${modelName(plan.model, models)} ${colors.muted(`· ${plan.model}`)}\n`);
722
782
  io.stdout.write(` Command ${shellPreview([plan.command, ...plan.args])}\n`);
723
783
  const entries = Object.entries(safeEnv);
724
784
  if (entries.length) {
@@ -741,7 +801,7 @@ async function writeLaunchFiles(plan) {
741
801
  }
742
802
  async function spawnPlan(plan, io, env) {
743
803
  const spawn = io.spawn ?? nodeSpawn;
744
- const child = spawn(plan.command, plan.args, {
804
+ const child = spawnCommand(spawn, io.platform ?? process.platform, plan.command, plan.args, {
745
805
  cwd: io.cwd,
746
806
  env: { ...env, ...(plan.env ?? {}) },
747
807
  stdio: "inherit"
@@ -762,10 +822,7 @@ export function unknownModelMessage(model, source) {
762
822
  if (source === "remote") {
763
823
  return `Unknown model "${model}". It is not offered by your account's catalog. Run zro models.\n`;
764
824
  }
765
- if (source === "cache") {
766
- return `Unknown model "${model}". It is not in the cached catalog from your last login. Run zro login to refresh your account's catalog.\n`;
767
- }
768
- return `Unknown model "${model}". It is not in the offline catalog bundled with zro. Run zro login to fetch your account's catalog.\n`;
825
+ return `Unknown model "${model}". It is not in the cached catalog from your last login. Run zro login to refresh your account's catalog.\n`;
769
826
  }
770
827
  export function redact(key, value, secret) {
771
828
  if (value === "")
@@ -802,22 +859,38 @@ function compactPath(cwd, homeDir) {
802
859
  return cwd === homeDir ? "~" : cwd.startsWith(`${homeDir}${path.sep}`) ? `~${cwd.slice(homeDir.length)}` : cwd;
803
860
  }
804
861
  function formatTokens(value) {
805
- if (value >= 1_000_000)
806
- return `${(value / 1_000_000).toFixed(1).replace(".0", "")}M`;
807
- return `${Math.round(value / 1_000)}K`;
808
- }
809
- function pad(value, width) {
810
- return value + " ".repeat(Math.max(1, width - value.length));
862
+ const units = [
863
+ [1_000_000_000, "B"],
864
+ [1_000_000, "M"],
865
+ [1_000, "K"],
866
+ ];
867
+ for (const [threshold, suffix] of units) {
868
+ if (value >= threshold) {
869
+ const scaled = value / threshold;
870
+ return `${scaled >= 10 ? Math.round(scaled) : scaled.toFixed(1)}${suffix}`;
871
+ }
872
+ }
873
+ return String(value);
811
874
  }
812
875
  function messageOf(error) {
813
876
  return error instanceof Error ? error.message : String(error);
814
877
  }
815
878
  async function openBrowserWithSystem(url, platform) {
816
- const command = platform === "darwin" ? "open" : platform === "linux" ? "xdg-open" : null;
879
+ // explorer.exe is a single-instance shell: a spawned process just forwards its argument to the
880
+ // running shell, which often opens a File Explorer window instead of the URL. rundll32 goes
881
+ // straight through the URL protocol handler, so the default browser always opens.
882
+ const command = platform === "darwin"
883
+ ? "open"
884
+ : platform === "linux"
885
+ ? "xdg-open"
886
+ : platform === "win32"
887
+ ? "rundll32"
888
+ : null;
817
889
  if (!command)
818
890
  return false;
891
+ const args = platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
819
892
  return new Promise((resolve) => {
820
- const child = nodeSpawn(command, [url], { detached: true, stdio: "ignore" });
893
+ const child = nodeSpawn(command, args, { detached: true, stdio: "ignore" });
821
894
  let settled = false;
822
895
  child.once("error", () => {
823
896
  if (settled)