@moonmath-ai/zro 0.1.16 → 0.2.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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +80 -73
  3. package/SECURITY.md +21 -0
  4. package/dist/args.d.ts +2 -4
  5. package/dist/args.js +182 -66
  6. package/dist/args.js.map +1 -1
  7. package/dist/catalog.d.ts +17 -0
  8. package/dist/catalog.js +23 -0
  9. package/dist/catalog.js.map +1 -0
  10. package/dist/engine/constants.js.map +1 -0
  11. package/dist/engine/files.js.map +1 -0
  12. package/dist/engine/key.js.map +1 -0
  13. package/dist/engine/serializers.js.map +1 -0
  14. package/dist/engine/tools/claude.js.map +1 -0
  15. package/dist/{tools → engine/tools}/codex.d.ts +2 -0
  16. package/dist/{tools → engine/tools}/codex.js +8 -2
  17. package/dist/engine/tools/codex.js.map +1 -0
  18. package/dist/engine/tools/grok.js.map +1 -0
  19. package/dist/engine/tools/helpers.js.map +1 -0
  20. package/dist/engine/tools/hermes.js.map +1 -0
  21. package/dist/engine/tools/openclaw.js.map +1 -0
  22. package/dist/engine/tools/opencode.js.map +1 -0
  23. package/dist/engine/tools/pi.js.map +1 -0
  24. package/dist/engine/types.d.ts +43 -0
  25. package/dist/engine/types.js +2 -0
  26. package/dist/engine/types.js.map +1 -0
  27. package/dist/install.d.ts +9 -0
  28. package/dist/install.js +133 -0
  29. package/dist/install.js.map +1 -0
  30. package/dist/preferences.d.ts +9 -0
  31. package/dist/preferences.js +31 -0
  32. package/dist/preferences.js.map +1 -0
  33. package/dist/run.d.ts +1 -17
  34. package/dist/run.js +609 -179
  35. package/dist/run.js.map +1 -1
  36. package/dist/types.d.ts +52 -47
  37. package/dist/ui.d.ts +15 -0
  38. package/dist/ui.js +135 -0
  39. package/dist/ui.js.map +1 -0
  40. package/package.json +13 -9
  41. package/dist/constants.js.map +0 -1
  42. package/dist/files.js.map +0 -1
  43. package/dist/key.js.map +0 -1
  44. package/dist/models.d.ts +0 -6
  45. package/dist/models.js +0 -128
  46. package/dist/models.js.map +0 -1
  47. package/dist/primes.d.ts +0 -10
  48. package/dist/primes.js +0 -98
  49. package/dist/primes.js.map +0 -1
  50. package/dist/serializers.js.map +0 -1
  51. package/dist/tools/claude.js.map +0 -1
  52. package/dist/tools/codex.js.map +0 -1
  53. package/dist/tools/grok.js.map +0 -1
  54. package/dist/tools/helpers.js.map +0 -1
  55. package/dist/tools/hermes.js.map +0 -1
  56. package/dist/tools/openclaw.js.map +0 -1
  57. package/dist/tools/opencode.js.map +0 -1
  58. package/dist/tools/pi.js.map +0 -1
  59. package/dist/upgrade.d.ts +0 -27
  60. package/dist/upgrade.js +0 -319
  61. package/dist/upgrade.js.map +0 -1
  62. /package/dist/{constants.d.ts → engine/constants.d.ts} +0 -0
  63. /package/dist/{constants.js → engine/constants.js} +0 -0
  64. /package/dist/{files.d.ts → engine/files.d.ts} +0 -0
  65. /package/dist/{files.js → engine/files.js} +0 -0
  66. /package/dist/{key.d.ts → engine/key.d.ts} +0 -0
  67. /package/dist/{key.js → engine/key.js} +0 -0
  68. /package/dist/{serializers.d.ts → engine/serializers.d.ts} +0 -0
  69. /package/dist/{serializers.js → engine/serializers.js} +0 -0
  70. /package/dist/{tools → engine/tools}/claude.d.ts +0 -0
  71. /package/dist/{tools → engine/tools}/claude.js +0 -0
  72. /package/dist/{tools → engine/tools}/grok.d.ts +0 -0
  73. /package/dist/{tools → engine/tools}/grok.js +0 -0
  74. /package/dist/{tools → engine/tools}/helpers.d.ts +0 -0
  75. /package/dist/{tools → engine/tools}/helpers.js +0 -0
  76. /package/dist/{tools → engine/tools}/hermes.d.ts +0 -0
  77. /package/dist/{tools → engine/tools}/hermes.js +0 -0
  78. /package/dist/{tools → engine/tools}/openclaw.d.ts +0 -0
  79. /package/dist/{tools → engine/tools}/openclaw.js +0 -0
  80. /package/dist/{tools → engine/tools}/opencode.d.ts +0 -0
  81. /package/dist/{tools → engine/tools}/opencode.js +0 -0
  82. /package/dist/{tools → engine/tools}/pi.d.ts +0 -0
  83. /package/dist/{tools → engine/tools}/pi.js +0 -0
package/dist/run.js CHANGED
@@ -1,20 +1,23 @@
1
1
  import { spawn as nodeSpawn } from "node:child_process";
2
+ import { constants as cryptoConstants, generateKeyPairSync, privateDecrypt, } from "node:crypto";
3
+ import fsSync from "node:fs";
2
4
  import fs from "node:fs/promises";
3
5
  import os from "node:os";
4
6
  import path from "node:path";
