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