5
- import { CommanderError } from "commander";
6
- import { ZRO_ENV_KEY } from "./constants.js";
7
- import { parseArgs, SUPPORTED_TOOLS_LIST } from "./args.js";
8
- import { credentialFilePath, deleteStoredApiKey, maskKey, promptHidden, readStoredApiKey, resolveApiKey, writeStoredApiKey } from "./key.js";
9
- import { resolveModel } from "./models.js";
10
- import { claudeTool } from "./tools/claude.js";
11
- import { codexAppTool, codexTool } from "./tools/codex.js";
12
- import { grokTool } from "./tools/grok.js";
13
- import { hermesTool } from "./tools/hermes.js";
14
- import { openClawTool } from "./tools/openclaw.js";
15
- import { opencodeTool } from "./tools/opencode.js";
16
- import { piTool } from "./tools/pi.js";
17
- import { checkUpgrade, defaultFetchLatestVersion, getPackageVersion } from "./upgrade.js";
7
+ import { ENDPOINT_ROOT, ZRO_ENV_KEY, ZRO_MODELS, DEFAULT_MODEL } from "./engine/constants.js";
8
+ import { credentialFilePath, deleteStoredApiKey, maskKey, promptHidden, readStoredApiKey, resolveApiKey, writeStoredApiKey } from "./engine/key.js";
9
+ import { claudeTool } from "./engine/tools/claude.js";
10
+ import { codexAppCredentialFilePath, codexAppTool, codexTool, } from "./engine/tools/codex.js";
11
+ import { grokTool } from "./engine/tools/grok.js";
12
+ import { hermesTool } from "./engine/tools/hermes.js";
13
+ import { openClawTool } from "./engine/tools/openclaw.js";
14
+ import { opencodeTool } from "./engine/tools/opencode.js";
15
+ import { piTool } from "./engine/tools/pi.js";
16
+ import { parseArgs } from "./args.js";
17
+ import { describeTool, TOOLS } from "./catalog.js";
18
+ import { commandExists, ensureHarnessInstalled, install } from "./install.js";
19
+ import { readPreferences, writePreferences } from "./preferences.js";
20
+ import { banner, chooseConnectMethod, chooseTool, helpText, isTty, modelName, theme } from "./ui.js";
18
21
  const tools = {
19
22
  claude: claudeTool,
20
23
  codex: codexTool,
@@ -25,191 +28,243 @@ const tools = {
25
28
  opencode: opencodeTool,
26
29
  pi: piTool
27
30
  };
31
+ const PACKAGE_VERSION = JSON.parse(fsSync.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
28
32
  export async function run(argv, io = defaultIo()) {
29
- const platform = io.platform ?? process.platform;
30
- if (platform === "win32") {
31
- io.stderr.write("zro supports macOS and Linux. Windows is not supported; use WSL on Windows.\n");
33
+ if ((io.platform ?? process.platform) === "win32") {
34
+ io.stderr.write("zro supports macOS and Linux. Use WSL on Windows.\n");
32
35
  return 1;
33
36
  }
34
- let args;
37
+ let request;
35
38
  try {
36
- args = parseArgs(argv);
39
+ request = parseArgs(argv);
37
40
  }
38
41
  catch (error) {
39
- if (error instanceof CommanderError) {
40
- io.stdout.write(`${error.message}\n`);
41
- return error.exitCode;
42
- }
43
- throw error;
42
+ io.stderr.write(`${messageOf(error)}\n`);
43
+ return 1;
44
44
  }
45
45
  const env = io.env ?? process.env;
46
- if (args.command === "login")
47
- return login(args.apiKey, io, env);
48
- if (args.command === "logout")
49
- return logout(io, env);
50
- if (args.command === "auth-status")
51
- return authStatus(io, env);
52
- if (args.command === "version") {
53
- io.stdout.write(`${getPackageVersion()}\n`);
46
+ const colors = theme(io.stdout, env);
47
+ if (request.command === "help") {
48
+ io.stdout.write(helpText(colors));
54
49
  return 0;
55
50
  }
56
- const tool = tools[args.tool];
57
- if (!tool) {
58
- io.stderr.write(`Unsupported tool: ${args.tool}\nSupported tools: ${SUPPORTED_TOOLS_LIST}\n`);
59
- return 1;
51
+ if (request.command === "version") {
52
+ io.stdout.write(request.output === "json"
53
+ ? `${JSON.stringify({ version: io.version ?? PACKAGE_VERSION })}\n`
54
+ : `${io.version ?? PACKAGE_VERSION}\n`);
55
+ return 0;
60
56
  }
61
- if (io.fetchLatestVersion) {
62
- const upgradeResult = await checkUpgrade({
63
- currentVersion: io.currentVersion ?? getPackageVersion(),
64
- homeDir: io.homeDir,
65
- cwd: io.cwd,
66
- env,
67
- stdin: io.stdin,
68
- stdout: io.stdout,
69
- stderr: io.stderr,
70
- spawn: io.spawn,
71
- fetchLatestVersion: io.fetchLatestVersion,
72
- execPath: io.execPath,
73
- scriptPath: io.scriptPath,
74
- argv
75
- });
76
- if (!upgradeResult.proceed) {
77
- return upgradeResult.exitCode;
57
+ if (request.command === "install")
58
+ return install(request, io, env);
59
+ if (request.command === "login")
60
+ return login(request, io, env, colors);
61
+ if (request.command === "logout")
62
+ return logout(request.output, io, env);
63
+ if (request.command === "status")
64
+ return status(request.output, io, env, colors);
65
+ if (request.command === "models")
66
+ return models(request.output, io, colors);
67
+ if (request.command === "home") {
68
+ if (!isTty(io.stdin) || !isTty(io.stdout)) {
69
+ io.stdout.write(helpText(colors));
70
+ return 0;
71
+ }
72
+ io.stdout.write(`${banner(colors)}\n\n`);
73
+ try {
74
+ const tool = await chooseTool(io.stdin, io.stdout, colors);
75
+ request = {
76
+ command: "launch",
77
+ tool,
78
+ dryRun: false,
79
+ output: "human",
80
+ extraArgs: []
81
+ };
78
82
  }
83
+ catch (error) {
84
+ if (messageOf(error) !== "Cancelled.")
85
+ io.stderr.write(`${messageOf(error)}\n`);
86
+ return messageOf(error) === "Cancelled." ? 0 : 1;
87
+ }
88
+ }
89
+ if (request.command === "again") {
90
+ const preferences = await readPreferences({ homeDir: io.homeDir, env });
91
+ if (!preferences.lastTool || !preferences.lastModel) {
92
+ io.stderr.write("Nothing to reopen yet. Start with: zro claude\n");
93
+ return 1;
94
+ }
95
+ request = {
96
+ command: "launch",
97
+ tool: preferences.lastTool,
98
+ model: preferences.lastModel,
99
+ dryRun: request.dryRun,
100
+ output: request.output,
101
+ extraArgs: []
102
+ };
103
+ }
104
+ if (request.install && !request.dryRun) {
105
+ const ready = await ensureHarnessInstalled(request.tool, io, env);
106
+ if (!ready)
107
+ return 1;
108
+ }
109
+ return launch(request, io, env, colors);
110
+ }
111
+ async function launch(request, io, env, colors) {
112
+ const model = request.model ?? DEFAULT_MODEL;
113
+ if (!ZRO_MODELS.some((candidate) => candidate.id === model)) {
114
+ io.stderr.write(`Unknown model "${model}". Run zro models.\n`);
115
+ return 1;
79
116
  }
80
117
  let key;
81
118
  try {
82
- key = await resolveApiKey({ flagValue: args.apiKey, env, homeDir: io.homeDir });
119
+ key = await resolveApiKey({ flagValue: request.apiKey, env, homeDir: io.homeDir });
83
120
  }
84
121
  catch (error) {
85
- const message = error instanceof Error ? error.message : String(error);
86
- io.stderr.write(`${message}\n`);
87
- return 1;
122
+ if (!isTty(io.stdin) || !isTty(io.stdout)) {
123
+ io.stderr.write("Not logged in. Run zro login or set ZRO_API_KEY.\n");
124
+ return 1;
125
+ }
126
+ io.stdout.write(`${colors.strong("Connect once to keep going.")}\n\n`);
127
+ const loggedIn = await loginWithWebsite({
128
+ command: "login",
129
+ method: "browser",
130
+ openBrowser: true,
131
+ output: "human",
132
+ }, io, env, colors);
133
+ if (loggedIn !== 0)
134
+ return loggedIn;
135
+ try {
136
+ key = await resolveApiKey({ env, homeDir: io.homeDir });
137
+ }
138
+ catch (resolutionError) {
139
+ io.stderr.write(`${messageOf(resolutionError)}\n`);
140
+ return 1;
141
+ }
88
142
  }
89
- if (key.source === "flag") {
90
- io.stderr.write(`Note: --api-key can land in shell history. Prefer zro login or ${ZRO_ENV_KEY}=... for CI.\n`);
143
+ if (request.apiKey) {
144
+ io.stderr.write(`Note: --api-key can land in shell history. Prefer zro login or ${ZRO_ENV_KEY}.\n`);
91
145
  }
92
- let model;
146
+ const tempRoot = path.join(env.XDG_CACHE_HOME || path.join(io.homeDir, ".cache"), "zro", "sessions");
147
+ const tempDir = path.join(tempRoot, `session-${process.pid}-${Date.now()}`);
148
+ let plan;
93
149
  try {
94
- model = await resolveModel({
95
- flagValue: args.model,
150
+ plan = await tools[request.tool].launch({
151
+ apiKey: key.apiKey,
152
+ apiKeySource: key.source,
153
+ model,
154
+ extraArgs: request.extraArgs,
155
+ homeDir: io.homeDir,
156
+ cwd: io.cwd,
157
+ tempDir,
96
158
  stdin: io.stdin,
97
- stdout: io.stdout
159
+ stdout: io.stdout,
160
+ stderr: io.stderr
98
161
  });
99
162
  }
100
163
  catch (error) {
101
- const message = error instanceof Error ? error.message : String(error);
102
- io.stderr.write(`${message}\n`);
164
+ io.stderr.write(`${messageOf(error)}\n`);
165
+ await fs.rm(tempDir, { recursive: true, force: true });
103
166
  return 1;
104
167
  }
105
- const tempRoot = path.join(env.XDG_CACHE_HOME || path.join(io.homeDir, ".cache"), "zro", "launches");
106
- const tempDir = path.join(tempRoot, `zro-launch-${process.pid}-${Date.now()}`);
107
- const ctx = {
108
- apiKey: key.apiKey,
109
- apiKeySource: key.source,
110
- model,
111
- print: args.print,
112
- extraArgs: args.extraArgs,
113
- homeDir: io.homeDir,
114
- cwd: io.cwd,
115
- tempDir,
116
- stdin: io.stdin,
117
- stdout: io.stdout,
118
- stderr: io.stderr
119
- };
120
- let plan;
121
- try {
122
- plan = await tool.launch(ctx);
168
+ if (request.dryRun) {
169
+ printPreview(plan, request.output, io, key.apiKey, colors);
170
+ await fs.rm(tempDir, { recursive: true, force: true });
171
+ return 0;
123
172
  }
124
- catch (error) {
125
- const message = error instanceof Error ? error.message : String(error);
126
- io.stderr.write(`${message}\n`);
173
+ if (!await verifyApiKey(key.apiKey, io, env)) {
127
174
  await fs.rm(tempDir, { recursive: true, force: true });
128
175
  return 1;
129
176
  }
130
- if (args.print) {
131
- printPlan(plan, io.stdout);
132
- return 0;
177
+ try {
178
+ await writePreferences({ homeDir: io.homeDir, env }, { lastTool: request.tool, lastModel: model, updatedAt: new Date().toISOString() });
179
+ }
180
+ catch (error) {
181
+ if (request.output === "human") {
182
+ io.stderr.write(`Could not remember this session: ${messageOf(error)}\n`);
183
+ }
184
+ }
185
+ if (request.output === "human" && isTty(io.stdout)) {
186
+ io.stdout.write(`${colors.accent("◆")} ${colors.strong(describeTool(request.tool).name)} ` +
187
+ `${colors.muted(`${modelName(model)} · ${model}`)}\n` +
188
+ `${colors.muted(` ${compactPath(io.cwd, io.homeDir)}`)}\n\n`);
133
189
  }
134
- await writeLaunchFiles(plan);
135
190
  try {
136
- return await spawnPlan(plan, io);
191
+ await writeLaunchFiles(plan);
192
+ return await spawnPlan(plan, io, env);
137
193
  }
138
194
  catch (error) {
139
- const message = error instanceof Error ? error.message : String(error);
140
- io.stderr.write(`Failed to launch ${plan.label}: ${message}\n`);
195
+ io.stderr.write(`Could not open ${plan.label}: ${messageOf(error)}\n`);
141
196
  return 1;
142
197
  }
143
198
  finally {
144
199
  await fs.rm(tempDir, { recursive: true, force: true });
145
200
  }
146
201
  }
147
- function printPlan(plan, stdout) {
148
- stdout.write(`${plan.message ?? `Launch ${plan.label}`}\n`);
149
- stdout.write(`Model: ${plan.model}\n`);
150
- stdout.write(`Command: ${shellPreview([plan.command, ...plan.args])}\n`);
151
- const env = plan.env ?? {};
152
- const envKeys = Object.keys(env).sort();
153
- if (envKeys.length) {
154
- stdout.write("Environment:\n");
155
- for (const key of envKeys) {
156
- stdout.write(` ${key}=${redactEnvValue(key, env[key])}\n`);
157
- }
202
+ async function verifyApiKey(apiKey, io, env) {
203
+ const fetcher = io.fetch ?? globalThis.fetch;
204
+ const endpointRoot = (env.ZRO_ENDPOINT_ROOT || ENDPOINT_ROOT).replace(/\/+$/, "");
205
+ const validationUrl = `${endpointRoot}/v1/models`;
206
+ let response;
207
+ try {
208
+ response = await fetcher(validationUrl, {
209
+ headers: { Authorization: `Bearer ${apiKey}` },
210
+ signal: AbortSignal.timeout(10_000),
211
+ });
158
212
  }
159
- if (plan.files?.length) {
160
- const hasPersistentFiles = plan.files.some((file) => file.persistent);
161
- stdout.write(hasPersistentFiles ? "Files:\n" : "Temp files:\n");
162
- for (const file of plan.files) {
163
- stdout.write(` ${file.path}\n`);
164
- }
213
+ catch (error) {
214
+ io.stderr.write(`Could not verify Zro authentication at ${endpointRoot}: ${messageOf(error)}. Agent was not started.\n`);
215
+ return false;
165
216
  }
166
- }
167
- async function writeLaunchFiles(plan) {
168
- for (const file of plan.files ?? []) {
169
- await fs.mkdir(path.dirname(file.path), { recursive: true });
170
- await fs.writeFile(file.path, file.contents, { mode: 0o600 });
217
+ const status = response.status;
218
+ try {
219
+ await response.body?.cancel();
220
+ }
221
+ catch {
222
+ // The status is sufficient for this preflight; the response body is intentionally ignored.
223
+ }
224
+ if (response.ok)
225
+ return true;
226
+ if (status === 401 || status === 403) {
227
+ io.stderr.write(`Authentication failed: Zro rejected the API key (HTTP ${status}). ` +
228
+ `Run zro login --manual with a valid API key. Agent was not started.\n`);
229
+ return false;
171
230
  }
231
+ io.stderr.write(`Could not verify Zro authentication: HTTP ${status} from ${validationUrl}. ` +
232
+ "Agent was not started.\n");
233
+ return false;
172
234
  }
173
- async function spawnPlan(plan, io) {
174
- const spawn = io.spawn ?? nodeSpawn;
175
- const child = spawn(plan.command, plan.args, {
176
- cwd: io.cwd,
177
- env: { ...(io.env ?? process.env), ...(plan.env ?? {}) },
178
- stdio: "inherit"
179
- });
180
- return new Promise((resolve, reject) => {
181
- child.once("error", reject);
182
- child.once("exit", (code, signal) => {
183
- if (typeof code === "number") {
184
- resolve(code);
185
- return;
235
+ async function login(request, io, env, colors) {
236
+ let method = request.method;
237
+ let showWebsiteBanner = true;
238
+ if (method === "choose") {
239
+ if (request.output === "human" && isTty(io.stdin) && isTty(io.stdout)) {
240
+ io.stdout.write(`${banner(colors)}\n\n`);
241
+ try {
242
+ method = await chooseConnectMethod(io.stdin, io.stdout, colors);
186
243
  }
187
- io.stderr.write(`Launched tool exited from signal ${signal ?? "unknown"}.\n`);
188
- resolve(1);
189
- });
190
- });
191
- }
192
- function shellPreview(argv) {
193
- return argv.map((arg) => {
194
- if (/^[A-Za-z0-9_./:=@+-]+$/.test(arg))
195
- return arg;
196
- return `'${arg.replace(/'/g, "'\\''")}'`;
197
- }).join(" ");
198
- }
199
- function redactEnvValue(key, value) {
200
- if (/KEY|TOKEN|SECRET/i.test(key))
201
- return maskKey(value);
202
- return value;
244
+ catch (error) {
245
+ if (messageOf(error) !== "Cancelled.")
246
+ io.stderr.write(`${messageOf(error)}\n`);
247
+ return messageOf(error) === "Cancelled." ? 0 : 1;
248
+ }
249
+ showWebsiteBanner = false;
250
+ }
251
+ else {
252
+ method = "browser";
253
+ }
254
+ }
255
+ if (method === "browser") {
256
+ return loginWithWebsite(request, io, env, colors, showWebsiteBanner);
257
+ }
258
+ return loginWithApiKey(request.apiKey, request.output, io, env);
203
259
  }
204
- async function login(apiKeyFlag, io, env) {
260
+ async function loginWithApiKey(apiKeyFlag, output, io, env) {
205
261
  let apiKey = apiKeyFlag ?? env[ZRO_ENV_KEY];
206
262
  if (!apiKey) {
207
263
  try {
208
- apiKey = await promptHidden("Zro API key: ", io.stdin, io.stdout);
264
+ apiKey = await promptHidden("API key ", io.stdin, io.stdout);
209
265
  }
210
266
  catch (error) {
211
- const message = error instanceof Error ? error.message : String(error);
212
- io.stderr.write(`${message}\n`);
267
+ io.stderr.write(`${messageOf(error)}\n`);
213
268
  return 1;
214
269
  }
215
270
  }
@@ -218,50 +273,427 @@ async function login(apiKeyFlag, io, env) {
218
273
  io.stderr.write("No API key entered.\n");
219
274
  return 1;
220
275
  }
221
- if (apiKeyFlag) {
222
- io.stderr.write(`Note: --api-key can land in shell history. Prefer interactive zro login or ${ZRO_ENV_KEY}=... zro login.\n`);
223
- }
224
276
  const filePath = await writeStoredApiKey({ apiKey: trimmed, homeDir: io.homeDir, env });
225
- io.stdout.write(`Stored Zro API key at ${filePath}\n`);
226
- io.stdout.write("Run: zro launch claude --model minimax-m3\n");
277
+ if (apiKeyFlag)
278
+ io.stderr.write("Note: --api-key can land in shell history. Interactive login is safer.\n");
279
+ io.stdout.write(output === "json"
280
+ ? `${JSON.stringify({ connected: true, source: "stored", path: filePath })}\n`
281
+ : `Logged in. Your key is stored securely.\nTry: zro claude\n`);
227
282
  return 0;
228
283
  }
229
- async function logout(io, env) {
230
- const filePath = credentialFilePath({ homeDir: io.homeDir, env });
231
- const removed = await deleteStoredApiKey({ homeDir: io.homeDir, env });
232
- io.stdout.write(removed ? `Removed stored Zro API key from ${filePath}\n` : "No stored Zro API key found.\n");
233
- if (env[ZRO_ENV_KEY]) {
234
- io.stdout.write(`${ZRO_ENV_KEY} is still set in this shell and will override stored credentials.\n`);
284
+ async function loginWithWebsite(request, io, env, colors, showBanner = true) {
285
+ const fetcher = io.fetch ?? globalThis.fetch;
286
+ const authRoot = getAuthRoot(env);
287
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", {
288
+ modulusLength: 2048,
289
+ publicKeyEncoding: { type: "spki", format: "pem" },
290
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
291
+ });
292
+ let started;
293
+ try {
294
+ const response = await fetcher(`${authRoot}/api/cli/auth/start`, {
295
+ method: "POST",
296
+ headers: { "Content-Type": "application/json" },
297
+ body: JSON.stringify({
298
+ publicKey,
299
+ // Machine names can contain personal or corporate information. Only
300
+ // send a user-supplied label; otherwise use a generic description.
301
+ deviceName: env.ZRO_DEVICE_NAME || "Terminal",
302
+ }),
303
+ });
304
+ const payload = await responseJson(response);
305
+ if (!response.ok) {
306
+ const detail = errorFromPayload(payload, "Could not start website login.");
307
+ throw new Error(`${detail} (HTTP ${response.status} from ${authRoot})`);
308
+ }
309
+ started = validateDeviceLoginStart(payload);
310
+ }
311
+ catch {
312
+ if (request.output === "human" && isTty(io.stdin) && isTty(io.stdout)) {
313
+ io.stdout.write("Website sign-in is unavailable.\nPaste your Zro API key to continue.\n\n");
314
+ return loginWithApiKey(undefined, request.output, io, env);
315
+ }
316
+ io.stderr.write("Website sign-in is unavailable. Run zro login --manual to enter an API key.\n");
317
+ return 1;
318
+ }
319
+ const approvalUrl = browserApprovalUrl(started.verificationUriComplete, env);
320
+ let opened = false;
321
+ if (request.openBrowser) {
322
+ opened = await (io.openBrowser
323
+ ? io.openBrowser(approvalUrl)
324
+ : openBrowserWithSystem(approvalUrl, io.platform ?? process.platform));
325
+ }
326
+ if (request.output === "human") {
327
+ if (showBanner)
328
+ io.stdout.write(`${banner(colors)}\n\n`);
329
+ io.stdout.write(`${colors.strong(opened ? "Finish signing in in your browser" : "Open this page to sign in")}\n`);
330
+ io.stdout.write(` ${approvalUrl}\n\n`);
331
+ io.stdout.write(` Code ${colors.accent(started.userCode)}\n\n`);
332
+ io.stdout.write(`${colors.muted("Waiting for approval…")}\n`);
333
+ }
334
+ const sleep = io.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
335
+ const expiresAt = Date.now() + started.expiresIn * 1000;
336
+ const intervalMs = Math.max(1, started.interval) * 1000;
337
+ while (Date.now() < expiresAt) {
338
+ await sleep(intervalMs);
339
+ let response;
340
+ let payload;
341
+ try {
342
+ response = await fetcher(`${authRoot}/api/cli/auth/token`, {
343
+ method: "POST",
344
+ headers: { "Content-Type": "application/json" },
345
+ body: JSON.stringify({ deviceCode: started.deviceCode }),
346
+ });
347
+ payload = await responseJson(response);
348
+ }
349
+ catch {
350
+ continue;
351
+ }
352
+ if (response.status === 202)
353
+ continue;
354
+ if (!response.ok) {
355
+ io.stderr.write(`${errorFromPayload(payload, "Website login failed.")}\n`);
356
+ return 1;
357
+ }
358
+ const encryptedToken = asRecord(payload).encryptedToken;
359
+ if (typeof encryptedToken !== "string") {
360
+ io.stderr.write("Website login returned an invalid credential.\n");
361
+ return 1;
362
+ }
363
+ let apiKey;
364
+ try {
365
+ apiKey = privateDecrypt({
366
+ key: privateKey,
367
+ padding: cryptoConstants.RSA_PKCS1_OAEP_PADDING,
368
+ oaepHash: "sha256",
369
+ }, Buffer.from(encryptedToken, "base64")).toString("utf8");
370
+ }
371
+ catch {
372
+ io.stderr.write("Could not decrypt the website credential for this terminal.\n");
373
+ return 1;
374
+ }
375
+ if (!apiKey.trim()) {
376
+ io.stderr.write("Website login returned an empty credential.\n");
377
+ return 1;
378
+ }
379
+ const filePath = await writeStoredApiKey({ apiKey: apiKey.trim(), homeDir: io.homeDir, env });
380
+ io.stdout.write(request.output === "json"
381
+ ? `${JSON.stringify({ connected: true, source: "website", path: filePath })}\n`
382
+ : `${colors.good("Logged in")} — you can close the browser.\nTry: zro claude\n`);
383
+ return 0;
384
+ }
385
+ io.stderr.write("Website login expired. Run zro login to try again.\n");
386
+ return 1;
387
+ }
388
+ async function logout(output, io, env) {
389
+ const [storedKeyRemoved, codexAppKeyRemoved] = await Promise.all([
390
+ deleteStoredApiKey({ homeDir: io.homeDir, env }),
391
+ deleteOptionalFile(codexAppCredentialFilePath(io.homeDir)),
392
+ ]);
393
+ const removed = storedKeyRemoved || codexAppKeyRemoved;
394
+ io.stdout.write(output === "json"
395
+ ? `${JSON.stringify({ connected: Boolean(env[ZRO_ENV_KEY]), storedKeyRemoved: removed, environmentKeySet: Boolean(env[ZRO_ENV_KEY]) })}\n`
396
+ : removed ? "Logged out. Stored key removed.\n" : "No stored login to remove.\n");
397
+ if (env[ZRO_ENV_KEY] && output === "human") {
398
+ io.stdout.write(`${ZRO_ENV_KEY} is still set in this shell.\n`);
235
399
  }
236
400
  return 0;
237
401
  }
238
- async function authStatus(io, env) {
239
- const envKey = env[ZRO_ENV_KEY];
240
- const filePath = credentialFilePath({ homeDir: io.homeDir, env });
402
+ async function deleteOptionalFile(filePath) {
403
+ try {
404
+ await fs.rm(filePath);
405
+ return true;
406
+ }
407
+ catch (error) {
408
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
409
+ return false;
410
+ throw error;
411
+ }
412
+ }
413
+ async function status(output, io, env, colors) {
241
414
  const stored = await readStoredApiKey({ homeDir: io.homeDir, env });
242
- if (envKey) {
243
- io.stdout.write(`${ZRO_ENV_KEY}: set (${maskKey(envKey)})\n`);
415
+ const envKey = env[ZRO_ENV_KEY];
416
+ const source = envKey ? "environment" : stored ? "stored" : "none";
417
+ const credential = envKey ?? stored;
418
+ const preferences = await readPreferences({ homeDir: io.homeDir, env });
419
+ const [installed, accountResult] = await Promise.all([
420
+ Promise.all(TOOLS.map(async (tool) => ({
421
+ id: tool.id,
422
+ name: tool.name,
423
+ installed: await commandExists(tool.executable, env)
424
+ }))),
425
+ credential
426
+ ? fetchAccountStatus(credential, io, env)
427
+ : Promise.resolve({ state: "not_connected" }),
428
+ ]);
429
+ const connected = source !== "none" && accountResult.state !== "rejected";
430
+ if (output === "json") {
431
+ io.stdout.write(`${JSON.stringify({
432
+ connected,
433
+ credentialSource: source,
434
+ credentialPath: credentialFilePath({ homeDir: io.homeDir, env }),
435
+ accountStatus: accountResult.state,
436
+ account: accountResult.state === "available" ? accountResult.account : null,
437
+ lastSession: preferences.lastTool && preferences.lastModel
438
+ ? { tool: preferences.lastTool, model: preferences.lastModel }
439
+ : null,
440
+ tools: installed
441
+ }, null, 2)}\n`);
442
+ return 0;
244
443
  }
245
- else {
246
- io.stdout.write(`${ZRO_ENV_KEY}: not set\n`);
444
+ io.stdout.write(`${banner(colors)}\n\n`);
445
+ io.stdout.write(`${!connected ? colors.muted("◇") : colors.good("◆")} Connection `);
446
+ io.stdout.write(source === "none"
447
+ ? `${colors.muted("not logged in")}\n Run zro login\n`
448
+ : accountResult.state === "rejected"
449
+ ? `${colors.muted("API key rejected")}\n Run zro login --manual\n`
450
+ : `${colors.strong(source)} ${colors.muted(`· ${maskKey(credential)}`)}\n`);
451
+ if (accountResult.state === "available") {
452
+ printAccountStatus(accountResult.account, io, colors);
247
453
  }
248
- if (stored) {
249
- io.stdout.write(`Stored key: present (${maskKey(stored)})\n`);
250
- io.stdout.write(`Stored key path: ${filePath}\n`);
454
+ else if (accountResult.state === "unavailable") {
455
+ io.stdout.write(`${colors.muted("◇")} Account ${colors.muted("details unavailable")}\n`);
456
+ }
457
+ if (preferences.lastTool && preferences.lastModel) {
458
+ io.stdout.write(`${colors.accent("◆")} Last session ${describeTool(preferences.lastTool).name} ${colors.muted(`· ${preferences.lastModel}`)}\n`);
251
459
  }
252
460
  else {
253
- io.stdout.write(`Stored key: not found at ${filePath}\n`);
461
+ io.stdout.write(`${colors.muted("◇")} Last session ${colors.muted("none yet")}\n`);
254
462
  }
255
- if (envKey) {
256
- io.stdout.write(`Launch source: ${ZRO_ENV_KEY}\n`);
257
- return 0;
463
+ io.stdout.write("\nTools\n");
464
+ for (const tool of installed) {
465
+ io.stdout.write(` ${tool.installed ? colors.good("◆") : colors.muted("◇")} ${pad(tool.name, 13)} ${tool.installed ? "ready" : colors.muted("not installed")}\n`);
466
+ }
467
+ return 0;
468
+ }
469
+ async function fetchAccountStatus(apiKey, io, env) {
470
+ const fetcher = io.fetch ?? globalThis.fetch;
471
+ const endpointRoot = getAuthRoot(env);
472
+ try {
473
+ const response = await fetcher(`${endpointRoot}/api/cli/status`, {
474
+ headers: { Authorization: `Bearer ${apiKey}` },
475
+ signal: AbortSignal.timeout(5_000),
476
+ });
477
+ if (response.status === 401 || response.status === 403) {
478
+ await response.body?.cancel().catch(() => { });
479
+ return { state: "rejected" };
480
+ }
481
+ if (!response.ok) {
482
+ await response.body?.cancel().catch(() => { });
483
+ return { state: "unavailable" };
484
+ }
485
+ const account = parseAccountStatus(await responseJson(response));
486
+ return account ? { state: "available", account } : { state: "unavailable" };
258
487
  }
259
- if (stored) {
260
- io.stdout.write("Launch source: stored key\n");
488
+ catch {
489
+ return { state: "unavailable" };
490
+ }
491
+ }
492
+ function getAuthRoot(env) {
493
+ return (env.ZRO_AUTH_URL || env.ZRO_ENDPOINT_ROOT || ENDPOINT_ROOT).replace(/\/+$/, "");
494
+ }
495
+ function browserApprovalUrl(serverUrl, env) {
496
+ const publicRoot = env.ZRO_PUBLIC_URL || env.ZRO_AUTH_URL;
497
+ if (!publicRoot)
498
+ return serverUrl;
499
+ const url = new URL(serverUrl);
500
+ return new URL(`${url.pathname}${url.search}${url.hash}`, new URL(publicRoot)).toString();
501
+ }
502
+ function parseAccountStatus(value) {
503
+ const root = asRecord(value);
504
+ const key = asRecord(root.key);
505
+ const billing = asRecord(root.billing);
506
+ const packs = asRecord(billing.usagePacks);
507
+ const activity = asRecord(root.activity30d);
508
+ const planValue = billing.plan;
509
+ const plan = planValue === null ? null : asRecord(planValue);
510
+ if (typeof key.id !== "string" || typeof key.alias !== "string" ||
511
+ typeof billing.status !== "string" || typeof billing.currency !== "string" ||
512
+ !hasNumbers(packs, ["total", "used", "remaining"]) ||
513
+ !hasNumbers(billing, ["totalRemaining"]) ||
514
+ !hasNumbers(activity, [
515
+ "requests", "modelRequests", "toolCalls", "inputTokens", "outputTokens",
516
+ "totalTokens", "cacheReadInputTokens", "spend",
517
+ ]) ||
518
+ (plan !== null && (typeof plan.id !== "string" || typeof plan.name !== "string" ||
519
+ !hasNumbers(plan, ["allowance", "used", "remaining"]))))
520
+ return null;
521
+ return value;
522
+ }
523
+ function hasNumbers(value, keys) {
524
+ return keys.every((key) => typeof value[key] === "number" && Number.isFinite(value[key]));
525
+ }
526
+ function printAccountStatus(account, io, colors) {
527
+ const plan = account.billing.plan;
528
+ io.stdout.write("\nAccount\n");
529
+ io.stdout.write(` ${colors.good("◆")} Plan ${plan ? colors.strong(plan.name) : colors.muted("none")} ` +
530
+ `${colors.muted(`· ${account.billing.status}`)}\n`);
531
+ if (plan) {
532
+ io.stdout.write(` ${colors.good("◆")} Plan usage ${money(plan.used, account.billing.currency)} of ` +
533
+ `${money(plan.allowance, account.billing.currency)} · ${money(plan.remaining, account.billing.currency)} left\n`);
534
+ }
535
+ const packs = account.billing.usagePacks;
536
+ io.stdout.write(` ${packs.remaining > 0 ? colors.good("◆") : colors.muted("◇")} Usage packs ` +
537
+ `${money(packs.remaining, account.billing.currency)} left · ${money(packs.total, account.billing.currency)} total\n`);
538
+ io.stdout.write(` ${colors.good("◆")} Available ${money(account.billing.totalRemaining, account.billing.currency)} total\n`);
539
+ io.stdout.write(` ${colors.muted("◇")} Last 30 days ${formatInteger(account.activity30d.requests)} requests · ` +
540
+ `${formatInteger(account.activity30d.totalTokens)} tokens\n`);
541
+ }
542
+ function money(value, currency) {
543
+ return new Intl.NumberFormat("en-US", {
544
+ style: "currency",
545
+ currency,
546
+ minimumFractionDigits: 2,
547
+ maximumFractionDigits: 2,
548
+ }).format(value);
549
+ }
550
+ function formatInteger(value) {
551
+ return new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 }).format(value);
552
+ }
553
+ function models(output, io, colors) {
554
+ if (output === "json") {
555
+ io.stdout.write(`${JSON.stringify({ default: DEFAULT_MODEL, models: ZRO_MODELS }, null, 2)}\n`);
261
556
  return 0;
262
557
  }
263
- io.stdout.write("Launch source: none. Run zro login.\n");
264
- return 1;
558
+ io.stdout.write(`${banner(colors)}\n\nModels\n`);
559
+ for (const model of ZRO_MODELS) {
560
+ const isDefault = model.id === DEFAULT_MODEL;
561
+ io.stdout.write(`\n ${isDefault ? colors.accent("◆") : colors.muted("◇")} ${colors.strong(model.displayName)} ${colors.muted(model.id)}${isDefault ? colors.accent(" default") : ""}\n`);
562
+ io.stdout.write(` ${formatTokens(model.contextWindow)} context · ${formatTokens(model.maxOutputTokens)} max output · ${model.reasoning.levels.map((level) => level.id).join(" / ")}\n`);
563
+ }
564
+ io.stdout.write("\nChoose per session with -m, for example: zro codex -m glm-5.2\n");
565
+ return 0;
566
+ }
567
+ function printPreview(plan, output, io, secret, colors) {
568
+ const safeEnv = Object.fromEntries(Object.entries(plan.env ?? {}).map(([key, value]) => [key, redact(key, value, secret)]));
569
+ const result = {
570
+ tool: plan.tool,
571
+ model: plan.model,
572
+ command: plan.command,
573
+ args: plan.args,
574
+ environment: safeEnv,
575
+ files: (plan.files ?? []).map((file) => ({ path: file.path, persistent: Boolean(file.persistent) }))
576
+ };
577
+ if (output === "json") {
578
+ io.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
579
+ return;
580
+ }
581
+ io.stdout.write(`${banner(colors)}\n\n${colors.strong("Session preview")}\n`);
582
+ io.stdout.write(` Tool ${describeTool(plan.tool).name}\n`);
583
+ io.stdout.write(` Model ${modelName(plan.model)} ${colors.muted(`· ${plan.model}`)}\n`);
584
+ io.stdout.write(` Command ${shellPreview([plan.command, ...plan.args])}\n`);
585
+ const entries = Object.entries(safeEnv);
586
+ if (entries.length) {
587
+ io.stdout.write(" Environment\n");
588
+ for (const [key, value] of entries)
589
+ io.stdout.write(` ${key}=${value}\n`);
590
+ }
591
+ if (result.files.length) {
592
+ io.stdout.write(" Session files\n");
593
+ for (const file of result.files)
594
+ io.stdout.write(` ${file.path}${file.persistent ? " (persistent)" : ""}\n`);
595
+ }
596
+ io.stdout.write(`\n${colors.muted("Nothing was launched or written.")}\n`);
597
+ }
598
+ async function writeLaunchFiles(plan) {
599
+ for (const file of plan.files ?? []) {
600
+ await fs.mkdir(path.dirname(file.path), { recursive: true });
601
+ await fs.writeFile(file.path, file.contents, { mode: 0o600 });
602
+ }
603
+ }
604
+ async function spawnPlan(plan, io, env) {
605
+ const spawn = io.spawn ?? nodeSpawn;
606
+ const child = spawn(plan.command, plan.args, {
607
+ cwd: io.cwd,
608
+ env: { ...env, ...(plan.env ?? {}) },
609
+ stdio: "inherit"
610
+ });
611
+ return new Promise((resolve, reject) => {
612
+ child.once("error", reject);
613
+ child.once("exit", (code, signal) => {
614
+ if (typeof code === "number")
615
+ resolve(code);
616
+ else {
617
+ io.stderr.write(`Agent exited from signal ${signal ?? "unknown"}.\n`);
618
+ resolve(1);
619
+ }
620
+ });
621
+ });
622
+ }
623
+ function redact(key, value, secret) {
624
+ if (/KEY|TOKEN|SECRET|AUTH/i.test(key) || value.includes(secret))
625
+ return maskKey(value);
626
+ return value;
627
+ }
628
+ function shellPreview(argv) {
629
+ return argv.map((value) => /^[A-Za-z0-9_./:=@+-]+$/.test(value)
630
+ ? value
631
+ : `'${value.replace(/'/g, "'\\''")}'`).join(" ");
632
+ }
633
+ function compactPath(cwd, homeDir) {
634
+ return cwd === homeDir ? "~" : cwd.startsWith(`${homeDir}${path.sep}`) ? `~${cwd.slice(homeDir.length)}` : cwd;
635
+ }
636
+ function formatTokens(value) {
637
+ if (value >= 1_000_000)
638
+ return `${(value / 1_000_000).toFixed(1).replace(".0", "")}M`;
639
+ return `${Math.round(value / 1_000)}K`;
640
+ }
641
+ function pad(value, width) {
642
+ return value + " ".repeat(Math.max(1, width - value.length));
643
+ }
644
+ function messageOf(error) {
645
+ return error instanceof Error ? error.message : String(error);
646
+ }
647
+ async function openBrowserWithSystem(url, platform) {
648
+ const command = platform === "darwin" ? "open" : platform === "linux" ? "xdg-open" : null;
649
+ if (!command)
650
+ return false;
651
+ return new Promise((resolve) => {
652
+ const child = nodeSpawn(command, [url], { detached: true, stdio: "ignore" });
653
+ let settled = false;
654
+ child.once("error", () => {
655
+ if (settled)
656
+ return;
657
+ settled = true;
658
+ resolve(false);
659
+ });
660
+ child.once("spawn", () => {
661
+ if (settled)
662
+ return;
663
+ settled = true;
664
+ child.unref();
665
+ resolve(true);
666
+ });
667
+ });
668
+ }
669
+ async function responseJson(response) {
670
+ try {
671
+ return await response.json();
672
+ }
673
+ catch {
674
+ return {};
675
+ }
676
+ }
677
+ function validateDeviceLoginStart(value) {
678
+ const result = asRecord(value);
679
+ if (typeof result.deviceCode !== "string" ||
680
+ typeof result.userCode !== "string" ||
681
+ typeof result.verificationUri !== "string" ||
682
+ typeof result.verificationUriComplete !== "string" ||
683
+ typeof result.expiresIn !== "number" ||
684
+ typeof result.interval !== "number") {
685
+ throw new Error("Website returned an invalid login session.");
686
+ }
687
+ return result;
688
+ }
689
+ function errorFromPayload(value, fallback) {
690
+ const error = asRecord(value).error;
691
+ return typeof error === "string" && error ? error : fallback;
692
+ }
693
+ function asRecord(value) {
694
+ return value && typeof value === "object" && !Array.isArray(value)
695
+ ? value
696
+ : {};
265
697
  }
266
698
  function defaultIo() {
267
699
  return {
@@ -273,9 +705,7 @@ function defaultIo() {
273
705
  env: process.env,
274
706
  spawn: nodeSpawn,
275
707
  platform: process.platform,
276
- fetchLatestVersion: defaultFetchLatestVersion,
277
- execPath: process.execPath,
278
- scriptPath: process.argv[1]
708
+ version: PACKAGE_VERSION
279
709
  };
280
710
  }
281
711
  //# sourceMappingURL=run.js.map