@bendyline/gezel-cli 1.0.4 → 1.0.6
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/README.md +7 -3
- package/dist/bin/gezel-main.js +1972 -0
- package/dist/bin/gezel.js +4 -6264
- package/dist/handboek-export.js +16 -5
- package/dist/tui/index.js +1340 -234
- package/package.json +10 -10
|
@@ -0,0 +1,1972 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/bin/gezel.ts
|
|
4
|
+
import { basename as basename3, isAbsolute as isAbsolutePath, join as joinPath } from "path";
|
|
5
|
+
import { GEZEL_VERSION } from "@bendyline/gezel";
|
|
6
|
+
import {
|
|
7
|
+
streamChatEvents
|
|
8
|
+
} from "@bendyline/gezel-client";
|
|
9
|
+
import {
|
|
10
|
+
GezelClient as GezelClient2,
|
|
11
|
+
createTrustingFetch as createTrustingFetch2,
|
|
12
|
+
discoverOrSpawn as discoverOrSpawn2,
|
|
13
|
+
isProcessAlive as isProcessAlive2,
|
|
14
|
+
readRuntime as readRuntime2,
|
|
15
|
+
resolveDaemonEntry as resolveDaemonEntry2,
|
|
16
|
+
stopOwnedDaemon as stopOwnedDaemon2,
|
|
17
|
+
stopProcessByPid
|
|
18
|
+
} from "@bendyline/gezel-client/node";
|
|
19
|
+
import { Command } from "commander";
|
|
20
|
+
|
|
21
|
+
// src/connection.ts
|
|
22
|
+
import { createHash, randomUUID } from "crypto";
|
|
23
|
+
import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
24
|
+
import { homedir } from "os";
|
|
25
|
+
import { basename, dirname, join, resolve } from "path";
|
|
26
|
+
import { pickRandomNameWithGender } from "@bendyline/gezel";
|
|
27
|
+
import {
|
|
28
|
+
GezelSdkError,
|
|
29
|
+
authorizeLocal,
|
|
30
|
+
authorizeLocalOwner
|
|
31
|
+
} from "@bendyline/gezel-app-sdk";
|
|
32
|
+
import {
|
|
33
|
+
GezelApiError,
|
|
34
|
+
GezelClient,
|
|
35
|
+
createTrustingFetch,
|
|
36
|
+
discoverOrSpawn,
|
|
37
|
+
electronNativeBinCandidates,
|
|
38
|
+
isProcessAlive,
|
|
39
|
+
readRuntime,
|
|
40
|
+
readSystemServiceEndpoint,
|
|
41
|
+
resolveDaemonEntry,
|
|
42
|
+
stopOwnedDaemon,
|
|
43
|
+
systemSharedAssetsDir
|
|
44
|
+
} from "@bendyline/gezel-client/node";
|
|
45
|
+
import { gezelPaths } from "@bendyline/gezel/paths";
|
|
46
|
+
var CliError = class extends Error {
|
|
47
|
+
constructor(message) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "CliError";
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
function applyHome(globals) {
|
|
53
|
+
if (globals.home) process.env.GEZEL_HOME = resolve(globals.home);
|
|
54
|
+
if (!process.env.GEZEL_SHARED_ASSETS_DIR) {
|
|
55
|
+
const sharedAssets = systemSharedAssetsDir();
|
|
56
|
+
if (sharedAssets) process.env.GEZEL_SHARED_ASSETS_DIR = sharedAssets;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function validateGlobals(globals) {
|
|
60
|
+
if (globals.connect && globals.standalone) {
|
|
61
|
+
throw new CliError("--connect and --standalone cannot be used together.");
|
|
62
|
+
}
|
|
63
|
+
if (globals.token && !globals.connect) {
|
|
64
|
+
throw new CliError("--token requires --connect <url>.");
|
|
65
|
+
}
|
|
66
|
+
if (globals.connect) normalizeServiceUrl(globals.connect);
|
|
67
|
+
}
|
|
68
|
+
function normalizeServiceUrl(raw) {
|
|
69
|
+
let url;
|
|
70
|
+
try {
|
|
71
|
+
url = new URL(raw);
|
|
72
|
+
} catch {
|
|
73
|
+
throw new CliError(`Invalid --connect URL: ${raw}`);
|
|
74
|
+
}
|
|
75
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
76
|
+
throw new CliError("--connect must use an http:// or https:// URL.");
|
|
77
|
+
}
|
|
78
|
+
if (url.username || url.password) {
|
|
79
|
+
throw new CliError("--connect must not contain credentials; use --token instead.");
|
|
80
|
+
}
|
|
81
|
+
if (url.search || url.hash) {
|
|
82
|
+
throw new CliError("--connect must not contain a query string or fragment.");
|
|
83
|
+
}
|
|
84
|
+
return url.toString().replace(/\/+$/, "");
|
|
85
|
+
}
|
|
86
|
+
function resolveDevHome(globals) {
|
|
87
|
+
applyHome(globals);
|
|
88
|
+
if (process.env.GEZEL_HOME) return;
|
|
89
|
+
if (process.env.GEZEL_DEV === "1") {
|
|
90
|
+
process.env.GEZEL_HOME = join(homedir(), ".gezel-dev");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
async function connectOwned(globals) {
|
|
94
|
+
applyHome(globals);
|
|
95
|
+
const preferred = await connectPreferredService(globals);
|
|
96
|
+
if (preferred) return preferred.client;
|
|
97
|
+
const runtime = await readRuntime();
|
|
98
|
+
if (!runtime || !isProcessAlive(runtime.pid)) {
|
|
99
|
+
await prepareStandaloneAssets();
|
|
100
|
+
}
|
|
101
|
+
const authorized = await authorizeLocalOwner({
|
|
102
|
+
daemon: {
|
|
103
|
+
daemonEntry: resolveDaemonEntry(import.meta.url),
|
|
104
|
+
spawnIfMissing: true,
|
|
105
|
+
timeoutMs: 2e4,
|
|
106
|
+
preferCanonicalPort: await shouldPreferCanonicalPort(),
|
|
107
|
+
...process.env.GEZEL_HOME ? { home: process.env.GEZEL_HOME } : {}
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
const connected = await connectionFromAuthorization(
|
|
111
|
+
authorized,
|
|
112
|
+
"The local Gezel owner authorization"
|
|
113
|
+
);
|
|
114
|
+
return connected.client;
|
|
115
|
+
}
|
|
116
|
+
async function connectForTui(globals) {
|
|
117
|
+
applyHome(globals);
|
|
118
|
+
const preferred = await connectPreferredService(globals);
|
|
119
|
+
if (preferred) return { client: preferred.client };
|
|
120
|
+
const runtime = await readRuntime();
|
|
121
|
+
if (!runtime || !isProcessAlive(runtime.pid)) {
|
|
122
|
+
await prepareStandaloneAssets();
|
|
123
|
+
}
|
|
124
|
+
const result = await discoverOrSpawn({
|
|
125
|
+
daemonEntry: resolveDaemonEntry(import.meta.url),
|
|
126
|
+
detached: false,
|
|
127
|
+
stdio: "pipe",
|
|
128
|
+
env: cliUserDaemonEnv(process.env.GEZEL_HOME, await shouldPreferCanonicalPort()),
|
|
129
|
+
...process.env.GEZEL_HOME ? { home: process.env.GEZEL_HOME } : {},
|
|
130
|
+
timeoutMs: 2e4
|
|
131
|
+
});
|
|
132
|
+
result.child?.stdout?.resume();
|
|
133
|
+
result.child?.stderr?.resume();
|
|
134
|
+
if (result.outcome !== "spawned") return { client: result.client };
|
|
135
|
+
let stopPromise;
|
|
136
|
+
return {
|
|
137
|
+
client: result.client,
|
|
138
|
+
stop: () => {
|
|
139
|
+
stopPromise ??= stopOwnedDaemon(result.child);
|
|
140
|
+
return stopPromise;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function cliUserDaemonEnv(home, preferCanonicalPort, inherited = process.env) {
|
|
145
|
+
const {
|
|
146
|
+
GEZEL_PORT: _inheritedPort,
|
|
147
|
+
GEZEL_SERVICE_ROLE: _inheritedRole,
|
|
148
|
+
GEZEL_SYSTEM_SCOPE: _inheritedSystemScope,
|
|
149
|
+
...rest
|
|
150
|
+
} = inherited;
|
|
151
|
+
return {
|
|
152
|
+
...rest,
|
|
153
|
+
...home ? { GEZEL_HOME: home } : {},
|
|
154
|
+
...preferCanonicalPort ? {} : { GEZEL_PORT: "0" },
|
|
155
|
+
GEZEL_SERVICE_ROLE: "user"
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
async function shouldPreferCanonicalPort() {
|
|
159
|
+
if (process.env.GEZEL_HOME || process.env.GEZEL_DEV === "1") return false;
|
|
160
|
+
try {
|
|
161
|
+
return await readSystemServiceEndpoint() === null;
|
|
162
|
+
} catch {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function resolveStartPortEnv(portFlag, preferCanonical) {
|
|
167
|
+
if (portFlag !== void 0) return String(portFlag);
|
|
168
|
+
return preferCanonical ? void 0 : "0";
|
|
169
|
+
}
|
|
170
|
+
async function connectForRun(globals) {
|
|
171
|
+
applyHome(globals);
|
|
172
|
+
const preferred = await connectPreferredService(globals);
|
|
173
|
+
if (preferred) return { kind: "owned", ...preferred };
|
|
174
|
+
try {
|
|
175
|
+
const connected = await requestCliGrant({
|
|
176
|
+
storageKey: localTokenStorageKey(),
|
|
177
|
+
daemon: {
|
|
178
|
+
spawnIfMissing: false,
|
|
179
|
+
...process.env.GEZEL_HOME ? { home: process.env.GEZEL_HOME } : {}
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
const authorized = await connectionFromAuthorization(
|
|
183
|
+
connected,
|
|
184
|
+
"The approved Gezel CLI authorization"
|
|
185
|
+
);
|
|
186
|
+
return { kind: "owned", ...authorized };
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (!(error instanceof GezelSdkError) || error.code !== "daemon_not_running") {
|
|
189
|
+
throw cliGrantError(error, "the local Gezel daemon");
|
|
190
|
+
}
|
|
191
|
+
const runtime = await readRuntime();
|
|
192
|
+
if (runtime && isProcessAlive(runtime.pid)) {
|
|
193
|
+
throw new CliError(
|
|
194
|
+
`The local Gezel daemon (pid ${runtime.pid}) is running but did not answer at ${runtime.baseUrl}. Stop or repair it before retrying.`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
await prepareStandaloneAssets();
|
|
199
|
+
if (process.env.GEZEL_SKIP_SYSTEM_BOOTSTRAP === void 0) {
|
|
200
|
+
process.env.GEZEL_SKIP_SYSTEM_BOOTSTRAP = "1";
|
|
201
|
+
}
|
|
202
|
+
const { startService } = await import("@bendyline/gezel-service");
|
|
203
|
+
const svc = await startService({ port: 0, role: "user" });
|
|
204
|
+
const scheme = svc.cert ? "https" : "http";
|
|
205
|
+
const baseUrl = `${scheme}://127.0.0.1:${svc.port}`;
|
|
206
|
+
const client = new GezelClient({
|
|
207
|
+
baseUrl,
|
|
208
|
+
// Use the same scoped first-party credential written to runtime. The
|
|
209
|
+
// process-local daemon root is an implementation credential, not a
|
|
210
|
+
// client connection token.
|
|
211
|
+
token: svc.clientToken,
|
|
212
|
+
...svc.cert ? { fetch: createTrustingFetch({ cert: svc.cert.certPem }) } : {}
|
|
213
|
+
});
|
|
214
|
+
let stopPromise;
|
|
215
|
+
const stop = () => {
|
|
216
|
+
stopPromise ??= (async () => {
|
|
217
|
+
await svc.stop();
|
|
218
|
+
try {
|
|
219
|
+
const paths = gezelPaths();
|
|
220
|
+
const pid = (await readFile(paths.runtime.pid, "utf8")).trim();
|
|
221
|
+
if (pid === String(process.pid)) {
|
|
222
|
+
await rm(paths.runtime.dir, { recursive: true, force: true });
|
|
223
|
+
}
|
|
224
|
+
} catch {
|
|
225
|
+
}
|
|
226
|
+
})();
|
|
227
|
+
return stopPromise;
|
|
228
|
+
};
|
|
229
|
+
return { kind: "owned", client, baseUrl, stop };
|
|
230
|
+
}
|
|
231
|
+
var CLI_APP_ID_PREFIX = "gezel-cli";
|
|
232
|
+
var CLI_APPROVAL_TIMEOUT_SEC = 300;
|
|
233
|
+
function isSystemProductServiceRole(role) {
|
|
234
|
+
return role === void 0 || role === "legacy-full";
|
|
235
|
+
}
|
|
236
|
+
function shouldTrySystemService(globals, env2 = process.env) {
|
|
237
|
+
return !globals.connect && !globals.standalone && !globals.home && !env2.GEZEL_HOME && env2.GEZEL_DEV !== "1";
|
|
238
|
+
}
|
|
239
|
+
async function findHealthySystemService(globals, deps = {}) {
|
|
240
|
+
if (!shouldTrySystemService(globals)) return null;
|
|
241
|
+
const endpoint = await (deps.readEndpoint ?? readSystemServiceEndpoint)();
|
|
242
|
+
if (!endpoint) return null;
|
|
243
|
+
const fetchImpl = endpoint.cert ? createTrustingFetch({ cert: endpoint.cert }) : globalThis.fetch;
|
|
244
|
+
const controller = new AbortController();
|
|
245
|
+
const timeout = setTimeout(() => controller.abort(), 1500);
|
|
246
|
+
timeout.unref?.();
|
|
247
|
+
try {
|
|
248
|
+
const health = deps.probeHealth ? await deps.probeHealth({ endpoint, fetch: fetchImpl, signal: controller.signal }) : await new GezelClient({
|
|
249
|
+
baseUrl: endpoint.baseUrl,
|
|
250
|
+
token: "",
|
|
251
|
+
fetch: fetchImpl
|
|
252
|
+
}).health(controller.signal);
|
|
253
|
+
if (!isSystemProductServiceRole(health.serviceRole)) return null;
|
|
254
|
+
return {
|
|
255
|
+
baseUrl: endpoint.baseUrl,
|
|
256
|
+
fetch: fetchImpl,
|
|
257
|
+
port: endpoint.port,
|
|
258
|
+
home: endpoint.home
|
|
259
|
+
};
|
|
260
|
+
} catch {
|
|
261
|
+
return null;
|
|
262
|
+
} finally {
|
|
263
|
+
clearTimeout(timeout);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
async function describeMachineEngineBroker(deps = {}) {
|
|
267
|
+
let endpoint = null;
|
|
268
|
+
try {
|
|
269
|
+
endpoint = await (deps.readEndpoint ?? readSystemServiceEndpoint)();
|
|
270
|
+
} catch {
|
|
271
|
+
endpoint = null;
|
|
272
|
+
}
|
|
273
|
+
if (!endpoint) return { present: false };
|
|
274
|
+
const fetchImpl = endpoint.cert ? createTrustingFetch({ cert: endpoint.cert }) : globalThis.fetch;
|
|
275
|
+
const controller = new AbortController();
|
|
276
|
+
const timeout = setTimeout(() => controller.abort(), 1500);
|
|
277
|
+
timeout.unref?.();
|
|
278
|
+
try {
|
|
279
|
+
const health = deps.probeHealth ? await deps.probeHealth({ endpoint, fetch: fetchImpl, signal: controller.signal }) : await new GezelClient({
|
|
280
|
+
baseUrl: endpoint.baseUrl,
|
|
281
|
+
token: "",
|
|
282
|
+
fetch: fetchImpl
|
|
283
|
+
}).health(controller.signal);
|
|
284
|
+
return {
|
|
285
|
+
present: true,
|
|
286
|
+
healthy: true,
|
|
287
|
+
baseUrl: endpoint.baseUrl,
|
|
288
|
+
port: endpoint.port,
|
|
289
|
+
...health.serviceRole !== void 0 ? { serviceRole: health.serviceRole } : {},
|
|
290
|
+
version: health.version,
|
|
291
|
+
...health.startedAt !== void 0 ? { startedAt: health.startedAt } : {}
|
|
292
|
+
};
|
|
293
|
+
} catch {
|
|
294
|
+
return { present: true, healthy: false, baseUrl: endpoint.baseUrl, port: endpoint.port };
|
|
295
|
+
} finally {
|
|
296
|
+
clearTimeout(timeout);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async function connectPreferredService(globals) {
|
|
300
|
+
validateGlobals(globals);
|
|
301
|
+
if (globals.connect) {
|
|
302
|
+
const baseUrl = normalizeServiceUrl(globals.connect);
|
|
303
|
+
return connectWithCliGrant({
|
|
304
|
+
baseUrl,
|
|
305
|
+
fetch: globalThis.fetch,
|
|
306
|
+
// Preserve the historical per-origin key for existing remote grants.
|
|
307
|
+
storageKey: baseUrl,
|
|
308
|
+
...globals.token ? { token: globals.token } : {}
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
const system = await findHealthySystemService(globals);
|
|
312
|
+
if (!system) return null;
|
|
313
|
+
return connectWithCliGrant({
|
|
314
|
+
baseUrl: system.baseUrl,
|
|
315
|
+
fetch: system.fetch,
|
|
316
|
+
storageKey: system.baseUrl
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
async function prepareStandaloneAssets() {
|
|
320
|
+
if (process.env.GEZEL_MOCK_PROVIDER === "1" || process.env.GEZEL_NATIVE_BIN_DIR) return;
|
|
321
|
+
const candidates = electronNativeBinCandidates();
|
|
322
|
+
if (candidates.length === 0) return;
|
|
323
|
+
const { reuseVerifiedElectronNativeBinaries } = await import("@bendyline/gezel-service");
|
|
324
|
+
await reuseVerifiedElectronNativeBinaries({ candidates });
|
|
325
|
+
}
|
|
326
|
+
async function connectWithCliGrant(input) {
|
|
327
|
+
if (input.token) {
|
|
328
|
+
if (!input.baseUrl) throw new CliError("--token requires an explicit service URL.");
|
|
329
|
+
const client = buildCliClient(input.baseUrl, input.token, input.fetch ?? globalThis.fetch);
|
|
330
|
+
await validateCliClient(client, "The supplied --token");
|
|
331
|
+
return { client, baseUrl: input.baseUrl };
|
|
332
|
+
}
|
|
333
|
+
try {
|
|
334
|
+
const authorized = await requestCliGrant(input);
|
|
335
|
+
return await connectionFromAuthorization(authorized, "The approved Gezel CLI authorization");
|
|
336
|
+
} catch (error) {
|
|
337
|
+
throw cliGrantError(error, input.baseUrl ?? "the local Gezel daemon");
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async function requestCliGrant(input) {
|
|
341
|
+
const appId = await resolveCliAppId();
|
|
342
|
+
return authorizeLocal({
|
|
343
|
+
appId,
|
|
344
|
+
appName: "Gezel CLI",
|
|
345
|
+
scopes: ["cli"],
|
|
346
|
+
...input.baseUrl ? { baseUrl: input.baseUrl } : {},
|
|
347
|
+
...input.fetch ? { fetch: input.fetch } : {},
|
|
348
|
+
...input.daemon ? { daemon: input.daemon } : {},
|
|
349
|
+
approvalTimeoutSec: CLI_APPROVAL_TIMEOUT_SEC,
|
|
350
|
+
tokenStorage: fileTokenStorage(input.storageKey),
|
|
351
|
+
onVerificationCode: (code) => {
|
|
352
|
+
console.error(
|
|
353
|
+
`Connecting Gezel CLI.
|
|
354
|
+
Open the Gezel app and enter code ${code} to approve this connection. Waiting for approval\u2026`
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
async function connectionFromAuthorization(authorized, label) {
|
|
360
|
+
const client = clientFromAuthorization(authorized);
|
|
361
|
+
await validateCliClient(client, label);
|
|
362
|
+
return { client, baseUrl: authorized.baseUrl };
|
|
363
|
+
}
|
|
364
|
+
function clientFromAuthorization(authorized) {
|
|
365
|
+
return buildCliClient(authorized.baseUrl, authorized.token, authorized.fetch);
|
|
366
|
+
}
|
|
367
|
+
function cliGrantError(error, target) {
|
|
368
|
+
if (error instanceof CliError) return error;
|
|
369
|
+
if (error instanceof GezelSdkError) {
|
|
370
|
+
if (error.code === "already_connected") {
|
|
371
|
+
return new CliError(
|
|
372
|
+
"Gezel already has a CLI authorization, but this terminal no longer has its token. Revoke \u201CGezel CLI\u201D in Settings \u2192 Connected Apps, then run this command again."
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
if (error.code === "user_denied") {
|
|
376
|
+
return new CliError("Gezel CLI access was denied in the Gezel app.");
|
|
377
|
+
}
|
|
378
|
+
if (error.code === "approval_timeout") {
|
|
379
|
+
return new CliError(
|
|
380
|
+
`Timed out after ${CLI_APPROVAL_TIMEOUT_SEC / 60} minutes waiting for Gezel CLI approval.`
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
if (error.code === "grant_expired") {
|
|
384
|
+
return new CliError(
|
|
385
|
+
"The Gezel CLI approval request expired. Run the command again to get a new code."
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
if (error.code === "daemon_not_running") {
|
|
389
|
+
return new CliError(
|
|
390
|
+
"No local Gezel daemon is running. Start the Gezel app or run `gezel start`, then try again."
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return new CliError(
|
|
395
|
+
`Could not authorize Gezel CLI against ${target}: ${error instanceof Error ? error.message : String(error)}`
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
async function resolveCliAppId() {
|
|
399
|
+
const dir = join(gezelPaths().root, "cli");
|
|
400
|
+
const file = join(dir, "client-id");
|
|
401
|
+
const readId = async () => {
|
|
402
|
+
try {
|
|
403
|
+
const id = (await readFile(file, "utf8")).trim();
|
|
404
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id) ? id.toLowerCase() : null;
|
|
405
|
+
} catch {
|
|
406
|
+
return null;
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
const existing = await readId();
|
|
410
|
+
if (existing) return `${CLI_APP_ID_PREFIX}.${existing}`;
|
|
411
|
+
const created = randomUUID();
|
|
412
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
413
|
+
try {
|
|
414
|
+
await writeFile(file, `${created}
|
|
415
|
+
`, {
|
|
416
|
+
encoding: "utf8",
|
|
417
|
+
mode: 384,
|
|
418
|
+
flag: "wx"
|
|
419
|
+
});
|
|
420
|
+
} catch (error) {
|
|
421
|
+
const raced = await readId();
|
|
422
|
+
if (raced) return `${CLI_APP_ID_PREFIX}.${raced}`;
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
await chmod(file, 384).catch(() => {
|
|
426
|
+
});
|
|
427
|
+
return `${CLI_APP_ID_PREFIX}.${created}`;
|
|
428
|
+
}
|
|
429
|
+
function buildCliClient(baseUrl, token, fetchImpl) {
|
|
430
|
+
return new GezelClient({ baseUrl, token, fetch: fetchImpl });
|
|
431
|
+
}
|
|
432
|
+
async function validateCliClient(client, label) {
|
|
433
|
+
try {
|
|
434
|
+
await client.getConfig();
|
|
435
|
+
} catch (error) {
|
|
436
|
+
if (error instanceof GezelApiError && (error.status === 401 || error.status === 403)) {
|
|
437
|
+
throw new CliError(
|
|
438
|
+
`${label} does not have CLI access. Revoke \u201CGezel CLI\u201D in Settings \u2192 Connected Apps and authorize it again.`
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
throw error;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
function fileTokenStorage(storageKey) {
|
|
445
|
+
const targetKey = createHash("sha256").update(storageKey).digest("hex");
|
|
446
|
+
const file = join(gezelPaths().root, "cli", "tokens", `${targetKey}.json`);
|
|
447
|
+
const read = async () => {
|
|
448
|
+
try {
|
|
449
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
450
|
+
} catch {
|
|
451
|
+
return {};
|
|
452
|
+
}
|
|
453
|
+
};
|
|
454
|
+
const deleteToken = async (appId) => {
|
|
455
|
+
const data = await read();
|
|
456
|
+
delete data[appId];
|
|
457
|
+
await mkdir(dirname(file), { recursive: true, mode: 448 });
|
|
458
|
+
await writeFile(file, `${JSON.stringify(data, null, 2)}
|
|
459
|
+
`, {
|
|
460
|
+
encoding: "utf8",
|
|
461
|
+
mode: 384
|
|
462
|
+
});
|
|
463
|
+
await chmod(file, 384).catch(() => {
|
|
464
|
+
});
|
|
465
|
+
};
|
|
466
|
+
return {
|
|
467
|
+
async load(appId) {
|
|
468
|
+
return (await read())[appId] ?? null;
|
|
469
|
+
},
|
|
470
|
+
async save(appId, token) {
|
|
471
|
+
const data = await read();
|
|
472
|
+
data[appId] = token;
|
|
473
|
+
await mkdir(dirname(file), { recursive: true, mode: 448 });
|
|
474
|
+
await writeFile(file, `${JSON.stringify(data, null, 2)}
|
|
475
|
+
`, {
|
|
476
|
+
encoding: "utf8",
|
|
477
|
+
mode: 384
|
|
478
|
+
});
|
|
479
|
+
await chmod(file, 384).catch(() => {
|
|
480
|
+
});
|
|
481
|
+
},
|
|
482
|
+
delete: deleteToken
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
function localTokenStorageKey() {
|
|
486
|
+
return "local-user-daemon";
|
|
487
|
+
}
|
|
488
|
+
async function ensureProjectForFolder(client, folderPath) {
|
|
489
|
+
const wd = resolve(folderPath);
|
|
490
|
+
const eq = (a, b) => !!a && (process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
491
|
+
const { projects } = await client.listProjects();
|
|
492
|
+
const exact = projects.find((p) => eq(p.workingDir, wd));
|
|
493
|
+
if (exact) return exact.id;
|
|
494
|
+
const name = basename(wd) || "workspace";
|
|
495
|
+
const orphan = projects.find((p) => !p.workingDir && p.name === name);
|
|
496
|
+
if (orphan) {
|
|
497
|
+
await client.setProjectWorkingDir(orphan.id, wd);
|
|
498
|
+
return orphan.id;
|
|
499
|
+
}
|
|
500
|
+
const created = await client.createProject({
|
|
501
|
+
name,
|
|
502
|
+
description: `CLI workspace at ${wd}`,
|
|
503
|
+
about: `${name} \u2014 working directory ${wd}. Fill in who this project is for, what's in scope, and what's explicitly out of scope.`,
|
|
504
|
+
missionObjectives: `${name} \u2014 fill in concrete success criteria for this project.`,
|
|
505
|
+
mode: "solo",
|
|
506
|
+
workingDir: wd
|
|
507
|
+
});
|
|
508
|
+
return created.id;
|
|
509
|
+
}
|
|
510
|
+
async function ensureCliProjectLead(client, projectId) {
|
|
511
|
+
const project = await client.getProject(projectId);
|
|
512
|
+
if (project.voormanGezelId) return project.voormanGezelId;
|
|
513
|
+
if (project.mode === "solo") {
|
|
514
|
+
if (project.gezelIds?.[0]) return project.gezelIds[0];
|
|
515
|
+
if (project.workingDir) {
|
|
516
|
+
const { gezels: gezels2 } = await client.listGezels();
|
|
517
|
+
let builder = gezels2.find(
|
|
518
|
+
(gezel) => gezel.templateId === "builder" || gezel.role?.trim().toLowerCase() === "builder"
|
|
519
|
+
);
|
|
520
|
+
if (!builder) {
|
|
521
|
+
const { name, gender } = pickRandomNameWithGender();
|
|
522
|
+
builder = await client.createGezelFromTemplate("builder", { name, gender });
|
|
523
|
+
}
|
|
524
|
+
const updated2 = await client.updateProject(projectId, { voormanGezelId: builder.id });
|
|
525
|
+
if (!updated2.voormanGezelId) {
|
|
526
|
+
throw new CliError(`project "${updated2.name}" has no Builder`);
|
|
527
|
+
}
|
|
528
|
+
return updated2.voormanGezelId;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const { gezels } = await client.listGezels();
|
|
532
|
+
let voorman = gezels.find(
|
|
533
|
+
(gezel) => gezel.templateId === "voorman" || gezel.role?.trim().toLowerCase() === "voorman"
|
|
534
|
+
);
|
|
535
|
+
if (!voorman) {
|
|
536
|
+
const { name, gender } = pickRandomNameWithGender();
|
|
537
|
+
voorman = await client.createGezelFromTemplate("voorman", { name, gender });
|
|
538
|
+
}
|
|
539
|
+
const updated = await client.updateProject(projectId, { voormanGezelId: voorman.id });
|
|
540
|
+
if (!updated.voormanGezelId) {
|
|
541
|
+
throw new CliError(`project "${updated.name}" has no voorman`);
|
|
542
|
+
}
|
|
543
|
+
return updated.voormanGezelId;
|
|
544
|
+
}
|
|
545
|
+
async function resolveRunProject(client, globals) {
|
|
546
|
+
const p = globals.project;
|
|
547
|
+
const folder = p === void 0 || p === true || p === false ? process.cwd() : p;
|
|
548
|
+
return ensureProjectForFolder(client, folder);
|
|
549
|
+
}
|
|
550
|
+
async function resolveTuiProject(client, globals) {
|
|
551
|
+
const p = globals.project;
|
|
552
|
+
const folder = p === void 0 || p === true || p === false ? process.cwd() : p;
|
|
553
|
+
return ensureProjectForFolder(client, folder);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// src/engagement-mode.ts
|
|
557
|
+
var CLI_ENGAGEMENT_MODES = [
|
|
558
|
+
{
|
|
559
|
+
name: "read-only",
|
|
560
|
+
mode: "off",
|
|
561
|
+
label: "Read-only",
|
|
562
|
+
description: "AI is paused; browse projects and history without starting AI work."
|
|
563
|
+
},
|
|
564
|
+
{
|
|
565
|
+
name: "reactive",
|
|
566
|
+
mode: "reactive",
|
|
567
|
+
label: "Reactive",
|
|
568
|
+
description: "AI replies to messages; autonomous task work stays paused."
|
|
569
|
+
},
|
|
570
|
+
{
|
|
571
|
+
name: "reactive+tasks",
|
|
572
|
+
mode: "scheduled",
|
|
573
|
+
label: "Reactive + tasks",
|
|
574
|
+
description: "Messages, task work, and schedules run without proactive nudges."
|
|
575
|
+
},
|
|
576
|
+
{
|
|
577
|
+
name: "full-play",
|
|
578
|
+
mode: "proactive",
|
|
579
|
+
label: "Full play",
|
|
580
|
+
description: "Everything runs, including proactive nudges and cross-gezel work."
|
|
581
|
+
}
|
|
582
|
+
];
|
|
583
|
+
var MODE_ALIASES = {
|
|
584
|
+
"read-only": "off",
|
|
585
|
+
readonly: "off",
|
|
586
|
+
off: "off",
|
|
587
|
+
reactive: "reactive",
|
|
588
|
+
"reactive-only": "reactive",
|
|
589
|
+
"reactive+tasks": "scheduled",
|
|
590
|
+
"tasks+reactive": "scheduled",
|
|
591
|
+
scheduled: "scheduled",
|
|
592
|
+
"full-play": "proactive",
|
|
593
|
+
fullplay: "proactive",
|
|
594
|
+
proactive: "proactive"
|
|
595
|
+
};
|
|
596
|
+
function parseCliEngagementMode(input) {
|
|
597
|
+
const normalized = input.trim().toLowerCase().replace(/\s*\+\s*/g, "+").replace(/[\s_]+/g, "-");
|
|
598
|
+
return MODE_ALIASES[normalized] ?? null;
|
|
599
|
+
}
|
|
600
|
+
function cliEngagementModeOption(mode) {
|
|
601
|
+
return CLI_ENGAGEMENT_MODES.find((option) => option.mode === (mode ?? "proactive"));
|
|
602
|
+
}
|
|
603
|
+
var CLI_ENGAGEMENT_MODE_USAGE = CLI_ENGAGEMENT_MODES.map((option) => option.name).join(
|
|
604
|
+
"|"
|
|
605
|
+
);
|
|
606
|
+
|
|
607
|
+
// src/generate.ts
|
|
608
|
+
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
|
|
609
|
+
import { basename as basename2, dirname as dirname2, resolve as resolve2 } from "path";
|
|
610
|
+
async function resolvePromptText(parts, file, label) {
|
|
611
|
+
const inline = (parts ?? []).join(" ").trim();
|
|
612
|
+
if (file) {
|
|
613
|
+
if (inline) throw new CliError(`provide either ${label} text or --file, not both.`);
|
|
614
|
+
let raw;
|
|
615
|
+
try {
|
|
616
|
+
raw = await readFile2(resolve2(file), "utf8");
|
|
617
|
+
} catch (err) {
|
|
618
|
+
throw new CliError(`could not read --file "${file}": ${err.message}`);
|
|
619
|
+
}
|
|
620
|
+
const text = raw.trim();
|
|
621
|
+
if (!text) throw new CliError(`--file "${file}" is empty.`);
|
|
622
|
+
return text;
|
|
623
|
+
}
|
|
624
|
+
if (!inline) throw new CliError(`provide ${label} text as the argument, or --file <path>.`);
|
|
625
|
+
return inline;
|
|
626
|
+
}
|
|
627
|
+
function intOpt(name, v) {
|
|
628
|
+
if (v === void 0) return void 0;
|
|
629
|
+
const n = Number.parseInt(v, 10);
|
|
630
|
+
if (!Number.isInteger(n)) throw new CliError(`--${name} must be an integer (got "${v}").`);
|
|
631
|
+
return n;
|
|
632
|
+
}
|
|
633
|
+
function floatOpt(name, v) {
|
|
634
|
+
if (v === void 0) return void 0;
|
|
635
|
+
const n = Number.parseFloat(v);
|
|
636
|
+
if (!Number.isFinite(n)) throw new CliError(`--${name} must be a number (got "${v}").`);
|
|
637
|
+
return n;
|
|
638
|
+
}
|
|
639
|
+
async function saveArtifact(client, projectId, artifactPath, output) {
|
|
640
|
+
const rel = artifactPath.replace(/^artifacts\//, "");
|
|
641
|
+
const blob = await client.fetchProjectArtifactBlob(projectId, rel);
|
|
642
|
+
const bytes = Buffer.from(await blob.arrayBuffer());
|
|
643
|
+
const dest = output ? resolve2(output) : resolve2(process.cwd(), basename2(artifactPath));
|
|
644
|
+
await mkdir2(dirname2(dest), { recursive: true });
|
|
645
|
+
await writeFile2(dest, bytes);
|
|
646
|
+
return dest;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// src/tui/bootstrap.ts
|
|
650
|
+
import {
|
|
651
|
+
computeModelFit,
|
|
652
|
+
formatModelAttribution,
|
|
653
|
+
isMoEFromTags,
|
|
654
|
+
isRecommendedModel,
|
|
655
|
+
mediaModelFits,
|
|
656
|
+
pickRecommendedModel
|
|
657
|
+
} from "@bendyline/gezel";
|
|
658
|
+
var NATIVE_TOOLKIT = [
|
|
659
|
+
"uv",
|
|
660
|
+
"sd-server",
|
|
661
|
+
"whisper-server",
|
|
662
|
+
"llama-server"
|
|
663
|
+
];
|
|
664
|
+
|
|
665
|
+
// src/native-command.ts
|
|
666
|
+
var NATIVE_VARIANTS = ["cuda", "vulkan", "metal", "cpu"];
|
|
667
|
+
function parseNativeVariant(value) {
|
|
668
|
+
if (value === void 0) return void 0;
|
|
669
|
+
if (NATIVE_VARIANTS.includes(value)) return value;
|
|
670
|
+
throw new CliError(`--variant must be one of ${NATIVE_VARIANTS.join(", ")} (got "${value}")`);
|
|
671
|
+
}
|
|
672
|
+
function formatNativeStatus(status) {
|
|
673
|
+
const installed = new Set(
|
|
674
|
+
status.engines.filter((engine) => engine.installed).map((engine) => engine.name)
|
|
675
|
+
);
|
|
676
|
+
const toolkitInstalled = NATIVE_TOOLKIT.filter((engine) => installed.has(engine)).length;
|
|
677
|
+
return [
|
|
678
|
+
`release: native-v${status.release} (${status.pinned ? "verified pin" : "unpinned \u2014 downloads disabled"})`,
|
|
679
|
+
`platform: ${status.platformKey ?? "unsupported \u2014 downloads unavailable"}`,
|
|
680
|
+
`llama backend: ${status.llamaBackend ?? "automatic"}`,
|
|
681
|
+
`toolkit: ${toolkitInstalled}/${NATIVE_TOOLKIT.length} installed`
|
|
682
|
+
].join("\n");
|
|
683
|
+
}
|
|
684
|
+
function formatNativeList(status) {
|
|
685
|
+
const rows = status.engines.map((engine) => {
|
|
686
|
+
const state = engine.installed ? "installed" : "missing";
|
|
687
|
+
return `${engine.name.padEnd(18)} ${state.padEnd(10)}${engine.path ? ` ${engine.path}` : ""}`;
|
|
688
|
+
});
|
|
689
|
+
return [
|
|
690
|
+
`native-v${status.release} \xB7 ${status.platformKey ?? "unsupported platform"} \xB7 ${status.pinned ? "verified" : "unpinned"}`,
|
|
691
|
+
"engine status path",
|
|
692
|
+
...rows
|
|
693
|
+
].join("\n");
|
|
694
|
+
}
|
|
695
|
+
async function installNativeToolkit(client, options) {
|
|
696
|
+
const status = await client.getNativeEngineStatus();
|
|
697
|
+
if (!status.pinned) {
|
|
698
|
+
throw new CliError(
|
|
699
|
+
"native downloads are disabled because the connected service has no verified native release pin."
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
if (!status.platformKey) {
|
|
703
|
+
throw new CliError(
|
|
704
|
+
`native downloads are unavailable on ${process.platform}/${process.arch}: no supported build exists.`
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
const llamaVariant = options.variant ?? status.llamaBackend;
|
|
708
|
+
for (const engine of NATIVE_TOOLKIT) {
|
|
709
|
+
await ensureOneEngine(client, engine, llamaVariant, options.output);
|
|
710
|
+
}
|
|
711
|
+
return client.getNativeEngineStatus();
|
|
712
|
+
}
|
|
713
|
+
async function ensureOneEngine(client, engine, llamaVariant, output) {
|
|
714
|
+
let terminalError;
|
|
715
|
+
let progressLineOpen = false;
|
|
716
|
+
const onEvent = (event) => {
|
|
717
|
+
if (event.type === "progress") {
|
|
718
|
+
progressLineOpen = true;
|
|
719
|
+
output.writeProgress(`\r${formatProgress(engine, event.bytesWritten, event.totalBytes)}`);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (progressLineOpen) {
|
|
723
|
+
output.writeProgress("\n");
|
|
724
|
+
progressLineOpen = false;
|
|
725
|
+
}
|
|
726
|
+
switch (event.type) {
|
|
727
|
+
case "retrying":
|
|
728
|
+
output.writeProgress(
|
|
729
|
+
`${engine}: retry ${event.attempt}/${event.maxAttempts} in ${event.delayMs}ms \u2014 ${event.reason}
|
|
730
|
+
`
|
|
731
|
+
);
|
|
732
|
+
break;
|
|
733
|
+
case "verifying":
|
|
734
|
+
output.writeProgress(`${engine}: verifying ${event.what}
|
|
735
|
+
`);
|
|
736
|
+
break;
|
|
737
|
+
case "done":
|
|
738
|
+
output.writeProgress(
|
|
739
|
+
`${engine}: ready${event.cached ? " (cached)" : ` \u2014 ${event.binPath}`}
|
|
740
|
+
`
|
|
741
|
+
);
|
|
742
|
+
break;
|
|
743
|
+
case "error":
|
|
744
|
+
terminalError = event.error;
|
|
745
|
+
output.writeProgress(`${engine}: error \u2014 ${event.error}
|
|
746
|
+
`);
|
|
747
|
+
break;
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
try {
|
|
751
|
+
await client.ensureNativeEngine(
|
|
752
|
+
engine,
|
|
753
|
+
onEvent,
|
|
754
|
+
engine === "llama-server" ? llamaVariant : void 0
|
|
755
|
+
);
|
|
756
|
+
} catch (error) {
|
|
757
|
+
if (progressLineOpen) output.writeProgress("\n");
|
|
758
|
+
throw new CliError(
|
|
759
|
+
`native install failed for ${engine}: ${terminalError ?? errorMessage(error)}`
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
if (progressLineOpen) output.writeProgress("\n");
|
|
763
|
+
if (terminalError) {
|
|
764
|
+
throw new CliError(`native install failed for ${engine}: ${terminalError}`);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
function formatProgress(engine, written, total) {
|
|
768
|
+
if (total <= 0) return `${engine}: ${formatBytes(written)} downloaded`;
|
|
769
|
+
const pct = Math.min(100, Math.floor(written / total * 100));
|
|
770
|
+
return `${engine}: ${String(pct).padStart(3)}% ${formatBytes(written)}/${formatBytes(total)}`;
|
|
771
|
+
}
|
|
772
|
+
function formatBytes(bytes) {
|
|
773
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
774
|
+
if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} KiB`;
|
|
775
|
+
if (bytes < 1024 ** 3) return `${(bytes / 1024 ** 2).toFixed(1)} MiB`;
|
|
776
|
+
return `${(bytes / 1024 ** 3).toFixed(2)} GiB`;
|
|
777
|
+
}
|
|
778
|
+
function errorMessage(error) {
|
|
779
|
+
return error instanceof Error ? error.message : String(error);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// src/signal-cleanup.ts
|
|
783
|
+
function installSignalCleanup(cleanup, options = {}) {
|
|
784
|
+
if (!cleanup) return () => {
|
|
785
|
+
};
|
|
786
|
+
const host = options.host ?? process;
|
|
787
|
+
let cleanupPromise;
|
|
788
|
+
const onSignal = (signal) => {
|
|
789
|
+
host.exitCode = signal === "SIGINT" ? 130 : 143;
|
|
790
|
+
cleanupPromise ??= cleanup().catch((error) => {
|
|
791
|
+
options.onError?.(error);
|
|
792
|
+
host.exitCode = 1;
|
|
793
|
+
});
|
|
794
|
+
};
|
|
795
|
+
const onSigint = () => onSignal("SIGINT");
|
|
796
|
+
const onSigterm = () => onSignal("SIGTERM");
|
|
797
|
+
host.on("SIGINT", onSigint);
|
|
798
|
+
host.on("SIGTERM", onSigterm);
|
|
799
|
+
return () => {
|
|
800
|
+
host.off("SIGINT", onSigint);
|
|
801
|
+
host.off("SIGTERM", onSigterm);
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// src/storage-format.ts
|
|
806
|
+
function formatBytes2(bytes) {
|
|
807
|
+
if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
|
808
|
+
if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(0)} MB`;
|
|
809
|
+
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
|
810
|
+
return `${bytes} B`;
|
|
811
|
+
}
|
|
812
|
+
function formatStorageSummary(summary) {
|
|
813
|
+
const lines = [`Gezel storage in ${summary.home}`, ""];
|
|
814
|
+
lines.push(...group("Can be downloaded again", summary, "redownloadable"));
|
|
815
|
+
lines.push(...group("Your content", summary, "user-content"));
|
|
816
|
+
lines.push(
|
|
817
|
+
...group("Program files (the uninstaller removes these)", summary, "uninstaller-owned")
|
|
818
|
+
);
|
|
819
|
+
lines.push(
|
|
820
|
+
`Total: ${formatBytes2(summary.redownloadableBytes)} re-downloadable, ${formatBytes2(summary.userContentBytes)} your content`
|
|
821
|
+
);
|
|
822
|
+
const external = summary.categories.flatMap((c) => c.external).sort((a, b) => a.path.localeCompare(b.path));
|
|
823
|
+
if (external.length > 0) {
|
|
824
|
+
lines.push("", "Outside the Gezel folder \u2014 not measured or removed by Gezel:");
|
|
825
|
+
for (const entry of external) {
|
|
826
|
+
lines.push(` ${entry.path}`);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
return lines.join("\n");
|
|
830
|
+
}
|
|
831
|
+
function group(heading, summary, cls) {
|
|
832
|
+
const categories = summary.categories.filter((c) => c.class === cls && c.bytes > 0).sort((a, b) => b.bytes - a.bytes);
|
|
833
|
+
if (categories.length === 0) return [];
|
|
834
|
+
const lines = [`${heading}:`];
|
|
835
|
+
for (const c of categories) {
|
|
836
|
+
lines.push(` ${pad(formatBytes2(c.bytes), 10)} ${c.label}`);
|
|
837
|
+
}
|
|
838
|
+
lines.push("");
|
|
839
|
+
return lines;
|
|
840
|
+
}
|
|
841
|
+
function pad(text, width) {
|
|
842
|
+
return text.padStart(width, " ");
|
|
843
|
+
}
|
|
844
|
+
var CLEANUP_FLAG_CATEGORIES = {
|
|
845
|
+
models: ["models"],
|
|
846
|
+
engines: ["native-engines", "engine-caches"],
|
|
847
|
+
toolsets: ["toolsets"],
|
|
848
|
+
caches: ["gilde-cache", "derived-caches"],
|
|
849
|
+
redownloadable: [
|
|
850
|
+
"models",
|
|
851
|
+
"native-engines",
|
|
852
|
+
"engine-caches",
|
|
853
|
+
"toolsets",
|
|
854
|
+
"gilde-cache",
|
|
855
|
+
"derived-caches"
|
|
856
|
+
]
|
|
857
|
+
};
|
|
858
|
+
var CLEANUP_CONTENT_CATEGORIES = {
|
|
859
|
+
gezels: ["gezels"],
|
|
860
|
+
projects: ["projects"],
|
|
861
|
+
documents: ["documents"],
|
|
862
|
+
settings: ["settings"],
|
|
863
|
+
all: ["gezels", "projects", "documents", "settings"]
|
|
864
|
+
};
|
|
865
|
+
function resolveCleanupSelection(flags) {
|
|
866
|
+
const categories = /* @__PURE__ */ new Set();
|
|
867
|
+
for (const [flag, ids] of Object.entries(CLEANUP_FLAG_CATEGORIES)) {
|
|
868
|
+
if (flags[flag] === true) for (const id of ids) categories.add(id);
|
|
869
|
+
}
|
|
870
|
+
let destroysUserContent = false;
|
|
871
|
+
if (flags.content !== void 0) {
|
|
872
|
+
const choice = flags.content;
|
|
873
|
+
const ids = CLEANUP_CONTENT_CATEGORIES[choice];
|
|
874
|
+
if (!ids) {
|
|
875
|
+
throw new Error(
|
|
876
|
+
`Unknown --content value "${flags.content}". Choose one of: ${Object.keys(
|
|
877
|
+
CLEANUP_CONTENT_CATEGORIES
|
|
878
|
+
).join(", ")}.`
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
for (const id of ids) categories.add(id);
|
|
882
|
+
destroysUserContent = true;
|
|
883
|
+
}
|
|
884
|
+
return { categories: [...categories], destroysUserContent };
|
|
885
|
+
}
|
|
886
|
+
function formatCleanupResult(job) {
|
|
887
|
+
const lines = [];
|
|
888
|
+
if (job.status === "error") {
|
|
889
|
+
lines.push(`Cleanup failed: ${job.error ?? "unknown error"}`);
|
|
890
|
+
} else if (job.status === "cancelled") {
|
|
891
|
+
lines.push(`Cleanup stopped early. Freed ${formatBytes2(job.bytesDone)} before stopping.`);
|
|
892
|
+
} else {
|
|
893
|
+
lines.push(`Freed ${formatBytes2(job.bytesDone)} across ${job.itemsDone} item(s).`);
|
|
894
|
+
}
|
|
895
|
+
if (job.skippedExternal.length > 0) {
|
|
896
|
+
lines.push("", "Left alone (stored outside the Gezel folder):");
|
|
897
|
+
for (const skipped of job.skippedExternal) {
|
|
898
|
+
lines.push(` ${skipped.label} \u2014 ${skipped.path}`);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
if (job.restartRequired) {
|
|
902
|
+
lines.push("", "Restart Gezel to pick up the changes.");
|
|
903
|
+
}
|
|
904
|
+
return lines.join("\n");
|
|
905
|
+
}
|
|
906
|
+
function formatCleanupPreview(summary, categories) {
|
|
907
|
+
const selected = new Set(categories);
|
|
908
|
+
const chosen = summary.categories.filter((c) => selected.has(c.id));
|
|
909
|
+
const total = chosen.reduce((sum, c) => sum + c.bytes, 0);
|
|
910
|
+
const lines = ["This will delete:"];
|
|
911
|
+
for (const c of chosen) {
|
|
912
|
+
lines.push(` ${pad(formatBytes2(c.bytes), 10)} ${c.label}`);
|
|
913
|
+
}
|
|
914
|
+
if (chosen.length === 0) lines.push(" (nothing \u2014 these categories are already empty)");
|
|
915
|
+
lines.push("", `Frees about ${formatBytes2(total)}.`);
|
|
916
|
+
const external = chosen.flatMap((c) => c.external);
|
|
917
|
+
if (external.length > 0) {
|
|
918
|
+
lines.push("", "Not touched (stored outside the Gezel folder):");
|
|
919
|
+
for (const entry of external) lines.push(` ${entry.path}`);
|
|
920
|
+
}
|
|
921
|
+
const userContent = chosen.filter((c) => c.class === "user-content");
|
|
922
|
+
if (userContent.length > 0) {
|
|
923
|
+
lines.push("", "WARNING: this includes content only you have. Gezel cannot download it again.");
|
|
924
|
+
}
|
|
925
|
+
return lines.join("\n");
|
|
926
|
+
}
|
|
927
|
+
function formatBackupPlan(plan) {
|
|
928
|
+
const lines = ["This backup will include:"];
|
|
929
|
+
const byKind = /* @__PURE__ */ new Map();
|
|
930
|
+
for (const item of plan.items) {
|
|
931
|
+
const bucket = byKind.get(item.kind) ?? { count: 0, bytes: 0 };
|
|
932
|
+
bucket.count += 1;
|
|
933
|
+
bucket.bytes += item.bytes;
|
|
934
|
+
byKind.set(item.kind, bucket);
|
|
935
|
+
}
|
|
936
|
+
const labels = {
|
|
937
|
+
gezel: "gezels",
|
|
938
|
+
project: "projects",
|
|
939
|
+
"document-root": "documents",
|
|
940
|
+
"settings-file": "settings files"
|
|
941
|
+
};
|
|
942
|
+
for (const [kind, bucket] of byKind) {
|
|
943
|
+
lines.push(` ${pad(formatBytes2(bucket.bytes), 10)} ${bucket.count} ${labels[kind] ?? kind}`);
|
|
944
|
+
}
|
|
945
|
+
if (plan.items.length === 0) lines.push(" (nothing yet \u2014 this install has no content)");
|
|
946
|
+
lines.push("", `About ${formatBytes2(plan.totalBytes)} total.`);
|
|
947
|
+
lines.push("Saved credentials are never included; reconnect services after restoring.");
|
|
948
|
+
for (const warning of plan.warnings) lines.push(` note: ${warning}`);
|
|
949
|
+
return lines.join("\n");
|
|
950
|
+
}
|
|
951
|
+
function formatRestoreReview(review) {
|
|
952
|
+
const lines = [
|
|
953
|
+
`Backup from Gezel ${review.gezelVersion}, made ${new Date(review.createdAt).toLocaleString()}`,
|
|
954
|
+
""
|
|
955
|
+
];
|
|
956
|
+
for (const item of review.items) {
|
|
957
|
+
const flag = item.conflict === "exists" ? " [already here]" : "";
|
|
958
|
+
lines.push(` ${pad(formatBytes2(item.bytes), 10)} ${item.kind}: ${item.label}${flag}`);
|
|
959
|
+
}
|
|
960
|
+
if (review.items.length === 0) lines.push(" (this backup is empty)");
|
|
961
|
+
if (review.warnings.length > 0) {
|
|
962
|
+
lines.push("");
|
|
963
|
+
for (const warning of review.warnings) lines.push(` note: ${warning}`);
|
|
964
|
+
}
|
|
965
|
+
return lines.join("\n");
|
|
966
|
+
}
|
|
967
|
+
function resolveRestoreSelection(review, opts) {
|
|
968
|
+
const wanted = opts.only && opts.only.length > 0 ? new Set(opts.only) : null;
|
|
969
|
+
const items = [];
|
|
970
|
+
const skipped = [];
|
|
971
|
+
for (const item of review.items) {
|
|
972
|
+
if (wanted && !wanted.has(`${item.kind}:${item.id}`) && !wanted.has(item.id)) continue;
|
|
973
|
+
if (item.conflict === "exists" && !opts.replace) {
|
|
974
|
+
skipped.push(`${item.label} (already here \u2014 use --replace to overwrite)`);
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
items.push({
|
|
978
|
+
kind: item.kind,
|
|
979
|
+
id: item.id,
|
|
980
|
+
action: item.conflict === "exists" ? "replace" : "add"
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
return { items, skipped };
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
// src/tui/craftbook-start.ts
|
|
987
|
+
import {
|
|
988
|
+
CRAFTBOOK_ROLE_META,
|
|
989
|
+
visibleCatalogItems
|
|
990
|
+
} from "@bendyline/gezel";
|
|
991
|
+
function normalizeCraftbooks(items, showWorkInProgressFeatures = false) {
|
|
992
|
+
const byId = /* @__PURE__ */ new Map();
|
|
993
|
+
for (const item of visibleCatalogItems(items, showWorkInProgressFeatures)) {
|
|
994
|
+
if (item.manifest.kind !== "craftbook-template") continue;
|
|
995
|
+
const manifest = item.manifest;
|
|
996
|
+
if (byId.has(manifest.id)) continue;
|
|
997
|
+
byId.set(manifest.id, {
|
|
998
|
+
id: manifest.id,
|
|
999
|
+
name: manifest.name,
|
|
1000
|
+
...manifest.description ? { description: manifest.description } : {},
|
|
1001
|
+
version: manifest.version,
|
|
1002
|
+
sourceId: item.sourceId,
|
|
1003
|
+
source: item.sourceId === "project" ? "project" : item.sourceId === "local" ? "local" : "bundled",
|
|
1004
|
+
stepCount: manifest.steps.length,
|
|
1005
|
+
tags: manifest.tags ?? [],
|
|
1006
|
+
role: manifest.role ?? "general"
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
return [...byId.values()].sort((left, right) => left.name.localeCompare(right.name));
|
|
1010
|
+
}
|
|
1011
|
+
function findCraftbook(books, value) {
|
|
1012
|
+
const query = value.trim().toLowerCase();
|
|
1013
|
+
return books.find((book) => book.id.toLowerCase() === query || book.name.toLowerCase() === query);
|
|
1014
|
+
}
|
|
1015
|
+
function craftbookStartRequest(book) {
|
|
1016
|
+
const summary = book.description?.trim();
|
|
1017
|
+
const description = summary ? `Start the "${book.name}" craftbook for this project. ${summary}` : `Start the "${book.name}" craftbook for this project. Follow every step in the recipe and verify its required outcomes before completing the task.`;
|
|
1018
|
+
return {
|
|
1019
|
+
title: book.name,
|
|
1020
|
+
description,
|
|
1021
|
+
craftbookId: book.id,
|
|
1022
|
+
craftbookSourceId: book.sourceId,
|
|
1023
|
+
...book.version ? { craftbookVersion: book.version } : {},
|
|
1024
|
+
dispatchEntry: true
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// src/bin/gezel.ts
|
|
1029
|
+
var program = new Command();
|
|
1030
|
+
program.name("gezel").description("Gezel \u2014 build a community of agents that do things.").version(GEZEL_VERSION).option(
|
|
1031
|
+
"--connect <url>",
|
|
1032
|
+
"Connect to this Gezel service (first use asks for approval in the Gezel app)."
|
|
1033
|
+
).option("--token <token>", "Bearer token for --connect (must have CLI access).").option(
|
|
1034
|
+
"--standalone",
|
|
1035
|
+
"Skip legacy full-product machine-service compatibility and use the per-user daemon."
|
|
1036
|
+
).option("--home <dir>", "Use this user-owned Gezel home (default: $GEZEL_HOME or ~/.gezel).").option(
|
|
1037
|
+
"--project [folder]",
|
|
1038
|
+
"Use this folder as the active project (default and bare flag: cwd)."
|
|
1039
|
+
);
|
|
1040
|
+
var cliGlobals = () => program.opts();
|
|
1041
|
+
program.hook("preAction", () => {
|
|
1042
|
+
const globals = cliGlobals();
|
|
1043
|
+
validateGlobals(globals);
|
|
1044
|
+
applyHome(globals);
|
|
1045
|
+
});
|
|
1046
|
+
program.action(async () => {
|
|
1047
|
+
const globals = cliGlobals();
|
|
1048
|
+
resolveDevHome(globals);
|
|
1049
|
+
const connection = await connectForTui(globals);
|
|
1050
|
+
try {
|
|
1051
|
+
const { client } = connection;
|
|
1052
|
+
const projectId = await resolveTuiProject(client, globals);
|
|
1053
|
+
const gezelId = await ensureCliProjectLead(client, projectId);
|
|
1054
|
+
let projectName = basename3(process.cwd()) || "workspace";
|
|
1055
|
+
try {
|
|
1056
|
+
const { projects } = await client.listProjects();
|
|
1057
|
+
projectName = projects.find((p) => p.id === projectId)?.name ?? projectName;
|
|
1058
|
+
} catch {
|
|
1059
|
+
}
|
|
1060
|
+
const tuiModule = "../tui/index.js";
|
|
1061
|
+
const { launchTui } = await import(tuiModule);
|
|
1062
|
+
await launchTui({ client, projectId, projectName, gezelId });
|
|
1063
|
+
} finally {
|
|
1064
|
+
await connection.stop?.();
|
|
1065
|
+
}
|
|
1066
|
+
});
|
|
1067
|
+
program.command("start").description("Start the Gezel daemon (no-op if already running)").option(
|
|
1068
|
+
"--port <port>",
|
|
1069
|
+
"Bind to a specific port (spawns a fresh daemon, does not adopt a running one)"
|
|
1070
|
+
).option(
|
|
1071
|
+
"--foreground",
|
|
1072
|
+
"Run the daemon attached to this terminal \u2014 stdio streams to this shell, Ctrl+C stops it. Useful for development and CI."
|
|
1073
|
+
).option(
|
|
1074
|
+
"--web",
|
|
1075
|
+
"Serve the web UI over HTTP on loopback and print a one-time browser URL (spawns a fresh HTTP daemon)."
|
|
1076
|
+
).option("--open", "With --web, open the printed URL in your default browser.").action(async (opts) => {
|
|
1077
|
+
const port = opts.port ? Number.parseInt(opts.port, 10) : void 0;
|
|
1078
|
+
if (port !== void 0 && !Number.isFinite(port)) {
|
|
1079
|
+
console.error(`invalid --port: ${opts.port}`);
|
|
1080
|
+
process.exitCode = 1;
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
const userEnv = { ...process.env };
|
|
1084
|
+
delete userEnv.GEZEL_SERVICE_ROLE;
|
|
1085
|
+
delete userEnv.GEZEL_SYSTEM_SCOPE;
|
|
1086
|
+
delete userEnv.GEZEL_PORT;
|
|
1087
|
+
const spawnEnv = {
|
|
1088
|
+
...userEnv,
|
|
1089
|
+
GEZEL_SERVICE_ROLE: "user"
|
|
1090
|
+
};
|
|
1091
|
+
const portEnv = resolveStartPortEnv(port, await shouldPreferCanonicalPort());
|
|
1092
|
+
if (portEnv !== void 0) spawnEnv.GEZEL_PORT = portEnv;
|
|
1093
|
+
if (opts.web) {
|
|
1094
|
+
spawnEnv.GEZEL_WEB = "1";
|
|
1095
|
+
spawnEnv.GEZEL_INSECURE_TRANSPORT = "1";
|
|
1096
|
+
}
|
|
1097
|
+
if (opts.foreground) {
|
|
1098
|
+
await startForeground(spawnEnv);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
if (port !== void 0 || opts.web) {
|
|
1102
|
+
const entry = resolveDaemonEntry2(import.meta.url);
|
|
1103
|
+
const result = await discoverOrSpawn2({
|
|
1104
|
+
daemonEntry: entry,
|
|
1105
|
+
detached: true,
|
|
1106
|
+
env: spawnEnv,
|
|
1107
|
+
// Always spawn fresh — don't adopt a running daemon that may be
|
|
1108
|
+
// on the wrong port / transport. (forceSpawn keeps the readiness
|
|
1109
|
+
// poll working, unlike a null readRuntimeFn override.)
|
|
1110
|
+
forceSpawn: true,
|
|
1111
|
+
// A cold first boot (fresh home: layout + default gezels +
|
|
1112
|
+
// native probe + catalog) routinely exceeds the 5s default, so
|
|
1113
|
+
// the spawn would time out while the daemon is still coming up —
|
|
1114
|
+
// and in --web mode the user would never see their URL. Give it
|
|
1115
|
+
// real headroom.
|
|
1116
|
+
timeoutMs: 2e4
|
|
1117
|
+
});
|
|
1118
|
+
const health2 = await result.client.health();
|
|
1119
|
+
console.log(
|
|
1120
|
+
`gezeld running (version ${health2.version}) on port ${new URL(result.baseUrl).port}`
|
|
1121
|
+
);
|
|
1122
|
+
if (opts.web) await printWebUrl(result.baseUrl, opts.open === true);
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
const client = await connectOwned(cliGlobals());
|
|
1126
|
+
const health = await client.health();
|
|
1127
|
+
console.log(`gezeld running (version ${health.version})`);
|
|
1128
|
+
});
|
|
1129
|
+
async function printWebUrl(baseUrl, open) {
|
|
1130
|
+
const { readFile: readFile3 } = await import("fs/promises");
|
|
1131
|
+
const { gezelPaths: gezelPaths2 } = await import("@bendyline/gezel/paths");
|
|
1132
|
+
let token;
|
|
1133
|
+
try {
|
|
1134
|
+
token = (await readFile3(gezelPaths2().runtime.webUiToken, "utf8")).trim();
|
|
1135
|
+
} catch {
|
|
1136
|
+
console.error("web UI: could not read the web-ui token from the runtime files.");
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
if (!token) {
|
|
1140
|
+
console.error("web UI: the web-ui token file was empty.");
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
const url = `${new URL(baseUrl).origin}/?token=${encodeURIComponent(token)}`;
|
|
1144
|
+
console.log("");
|
|
1145
|
+
console.log(` Gezel web UI \u2192 ${url}`);
|
|
1146
|
+
console.log("");
|
|
1147
|
+
if (open) await openInBrowser(url);
|
|
1148
|
+
}
|
|
1149
|
+
async function openInBrowser(url) {
|
|
1150
|
+
const { spawn } = await import("child_process");
|
|
1151
|
+
try {
|
|
1152
|
+
if (process.platform === "win32") {
|
|
1153
|
+
spawn("cmd", ["/c", "start", "", url], {
|
|
1154
|
+
detached: true,
|
|
1155
|
+
stdio: "ignore",
|
|
1156
|
+
windowsHide: true
|
|
1157
|
+
}).unref();
|
|
1158
|
+
} else if (process.platform === "darwin") {
|
|
1159
|
+
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
1160
|
+
} else {
|
|
1161
|
+
spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
|
|
1162
|
+
}
|
|
1163
|
+
} catch (err) {
|
|
1164
|
+
console.error(`could not open a browser automatically: ${err.message}`);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
async function startForeground(env2) {
|
|
1168
|
+
const { spawn } = await import("child_process");
|
|
1169
|
+
const entry = resolveDaemonEntry2(import.meta.url);
|
|
1170
|
+
const child = spawn(process.execPath, [entry], {
|
|
1171
|
+
detached: false,
|
|
1172
|
+
stdio: ["pipe", "inherit", "inherit"],
|
|
1173
|
+
env: { ...env2, GEZEL_SHUTDOWN_ON_STDIN_EOF: "1" }
|
|
1174
|
+
});
|
|
1175
|
+
let stopping;
|
|
1176
|
+
const requestStop = () => {
|
|
1177
|
+
stopping ??= stopOwnedDaemon2(child);
|
|
1178
|
+
void stopping;
|
|
1179
|
+
};
|
|
1180
|
+
process.on("SIGINT", requestStop);
|
|
1181
|
+
process.on("SIGTERM", requestStop);
|
|
1182
|
+
try {
|
|
1183
|
+
await new Promise((resolve3) => {
|
|
1184
|
+
child.on("exit", (code) => {
|
|
1185
|
+
process.exitCode = code ?? 0;
|
|
1186
|
+
resolve3();
|
|
1187
|
+
});
|
|
1188
|
+
});
|
|
1189
|
+
} finally {
|
|
1190
|
+
process.off("SIGINT", requestStop);
|
|
1191
|
+
process.off("SIGTERM", requestStop);
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
program.command("status").description("Show daemon status").action(async () => {
|
|
1195
|
+
const globals = cliGlobals();
|
|
1196
|
+
if (globals.connect) {
|
|
1197
|
+
const client2 = await connectOwned(globals);
|
|
1198
|
+
const health = await client2.health();
|
|
1199
|
+
console.log(
|
|
1200
|
+
`gezeld explicit service port=${new URL(globals.connect).port || "(default)"} health=ok version=${health.version}`
|
|
1201
|
+
);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
const system = await findHealthySystemService(globals);
|
|
1205
|
+
if (system) {
|
|
1206
|
+
const client2 = new GezelClient2({
|
|
1207
|
+
baseUrl: system.baseUrl,
|
|
1208
|
+
token: "",
|
|
1209
|
+
fetch: system.fetch
|
|
1210
|
+
});
|
|
1211
|
+
const health = await client2.health();
|
|
1212
|
+
console.log(
|
|
1213
|
+
`gezeld system service port=${system.port} health=ok version=${health.version} startedAt=${health.startedAt}`
|
|
1214
|
+
);
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
const broker = await describeMachineEngineBroker();
|
|
1218
|
+
if (broker.present && broker.healthy && broker.serviceRole === "machine-engine") {
|
|
1219
|
+
console.log(
|
|
1220
|
+
`gezeld machine engine broker port=${broker.port} health=ok version=${broker.version} (compute only \u2014 the product API is the per-user daemon below)`
|
|
1221
|
+
);
|
|
1222
|
+
} else if (broker.present && broker.healthy === false) {
|
|
1223
|
+
console.log(
|
|
1224
|
+
`gezeld machine service: runtime files present but unreachable (port ${broker.port})`
|
|
1225
|
+
);
|
|
1226
|
+
}
|
|
1227
|
+
const runtime = await readRuntime2();
|
|
1228
|
+
if (!runtime) {
|
|
1229
|
+
console.log("gezeld is not running");
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
const alive = isProcessAlive2(runtime.pid);
|
|
1233
|
+
console.log(`gezeld pid=${runtime.pid} port=${runtime.port} alive=${alive}`);
|
|
1234
|
+
if (!alive) return;
|
|
1235
|
+
const client = new GezelClient2({
|
|
1236
|
+
baseUrl: runtime.baseUrl,
|
|
1237
|
+
// Health is intentionally unauthenticated; diagnostics do not need to
|
|
1238
|
+
// consume the per-launch first-party runtime credential.
|
|
1239
|
+
token: "",
|
|
1240
|
+
...runtime.cert ? { fetch: createTrustingFetch2({ cert: runtime.cert }) } : {}
|
|
1241
|
+
});
|
|
1242
|
+
try {
|
|
1243
|
+
const health = await client.health();
|
|
1244
|
+
const engineNote = health.machineEngineConnected !== void 0 ? ` machineEngine=${health.machineEngineConnected ? "connected" : "unavailable"}` : "";
|
|
1245
|
+
console.log(
|
|
1246
|
+
`health ok: version=${health.version} startedAt=${health.startedAt}${engineNote}`
|
|
1247
|
+
);
|
|
1248
|
+
} catch (err) {
|
|
1249
|
+
console.error(`health failed: ${err.message}`);
|
|
1250
|
+
}
|
|
1251
|
+
});
|
|
1252
|
+
program.command("stop").description("Hard stop all AI work and switch Gezel to Reactive mode").option("--daemon", "Shut down the user-owned daemon process itself").action(async (opts) => {
|
|
1253
|
+
const globals = cliGlobals();
|
|
1254
|
+
if (opts.daemon) {
|
|
1255
|
+
await stopUserDaemon(globals);
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
if (!globals.connect && !await findHealthySystemService(globals)) {
|
|
1259
|
+
const runtime = await readRuntime2();
|
|
1260
|
+
if (!runtime || !isProcessAlive2(runtime.pid)) {
|
|
1261
|
+
console.log("Gezel has no running AI work to stop.");
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
const client = await connectOwned(globals);
|
|
1266
|
+
const result = await client.emergencyStopChats();
|
|
1267
|
+
const details = [
|
|
1268
|
+
`${result.cancelledTurns} active ${result.cancelledTurns === 1 ? "chat" : "chats"}`,
|
|
1269
|
+
`${result.clearedQueuedMessages} queued ${result.clearedQueuedMessages === 1 ? "message" : "messages"}`,
|
|
1270
|
+
`${result.clearedDeferredActions} deferred ${result.clearedDeferredActions === 1 ? "action" : "actions"}`
|
|
1271
|
+
];
|
|
1272
|
+
console.log(
|
|
1273
|
+
`Hard stop complete: ${details.join(", ")}. Local engines unloaded; Gezel is Reactive.`
|
|
1274
|
+
);
|
|
1275
|
+
});
|
|
1276
|
+
async function stopUserDaemon(globals) {
|
|
1277
|
+
if (globals.connect) {
|
|
1278
|
+
throw new CliError("gezel stop --daemon cannot stop an explicit remote service.");
|
|
1279
|
+
}
|
|
1280
|
+
const system = await findHealthySystemService(globals);
|
|
1281
|
+
if (system) {
|
|
1282
|
+
console.log(
|
|
1283
|
+
`The Electron-installed system service is running on port ${system.port} and is managed by the operating system. Use --standalone to target a user-owned runtime instead.`
|
|
1284
|
+
);
|
|
1285
|
+
return;
|
|
1286
|
+
}
|
|
1287
|
+
const runtime = await readRuntime2();
|
|
1288
|
+
if (!runtime) {
|
|
1289
|
+
console.log("gezeld is not running");
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
const stopped = await stopProcessByPid(runtime.pid);
|
|
1293
|
+
if (stopped) {
|
|
1294
|
+
console.log(`stopped gezeld pid=${runtime.pid}`);
|
|
1295
|
+
} else {
|
|
1296
|
+
console.error(`failed to confirm gezeld pid=${runtime.pid} stopped`);
|
|
1297
|
+
process.exitCode = 1;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
program.command("mode [mode]").description("Show or set AI activity (read-only, reactive, reactive+tasks, or full-play)").action(async (requested) => {
|
|
1301
|
+
const next = requested ? parseCliEngagementMode(requested) : null;
|
|
1302
|
+
if (requested && !next) {
|
|
1303
|
+
throw new CliError(
|
|
1304
|
+
`Invalid mode: ${requested}. Usage: gezel mode <${CLI_ENGAGEMENT_MODE_USAGE}>`
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
const client = await connectOwned(cliGlobals());
|
|
1308
|
+
if (!next) {
|
|
1309
|
+
const config = await client.getConfig();
|
|
1310
|
+
const current2 = cliEngagementModeOption(config.aiEngagementMode);
|
|
1311
|
+
console.log(`${current2.name} \u2014 ${current2.description}`);
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
const updated = await client.updateConfig({ aiEngagementMode: next });
|
|
1315
|
+
const current = cliEngagementModeOption(updated.aiEngagementMode);
|
|
1316
|
+
console.log(`AI mode \u2192 ${current.name} \u2014 ${current.description}`);
|
|
1317
|
+
});
|
|
1318
|
+
program.command("run [prompt...]").description("Run a prompt through a gezel and print the reply").option("-g, --gezel <ref>", "gezel id or name (default: this project's voorman)").action(async (promptParts, opts) => {
|
|
1319
|
+
const prompt = (promptParts ?? []).join(" ").trim();
|
|
1320
|
+
if (!prompt) {
|
|
1321
|
+
console.error('usage: gezel run "<prompt>"');
|
|
1322
|
+
process.exitCode = 1;
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
const conn = await connectForRun(cliGlobals());
|
|
1326
|
+
const removeSignalCleanup = installSignalCleanup(conn.stop, {
|
|
1327
|
+
onError: (error) => {
|
|
1328
|
+
console.error(`shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1329
|
+
}
|
|
1330
|
+
});
|
|
1331
|
+
try {
|
|
1332
|
+
const { client } = conn;
|
|
1333
|
+
const projectId = await resolveRunProject(client, cliGlobals());
|
|
1334
|
+
const gezelId = opts.gezel ?? await ensureCliProjectLead(client, projectId);
|
|
1335
|
+
const session = await client.createChatSession({ gezelId, projectId });
|
|
1336
|
+
await client.sendToChatSession(session.id, prompt);
|
|
1337
|
+
let printed = false;
|
|
1338
|
+
let errored = false;
|
|
1339
|
+
for await (const ev of streamChatEvents({
|
|
1340
|
+
url: client.sessionEventsUrl(session.id),
|
|
1341
|
+
headers: client.authHeader(),
|
|
1342
|
+
fetch: client.getFetch()
|
|
1343
|
+
})) {
|
|
1344
|
+
if (ev.type === "delta") {
|
|
1345
|
+
process.stdout.write(ev.content);
|
|
1346
|
+
printed = true;
|
|
1347
|
+
} else if (ev.type === "complete") {
|
|
1348
|
+
if (!printed && ev.message.content) {
|
|
1349
|
+
process.stdout.write(ev.message.content);
|
|
1350
|
+
printed = true;
|
|
1351
|
+
}
|
|
1352
|
+
} else if (ev.type === "error") {
|
|
1353
|
+
console.error(`
|
|
1354
|
+
${ev.error}`);
|
|
1355
|
+
errored = true;
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
if (printed) process.stdout.write("\n");
|
|
1359
|
+
if (errored) process.exitCode = 1;
|
|
1360
|
+
} finally {
|
|
1361
|
+
removeSignalCleanup();
|
|
1362
|
+
if (conn.stop) await conn.stop();
|
|
1363
|
+
}
|
|
1364
|
+
});
|
|
1365
|
+
program.command("do <craftbook...>").description("Start a craftbook as a task in the current directory's project").action(async (craftbookParts) => {
|
|
1366
|
+
const craftbookRef = craftbookParts.join(" ").trim();
|
|
1367
|
+
const client = await connectOwned(cliGlobals());
|
|
1368
|
+
const projectId = await resolveRunProject(client, cliGlobals());
|
|
1369
|
+
const [config, result] = await Promise.all([
|
|
1370
|
+
client.getConfig(),
|
|
1371
|
+
client.listProjectCraftbooks(projectId)
|
|
1372
|
+
]);
|
|
1373
|
+
const craftbooks = normalizeCraftbooks(
|
|
1374
|
+
result.items,
|
|
1375
|
+
config.showWorkInProgressFeatures === true
|
|
1376
|
+
);
|
|
1377
|
+
const book = findCraftbook(craftbooks, craftbookRef);
|
|
1378
|
+
if (!book) {
|
|
1379
|
+
throw new CliError(`craftbook not found: ${craftbookRef} (run gezel and type /do to browse)`);
|
|
1380
|
+
}
|
|
1381
|
+
const created = await client.createTask(projectId, {
|
|
1382
|
+
...craftbookStartRequest(book),
|
|
1383
|
+
roleBasedNameOnlyMode: true
|
|
1384
|
+
});
|
|
1385
|
+
console.log(`started ${created.ref} \u2014 ${created.title}`);
|
|
1386
|
+
});
|
|
1387
|
+
var agent = program.command("agent").description("Manage agents");
|
|
1388
|
+
agent.command("list").description("List agents").action(async () => {
|
|
1389
|
+
const client = await connectOwned(cliGlobals());
|
|
1390
|
+
const res = await client.listGezels();
|
|
1391
|
+
for (const a of res.gezels) {
|
|
1392
|
+
console.log(`${a.id.padEnd(20)} ${a.name}`);
|
|
1393
|
+
}
|
|
1394
|
+
});
|
|
1395
|
+
agent.command("create <name>").description("Create a new agent").option("-d, --description <text>", "description").option("-m, --model <model>", "model identifier").action(async (name, opts) => {
|
|
1396
|
+
const client = await connectOwned(cliGlobals());
|
|
1397
|
+
const created = await client.createGezel({ name, ...opts });
|
|
1398
|
+
console.log(`created agent ${created.id}`);
|
|
1399
|
+
});
|
|
1400
|
+
agent.command("show <id>").description("Show an agent").action(async (id) => {
|
|
1401
|
+
const client = await connectOwned(cliGlobals());
|
|
1402
|
+
const a = await client.getGezel(id);
|
|
1403
|
+
console.log(a.parsed.source);
|
|
1404
|
+
});
|
|
1405
|
+
var env = program.command("env").description("Manage projects");
|
|
1406
|
+
env.command("list").description("List projects").action(async () => {
|
|
1407
|
+
const client = await connectOwned(cliGlobals());
|
|
1408
|
+
const res = await client.listProjects();
|
|
1409
|
+
for (const e of res.projects) {
|
|
1410
|
+
console.log(`${e.id.padEnd(20)} ${e.name}`);
|
|
1411
|
+
}
|
|
1412
|
+
});
|
|
1413
|
+
env.command("create <name>").option("-d, --description <text>", "description").option(
|
|
1414
|
+
"-a, --about <text>",
|
|
1415
|
+
"about \u2014 paragraphs about who the project is for + scope (min 60 chars)"
|
|
1416
|
+
).option("-m, --mission <text>", "mission objectives \u2014 concrete success criteria (min 40 chars)").action(
|
|
1417
|
+
async (name, opts) => {
|
|
1418
|
+
const about = opts.about ?? `${name} \u2014 fill in the about for this project. Add paragraphs about who it's for, what's in scope, and what's explicitly out of scope.`;
|
|
1419
|
+
const missionObjectives = opts.mission ?? `${name} \u2014 fill in the mission objectives. Use concrete success criteria, usually as a bullet list.`;
|
|
1420
|
+
const client = await connectOwned(cliGlobals());
|
|
1421
|
+
const created = await client.createProject({
|
|
1422
|
+
name,
|
|
1423
|
+
...opts.description ? { description: opts.description } : {},
|
|
1424
|
+
about,
|
|
1425
|
+
missionObjectives
|
|
1426
|
+
});
|
|
1427
|
+
console.log(`created project ${created.id}`);
|
|
1428
|
+
}
|
|
1429
|
+
);
|
|
1430
|
+
env.command("install <envId> <package>").description("Install an npm package into a project (--ignore-scripts)").option("-V, --version <version>", "package version").action(async (envId, pkg, opts) => {
|
|
1431
|
+
const client = await connectOwned(cliGlobals());
|
|
1432
|
+
const res = await client.installPackage(envId, { name: pkg, version: opts.version });
|
|
1433
|
+
console.log(res.log);
|
|
1434
|
+
console.log(`installed ${pkg} into ${envId}`);
|
|
1435
|
+
});
|
|
1436
|
+
var skills = program.command("skills").description("Discover and convert SKILL.md skills into craftbooks");
|
|
1437
|
+
skills.command("list").description("List skills discovered in the project workspace").action(async () => {
|
|
1438
|
+
const client = await connectOwned(cliGlobals());
|
|
1439
|
+
const projectId = await resolveRunProject(client, cliGlobals());
|
|
1440
|
+
const index = await client.getProjectSkills(projectId);
|
|
1441
|
+
if (index.skills.length === 0) {
|
|
1442
|
+
console.log("no skills discovered (.claude/skills, .gstack/skills, agents/skills)");
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
for (const s of index.skills) {
|
|
1446
|
+
console.log(
|
|
1447
|
+
`${s.name.padEnd(24)} ${s.source}${s.description ? ` \u2014 ${s.description}` : ""}`
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
});
|
|
1451
|
+
skills.command("import <source>").description("Convert a discovered skill (by its workspace-relative SKILL.md path)").option("--queue", "queue script/persona-bearing results for review instead of reporting").option("--no-llm", "static conversion only \u2014 never call the model for shell blocks").action(async (source, opts) => {
|
|
1452
|
+
const client = await connectOwned(cliGlobals());
|
|
1453
|
+
const projectId = await resolveRunProject(client, cliGlobals());
|
|
1454
|
+
const result = await client.convertProjectImport(projectId, source, {
|
|
1455
|
+
allowLlm: opts.llm !== false
|
|
1456
|
+
});
|
|
1457
|
+
switch (result.status) {
|
|
1458
|
+
case "written":
|
|
1459
|
+
console.log(`imported as craftbook ${result.craftbookId}`);
|
|
1460
|
+
break;
|
|
1461
|
+
case "queued": {
|
|
1462
|
+
if (opts.queue) {
|
|
1463
|
+
console.log(
|
|
1464
|
+
`queued for review (${result.scripts} script(s)${result.persona ? `, persona "${result.persona}"` : ""}) \u2014 approve in the Commands panel`
|
|
1465
|
+
);
|
|
1466
|
+
break;
|
|
1467
|
+
}
|
|
1468
|
+
const approved = await client.approveProjectImport(projectId, source);
|
|
1469
|
+
console.log(
|
|
1470
|
+
`imported as craftbook ${approved.craftbookId} (${result.scripts} script(s)${result.persona ? `, persona "${result.persona}"` : ""})`
|
|
1471
|
+
);
|
|
1472
|
+
break;
|
|
1473
|
+
}
|
|
1474
|
+
case "user-edited":
|
|
1475
|
+
console.log("already imported and user-edited \u2014 left untouched");
|
|
1476
|
+
break;
|
|
1477
|
+
case "not-found":
|
|
1478
|
+
console.error(`no discovered skill at ${source} \u2014 try \`gezel skills list\``);
|
|
1479
|
+
process.exitCode = 1;
|
|
1480
|
+
break;
|
|
1481
|
+
default:
|
|
1482
|
+
console.error(`conversion failed: ${result.notes.join("; ") || "see the service log"}`);
|
|
1483
|
+
process.exitCode = 1;
|
|
1484
|
+
}
|
|
1485
|
+
for (const note of result.notes) console.log(` note: ${note}`);
|
|
1486
|
+
});
|
|
1487
|
+
skills.command("convert <path>").description("Convert a SKILL.md file to a craftbook document on stdout (no daemon)").option("--md", "emit the markdown encoding instead of JSON").option("--released-at <iso>", "stamp releasedAt (catalog authoring)").action(async (path, opts) => {
|
|
1488
|
+
const { readFile: readFsFile } = await import("fs/promises");
|
|
1489
|
+
const { basename: base, dirname: dir } = await import("path");
|
|
1490
|
+
const { parseSkillDoc, skillToCraftbookDoc, serializeCraftbookDoc, craftbookFromDoc } = await import("@bendyline/gezel");
|
|
1491
|
+
const raw = await readFsFile(path, "utf8");
|
|
1492
|
+
const skill = parseSkillDoc(raw, { fallbackName: base(dir(path)) });
|
|
1493
|
+
const result = skillToCraftbookDoc(skill, {
|
|
1494
|
+
...opts.releasedAt ? { releasedAt: opts.releasedAt } : {}
|
|
1495
|
+
});
|
|
1496
|
+
const check = craftbookFromDoc(result.doc, { now: "1970-01-01T00:00:00.000Z" });
|
|
1497
|
+
if (!check.ok) {
|
|
1498
|
+
console.error("conversion produced an invalid craftbook:");
|
|
1499
|
+
for (const e of check.errors) console.error(` ${e.where}: ${e.message}`);
|
|
1500
|
+
process.exitCode = 1;
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
process.stdout.write(serializeCraftbookDoc(result.doc, opts.md ? "markdown" : "json"));
|
|
1504
|
+
for (const note of result.notes) console.error(`note: ${note}`);
|
|
1505
|
+
if (result.persona) console.error(`persona: ${result.persona.role}`);
|
|
1506
|
+
});
|
|
1507
|
+
var handboek = program.command("handboek").description("The built-in documentation (Handboek)");
|
|
1508
|
+
handboek.command("export").description("Render the Handboek as a static HTML site for gezel.com (no daemon)").requiredOption("--out <dir>", "output directory").option(
|
|
1509
|
+
"--css <href>",
|
|
1510
|
+
"extra stylesheet to link on every page; relative hrefs resolve against the export root. Repeatable.",
|
|
1511
|
+
(href, prior) => [...prior, href],
|
|
1512
|
+
[]
|
|
1513
|
+
).option(
|
|
1514
|
+
"--site-url <url>",
|
|
1515
|
+
"URL of the surrounding site; adds a wordmark link back out of the docs"
|
|
1516
|
+
).action(async (opts) => {
|
|
1517
|
+
const handboekModule = "../handboek-export.js";
|
|
1518
|
+
const { runHandboekExport } = await import(handboekModule);
|
|
1519
|
+
const result = await runHandboekExport({
|
|
1520
|
+
out: opts.out,
|
|
1521
|
+
css: opts.css,
|
|
1522
|
+
siteUrl: opts.siteUrl
|
|
1523
|
+
});
|
|
1524
|
+
console.log(`Handboek exported: ${result.pages} pages \u2192 ${result.out}`);
|
|
1525
|
+
for (const id of result.skipped) console.error(` skipped (no body): ${id}`);
|
|
1526
|
+
});
|
|
1527
|
+
var task = program.command("task").description("Manage tasks");
|
|
1528
|
+
task.command("list").description("List tasks across every project").option("-s, --status <status>", "filter by status (paused|active|complete|canceled)").action(async (opts) => {
|
|
1529
|
+
const client = await connectOwned(cliGlobals());
|
|
1530
|
+
const res = await client.listTasks(
|
|
1531
|
+
opts.status ? { status: opts.status } : void 0
|
|
1532
|
+
);
|
|
1533
|
+
for (const t of res.tasks) {
|
|
1534
|
+
const assignee = t.assignee.kind === "user" ? "user" : t.assignee.gezelId;
|
|
1535
|
+
console.log(
|
|
1536
|
+
`${t.ref.padEnd(24)} ${t.status.padEnd(10)} ${assignee.padEnd(20)} ${t.title}`
|
|
1537
|
+
);
|
|
1538
|
+
}
|
|
1539
|
+
});
|
|
1540
|
+
task.command("create <projectId> <title>").description("Create a task with a single phase").option("-a, --assignee <gezelId>", "gezel id to assign (default: user)").option("-p, --phase <name>", "first phase name", "Main").option("-d, --description <text>", "task description \u2014 what done looks like (min 40 chars)").action(
|
|
1541
|
+
async (projectId, title, opts) => {
|
|
1542
|
+
const description = opts.description ?? `${title} \u2014 fill in the task description. Cover what done looks like, key constraints, and any links the assignee will need.`;
|
|
1543
|
+
const client = await connectOwned(cliGlobals());
|
|
1544
|
+
const created = await client.createTask(projectId, {
|
|
1545
|
+
title,
|
|
1546
|
+
description,
|
|
1547
|
+
assignee: opts.assignee ? { kind: "gezel", gezelId: opts.assignee } : { kind: "user" },
|
|
1548
|
+
steps: [{ name: opts.phase }],
|
|
1549
|
+
roleBasedNameOnlyMode: true
|
|
1550
|
+
});
|
|
1551
|
+
console.log(`created ${created.ref}`);
|
|
1552
|
+
}
|
|
1553
|
+
);
|
|
1554
|
+
task.command("show <ref>").description("Show one task (format: projectId/num)").action(async (ref) => {
|
|
1555
|
+
const client = await connectOwned(cliGlobals());
|
|
1556
|
+
const t = await client.getTaskByRef(ref);
|
|
1557
|
+
console.log(JSON.stringify(t, null, 2));
|
|
1558
|
+
});
|
|
1559
|
+
program.command("create-image [prompt...]").description("Generate an image from a prompt (or --file) via the configured image engine").option("-f, --file <path>", "read the prompt from a text file instead of the argument").option("-m, --model <id>", "image model catalog id (default: the engine default)").option("-n, --negative <text>", "negative prompt").option("-W, --width <px>", "width in pixels").option("-H, --height <px>", "height in pixels").option("-s, --steps <n>", "sampler steps (default: the model recommendation)").option("--seed <n>", "seed for reproducible output").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the image here (default: ./<artifact name>)").action(
|
|
1560
|
+
async (promptParts, opts) => {
|
|
1561
|
+
const prompt = await resolvePromptText(promptParts, opts.file, "prompt");
|
|
1562
|
+
const client = await connectOwned(cliGlobals());
|
|
1563
|
+
const projectId = opts.project ?? "default";
|
|
1564
|
+
const width = intOpt("width", opts.width);
|
|
1565
|
+
const height = intOpt("height", opts.height);
|
|
1566
|
+
const steps = intOpt("steps", opts.steps);
|
|
1567
|
+
const seed = intOpt("seed", opts.seed);
|
|
1568
|
+
console.error(`generating image${opts.model ? ` (model ${opts.model})` : ""}...`);
|
|
1569
|
+
let res;
|
|
1570
|
+
try {
|
|
1571
|
+
res = await client.generateImage({
|
|
1572
|
+
prompt,
|
|
1573
|
+
projectId,
|
|
1574
|
+
...opts.model ? { model: opts.model } : {},
|
|
1575
|
+
...opts.negative ? { negativePrompt: opts.negative } : {},
|
|
1576
|
+
...width !== void 0 ? { width } : {},
|
|
1577
|
+
...height !== void 0 ? { height } : {},
|
|
1578
|
+
...steps !== void 0 ? { steps } : {},
|
|
1579
|
+
...seed !== void 0 ? { seed } : {}
|
|
1580
|
+
});
|
|
1581
|
+
} catch (err) {
|
|
1582
|
+
throw new CliError(
|
|
1583
|
+
`image generation failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1584
|
+
);
|
|
1585
|
+
}
|
|
1586
|
+
const dest = await saveArtifact(client, projectId, res.artifactPath, opts.output);
|
|
1587
|
+
const m = res.meta;
|
|
1588
|
+
console.log(dest);
|
|
1589
|
+
console.error(
|
|
1590
|
+
` model=${m.model} seed=${m.seed} steps=${m.steps} size=${m.widthPx}x${m.heightPx} time=${(m.durationMs / 1e3).toFixed(1)}s`
|
|
1591
|
+
);
|
|
1592
|
+
}
|
|
1593
|
+
);
|
|
1594
|
+
program.command("create-video [prompt...]").description("Generate a video from a prompt (or --file) via the configured video engine").option("-f, --file <path>", "read the prompt from a text file instead of the argument").option("-m, --model <id>", "video model catalog id (default: the engine default)").option("-n, --negative <text>", "negative prompt").option("-W, --width <px>", "width in pixels").option("-H, --height <px>", "height in pixels").option("--frames <n>", "number of frames").option("--fps <n>", "frames per second").option("-s, --steps <n>", "sampler steps").option("--seed <n>", "seed for reproducible output").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the video here (default: ./<artifact name>)").action(
|
|
1595
|
+
async (promptParts, opts) => {
|
|
1596
|
+
const prompt = await resolvePromptText(promptParts, opts.file, "prompt");
|
|
1597
|
+
const client = await connectOwned(cliGlobals());
|
|
1598
|
+
const projectId = opts.project ?? "default";
|
|
1599
|
+
const width = intOpt("width", opts.width);
|
|
1600
|
+
const height = intOpt("height", opts.height);
|
|
1601
|
+
const numFrames = intOpt("frames", opts.frames);
|
|
1602
|
+
const fps = intOpt("fps", opts.fps);
|
|
1603
|
+
const steps = intOpt("steps", opts.steps);
|
|
1604
|
+
const seed = intOpt("seed", opts.seed);
|
|
1605
|
+
console.error(
|
|
1606
|
+
`generating video${opts.model ? ` (model ${opts.model})` : ""} \u2014 this can take a while...`
|
|
1607
|
+
);
|
|
1608
|
+
let res;
|
|
1609
|
+
try {
|
|
1610
|
+
res = await client.generateVideo({
|
|
1611
|
+
prompt,
|
|
1612
|
+
projectId,
|
|
1613
|
+
...opts.model ? { model: opts.model } : {},
|
|
1614
|
+
...opts.negative ? { negativePrompt: opts.negative } : {},
|
|
1615
|
+
...width !== void 0 ? { width } : {},
|
|
1616
|
+
...height !== void 0 ? { height } : {},
|
|
1617
|
+
...numFrames !== void 0 ? { numFrames } : {},
|
|
1618
|
+
...fps !== void 0 ? { fps } : {},
|
|
1619
|
+
...steps !== void 0 ? { steps } : {},
|
|
1620
|
+
...seed !== void 0 ? { seed } : {}
|
|
1621
|
+
});
|
|
1622
|
+
} catch (err) {
|
|
1623
|
+
throw new CliError(
|
|
1624
|
+
`video generation failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1625
|
+
);
|
|
1626
|
+
}
|
|
1627
|
+
const dest = await saveArtifact(client, projectId, res.artifactPath, opts.output);
|
|
1628
|
+
const m = res.meta;
|
|
1629
|
+
console.log(dest);
|
|
1630
|
+
console.error(
|
|
1631
|
+
` model=${m.model} seed=${m.seed} ${m.widthPx}x${m.heightPx} frames=${m.numFrames} fps=${m.fps} time=${(m.durationMs / 1e3).toFixed(1)}s`
|
|
1632
|
+
);
|
|
1633
|
+
}
|
|
1634
|
+
);
|
|
1635
|
+
program.command("create-audio [text...]").description("Synthesize speech from text (or --file) via the configured TTS engine").option("-f, --file <path>", "read the text from a file instead of the argument").option("-m, --model <id>", "TTS model catalog id (default: the engine default)").option("--voice <id>", "voice id (default: the model/gezel default)").option("--speed <x>", "speed multiplier, 0.25-4 (default: 1.0)").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the audio here (default: ./<artifact name>)").action(async (textParts, opts) => {
|
|
1636
|
+
const text = await resolvePromptText(textParts, opts.file, "text");
|
|
1637
|
+
const client = await connectOwned(cliGlobals());
|
|
1638
|
+
const projectId = opts.project ?? "default";
|
|
1639
|
+
const speed = floatOpt("speed", opts.speed);
|
|
1640
|
+
console.error("synthesizing speech...");
|
|
1641
|
+
let res;
|
|
1642
|
+
try {
|
|
1643
|
+
res = await client.synthesizeSpeech({
|
|
1644
|
+
text,
|
|
1645
|
+
projectId,
|
|
1646
|
+
...opts.model ? { model: opts.model } : {},
|
|
1647
|
+
...opts.voice ? { voice: opts.voice } : {},
|
|
1648
|
+
...speed !== void 0 ? { speed } : {}
|
|
1649
|
+
});
|
|
1650
|
+
} catch (err) {
|
|
1651
|
+
throw new CliError(
|
|
1652
|
+
`speech synthesis failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1653
|
+
);
|
|
1654
|
+
}
|
|
1655
|
+
const dest = await saveArtifact(client, projectId, res.artifactPath, opts.output);
|
|
1656
|
+
const m = res.meta;
|
|
1657
|
+
console.log(dest);
|
|
1658
|
+
console.error(
|
|
1659
|
+
` voice=${m.voice} model=${m.model} ${m.durationSeconds.toFixed(1)}s @ ${m.sampleRate}Hz`
|
|
1660
|
+
);
|
|
1661
|
+
});
|
|
1662
|
+
var native = program.command("native").description("Manage native engine binaries");
|
|
1663
|
+
native.command("install").description("Download, verify, and activate the native inference toolkit").option("--variant <backend>", "llama.cpp backend: cuda | vulkan | metal | cpu").action(async (opts) => {
|
|
1664
|
+
const variant = parseNativeVariant(opts.variant);
|
|
1665
|
+
const client = await connectOwned(cliGlobals());
|
|
1666
|
+
const installed = await installNativeToolkit(client, {
|
|
1667
|
+
...variant ? { variant } : {},
|
|
1668
|
+
output: { writeProgress: (text) => process.stderr.write(text) }
|
|
1669
|
+
});
|
|
1670
|
+
console.log(`native toolkit ready
|
|
1671
|
+
${formatNativeStatus(installed)}`);
|
|
1672
|
+
});
|
|
1673
|
+
native.command("list").description("List native executables and their install state").action(async () => {
|
|
1674
|
+
const client = await connectOwned(cliGlobals());
|
|
1675
|
+
console.log(formatNativeList(await client.getNativeEngineStatus()));
|
|
1676
|
+
});
|
|
1677
|
+
native.command("status").description("Show native release, platform, backend, and toolkit status").action(async () => {
|
|
1678
|
+
const client = await connectOwned(cliGlobals());
|
|
1679
|
+
console.log(formatNativeStatus(await client.getNativeEngineStatus()));
|
|
1680
|
+
});
|
|
1681
|
+
var image = program.command("image").description("Manage image-generation models");
|
|
1682
|
+
image.command("status").description("Show the image engine status and local model count").action(async () => {
|
|
1683
|
+
const client = await connectOwned(cliGlobals());
|
|
1684
|
+
const { engine, modelCount } = await client.getImageEngineStatus();
|
|
1685
|
+
console.log(
|
|
1686
|
+
`engine: ${engine.provider ?? "unknown"} (${engine.kind ?? "?"}) \u2014 ${engine.status}`
|
|
1687
|
+
);
|
|
1688
|
+
if (engine.error) console.log(` ${engine.error}`);
|
|
1689
|
+
console.log(`local models: ${modelCount}`);
|
|
1690
|
+
});
|
|
1691
|
+
image.command("models").description("List local image models").action(async () => {
|
|
1692
|
+
const client = await connectOwned(cliGlobals());
|
|
1693
|
+
const { models } = await client.listInstalledImageModels();
|
|
1694
|
+
if (models.length === 0) {
|
|
1695
|
+
console.log("(no local image models \u2014 download one with `gezel image pull <id>`)");
|
|
1696
|
+
return;
|
|
1697
|
+
}
|
|
1698
|
+
for (const m of models) {
|
|
1699
|
+
console.log(
|
|
1700
|
+
`${m.id.padEnd(24)} ${(m.approxSizeBytes / 1e9).toFixed(2).padStart(6)} GB ${m.name}`
|
|
1701
|
+
);
|
|
1702
|
+
}
|
|
1703
|
+
});
|
|
1704
|
+
image.command("pull <id>").description("Download an image model from the catalog (e.g. krea-2-turbo-q4)").action(async (id) => {
|
|
1705
|
+
const client = await connectOwned(cliGlobals());
|
|
1706
|
+
let lastPct = -1;
|
|
1707
|
+
let pullError;
|
|
1708
|
+
await client.pullImageModel(id, (ev) => {
|
|
1709
|
+
if (ev.type === "progress") {
|
|
1710
|
+
const total = ev.totalBytes ?? 0;
|
|
1711
|
+
const pct = total > 0 ? Math.floor(ev.bytesWritten / total * 100) : 0;
|
|
1712
|
+
if (pct !== lastPct) {
|
|
1713
|
+
lastPct = pct;
|
|
1714
|
+
process.stderr.write(
|
|
1715
|
+
`\rpulling ${id}: ${String(pct).padStart(3)}% ${(ev.bytesWritten / 1e9).toFixed(2)}/${(total / 1e9).toFixed(2)} GB`
|
|
1716
|
+
);
|
|
1717
|
+
}
|
|
1718
|
+
} else if (ev.type === "retrying") {
|
|
1719
|
+
process.stderr.write(`
|
|
1720
|
+
retry ${ev.attempt}/${ev.maxAttempts}: ${ev.reason}
|
|
1721
|
+
`);
|
|
1722
|
+
} else if (ev.type === "error") {
|
|
1723
|
+
pullError = ev.error;
|
|
1724
|
+
process.stderr.write("\n");
|
|
1725
|
+
} else if (ev.type === "done" && !pullError) {
|
|
1726
|
+
process.stderr.write(`\rpulled ${id}${" ".repeat(48)}
|
|
1727
|
+
`);
|
|
1728
|
+
}
|
|
1729
|
+
});
|
|
1730
|
+
if (pullError) throw new CliError(`pull failed: ${pullError}`);
|
|
1731
|
+
});
|
|
1732
|
+
image.command("rm <id>").description("Delete a local image model").action(async (id) => {
|
|
1733
|
+
const client = await connectOwned(cliGlobals());
|
|
1734
|
+
await client.deleteImageModel(id);
|
|
1735
|
+
console.log(`removed ${id}`);
|
|
1736
|
+
});
|
|
1737
|
+
var model = program.command("model").description("Manage local chat models (MLX / llama)");
|
|
1738
|
+
function resolveModelProvider(raw) {
|
|
1739
|
+
if (raw) {
|
|
1740
|
+
if (raw !== "mlx" && raw !== "llama-cpp" && raw !== "ds4") {
|
|
1741
|
+
throw new CliError(`--provider must be one of mlx, llama-cpp, ds4 (got "${raw}")`);
|
|
1742
|
+
}
|
|
1743
|
+
return raw;
|
|
1744
|
+
}
|
|
1745
|
+
return process.platform === "darwin" && process.arch === "arm64" ? "mlx" : "llama-cpp";
|
|
1746
|
+
}
|
|
1747
|
+
model.command("list").description("List local chat models for an engine").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").action(async (opts) => {
|
|
1748
|
+
const client = await connectOwned(cliGlobals());
|
|
1749
|
+
const provider = resolveModelProvider(opts.provider);
|
|
1750
|
+
const { models } = provider === "mlx" ? await client.listMlxModels() : provider === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
|
|
1751
|
+
if (models.length === 0) {
|
|
1752
|
+
console.log(`(no local ${provider} models \u2014 download one with \`gezel model pull <id>\`)`);
|
|
1753
|
+
return;
|
|
1754
|
+
}
|
|
1755
|
+
for (const m of models) {
|
|
1756
|
+
console.log(
|
|
1757
|
+
`${m.id.padEnd(28)} ${(m.approxSizeBytes / 1e9).toFixed(2).padStart(6)} GB ${m.name}`
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
});
|
|
1761
|
+
model.command("pull <id>").description("Download a local chat model from the catalog (e.g. gemma4-31b-q4)").option("-p, --provider <engine>", "mlx | llama-cpp | ds4 (default: platform default)").action(async (id, opts) => {
|
|
1762
|
+
const client = await connectOwned(cliGlobals());
|
|
1763
|
+
const provider = resolveModelProvider(opts.provider);
|
|
1764
|
+
let lastPct = -1;
|
|
1765
|
+
let pullError;
|
|
1766
|
+
const onEvent = (ev) => {
|
|
1767
|
+
if (ev.type === "progress") {
|
|
1768
|
+
const written = "bytesWrittenAll" in ev ? ev.bytesWrittenAll : ev.bytesWritten;
|
|
1769
|
+
const total = "totalBytesAll" in ev ? ev.totalBytesAll : ev.totalBytes ?? 0;
|
|
1770
|
+
const pct = total > 0 ? Math.floor(written / total * 100) : 0;
|
|
1771
|
+
if (pct !== lastPct) {
|
|
1772
|
+
lastPct = pct;
|
|
1773
|
+
process.stderr.write(
|
|
1774
|
+
`\rpulling ${id} (${provider}): ${String(pct).padStart(3)}% ${(written / 1e9).toFixed(2)}/${(total / 1e9).toFixed(2)} GB`
|
|
1775
|
+
);
|
|
1776
|
+
}
|
|
1777
|
+
} else if (ev.type === "retrying") {
|
|
1778
|
+
process.stderr.write(`
|
|
1779
|
+
retry ${ev.attempt}/${ev.maxAttempts}: ${ev.reason}
|
|
1780
|
+
`);
|
|
1781
|
+
} else if (ev.type === "error") {
|
|
1782
|
+
pullError = ev.error;
|
|
1783
|
+
process.stderr.write("\n");
|
|
1784
|
+
} else if (ev.type === "done" && !pullError) {
|
|
1785
|
+
process.stderr.write(`\rpulled ${id} (${provider})${" ".repeat(48)}
|
|
1786
|
+
`);
|
|
1787
|
+
}
|
|
1788
|
+
};
|
|
1789
|
+
if (provider === "mlx") {
|
|
1790
|
+
await client.installMlxModel(id, onEvent);
|
|
1791
|
+
} else if (provider === "ds4") {
|
|
1792
|
+
await client.installDs4Model(id, onEvent);
|
|
1793
|
+
} else {
|
|
1794
|
+
await client.installLlamaCppModel(id, onEvent);
|
|
1795
|
+
}
|
|
1796
|
+
if (pullError) throw new CliError(`pull failed: ${pullError}`);
|
|
1797
|
+
});
|
|
1798
|
+
program.command("doctor").description("Check the Gezel installation").action(async () => {
|
|
1799
|
+
const globals = cliGlobals();
|
|
1800
|
+
const system = globals.connect ? null : await findHealthySystemService(globals);
|
|
1801
|
+
const broker = globals.connect ? null : await describeMachineEngineBroker();
|
|
1802
|
+
const runtime = await readRuntime2();
|
|
1803
|
+
console.log(`node: ${process.version}`);
|
|
1804
|
+
if (globals.connect) {
|
|
1805
|
+
console.log("machine service: skipped (--connect)");
|
|
1806
|
+
} else if (system) {
|
|
1807
|
+
console.log(`system service (product): healthy (${system.baseUrl})`);
|
|
1808
|
+
} else if (broker?.present && broker.healthy && broker.serviceRole === "machine-engine") {
|
|
1809
|
+
console.log(
|
|
1810
|
+
`machine engine: healthy (${broker.baseUrl}) version=${broker.version} \u2014 compute broker; the product API is the per-user daemon`
|
|
1811
|
+
);
|
|
1812
|
+
} else if (broker?.present && broker.healthy === false) {
|
|
1813
|
+
console.log(`machine service: runtime files present but unreachable (port ${broker.port})`);
|
|
1814
|
+
} else if (broker?.present) {
|
|
1815
|
+
console.log(
|
|
1816
|
+
`machine service: healthy (${broker.baseUrl}) role=${broker.serviceRole ?? "legacy-full"} (not selected for this command)`
|
|
1817
|
+
);
|
|
1818
|
+
} else {
|
|
1819
|
+
console.log("machine service: not installed");
|
|
1820
|
+
}
|
|
1821
|
+
console.log(`runtime file: ${runtime ? "present" : "missing"}`);
|
|
1822
|
+
if (runtime) {
|
|
1823
|
+
const alive = isProcessAlive2(runtime.pid);
|
|
1824
|
+
console.log(` port=${runtime.port} pid=${runtime.pid} alive=${alive}`);
|
|
1825
|
+
if (alive) {
|
|
1826
|
+
try {
|
|
1827
|
+
const client = new GezelClient2({
|
|
1828
|
+
baseUrl: runtime.baseUrl,
|
|
1829
|
+
token: "",
|
|
1830
|
+
...runtime.cert ? { fetch: createTrustingFetch2({ cert: runtime.cert }) } : {}
|
|
1831
|
+
});
|
|
1832
|
+
const health = await client.health();
|
|
1833
|
+
const engineNote = health.machineEngineConnected !== void 0 ? ` machine engine connected: ${health.machineEngineConnected ? "yes" : "no"}` : "";
|
|
1834
|
+
console.log(` role=${health.serviceRole ?? "user"}${engineNote}`);
|
|
1835
|
+
} catch {
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
});
|
|
1840
|
+
program.command("cleanup").description("Show or reclaim the space Gezel is using on this device").option("--refresh", "Re-measure instead of using the cached sizes").option("--models", "Delete downloaded models").option("--engines", "Delete engine binaries and their caches").option("--toolsets", "Delete installed tools and the automation browser").option("--caches", "Delete catalog content and generated indexes").option("--redownloadable", "Delete everything Gezel can download again").option(
|
|
1841
|
+
"--content <what>",
|
|
1842
|
+
"Delete your own content: gezels, projects, documents, settings, or all"
|
|
1843
|
+
).option("--dry-run", "Show what would be deleted without deleting anything").option("--yes", "Skip the confirmation prompt").action(async (opts) => {
|
|
1844
|
+
const client = await connectOwned(cliGlobals());
|
|
1845
|
+
const selection = resolveCleanupSelection(opts);
|
|
1846
|
+
if (selection.categories.length === 0) {
|
|
1847
|
+
const summary2 = await client.storageSummary(opts.refresh ? { refresh: true } : void 0);
|
|
1848
|
+
console.log(formatStorageSummary(summary2));
|
|
1849
|
+
if (!opts.dryRun) {
|
|
1850
|
+
console.log(
|
|
1851
|
+
"\nTo reclaim space, re-run with --redownloadable (safe: Gezel downloads these again)."
|
|
1852
|
+
);
|
|
1853
|
+
}
|
|
1854
|
+
return;
|
|
1855
|
+
}
|
|
1856
|
+
const summary = await client.storageSummary({ refresh: true });
|
|
1857
|
+
console.log(formatCleanupPreview(summary, selection.categories));
|
|
1858
|
+
if (opts.dryRun) {
|
|
1859
|
+
console.log("\nDry run \u2014 nothing was deleted.");
|
|
1860
|
+
return;
|
|
1861
|
+
}
|
|
1862
|
+
if (selection.destroysUserContent) {
|
|
1863
|
+
const confirmed = await confirmByTyping(
|
|
1864
|
+
'This permanently deletes content only you have. Type "delete my content" to continue: ',
|
|
1865
|
+
"delete my content"
|
|
1866
|
+
);
|
|
1867
|
+
if (!confirmed) {
|
|
1868
|
+
console.log("Cancelled.");
|
|
1869
|
+
return;
|
|
1870
|
+
}
|
|
1871
|
+
} else if (!opts.yes) {
|
|
1872
|
+
const confirmed = await confirmByTyping('Delete these? Type "yes" to continue: ', "yes");
|
|
1873
|
+
if (!confirmed) {
|
|
1874
|
+
console.log("Cancelled.");
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
const { jobId } = await client.startCleanup({
|
|
1879
|
+
categories: selection.categories,
|
|
1880
|
+
...selection.destroysUserContent ? { confirmUserContent: true } : {}
|
|
1881
|
+
});
|
|
1882
|
+
const job = await pollStorageJob(client, jobId);
|
|
1883
|
+
console.log(formatCleanupResult(job));
|
|
1884
|
+
if (job.status === "error") process.exitCode = 1;
|
|
1885
|
+
});
|
|
1886
|
+
program.command("backup <file>").description("Write your gezels, projects, and documents to a backup file").option("--no-workspaces", "Leave project working files out of the backup").option("--dry-run", "Show what would be included without writing the file").action(async (file, opts) => {
|
|
1887
|
+
const client = await connectOwned(cliGlobals());
|
|
1888
|
+
const outPath = resolvePath(file);
|
|
1889
|
+
const excludeWorkspaces = opts.workspaces === false;
|
|
1890
|
+
const plan = await client.planBackup({ destPath: outPath, excludeWorkspaces });
|
|
1891
|
+
console.log(formatBackupPlan(plan));
|
|
1892
|
+
if (opts.dryRun) {
|
|
1893
|
+
console.log("\nDry run \u2014 no file was written.");
|
|
1894
|
+
return;
|
|
1895
|
+
}
|
|
1896
|
+
if (plan.items.length === 0) throw new CliError("There is nothing to back up yet.");
|
|
1897
|
+
const { jobId } = await client.startBackup({ outPath, excludeWorkspaces });
|
|
1898
|
+
const job = await pollStorageJob(client, jobId);
|
|
1899
|
+
if (job.status === "error") {
|
|
1900
|
+
throw new CliError(`Backup failed: ${job.error ?? "unknown error"}`);
|
|
1901
|
+
}
|
|
1902
|
+
console.log(`
|
|
1903
|
+
Wrote ${outPath}`);
|
|
1904
|
+
});
|
|
1905
|
+
program.command("restore <file>").description("Restore gezels, projects, and documents from a backup file").option("--list", "Show what the backup holds without restoring anything").option(
|
|
1906
|
+
"--only <item...>",
|
|
1907
|
+
"Restore just these items, by id (repeatable, e.g. --only tamsin roof-survey)"
|
|
1908
|
+
).option("--replace", "Overwrite items that already exist here").option("--settings", "Also restore preferences from the backup").action(
|
|
1909
|
+
async (file, opts) => {
|
|
1910
|
+
const client = await connectOwned(cliGlobals());
|
|
1911
|
+
const review = await client.scanRestore({ path: resolvePath(file) });
|
|
1912
|
+
console.log(formatRestoreReview(review));
|
|
1913
|
+
if (opts.list) return;
|
|
1914
|
+
const selection = resolveRestoreSelection(review, opts);
|
|
1915
|
+
for (const note of selection.skipped) console.log(` skipping ${note}`);
|
|
1916
|
+
if (selection.items.length === 0) {
|
|
1917
|
+
console.log("\nNothing to restore.");
|
|
1918
|
+
await client.cancelRestore(review.restoreId);
|
|
1919
|
+
return;
|
|
1920
|
+
}
|
|
1921
|
+
const { jobId } = await client.confirmRestore(review.restoreId, {
|
|
1922
|
+
items: selection.items,
|
|
1923
|
+
...opts.settings ? { settings: true } : {}
|
|
1924
|
+
});
|
|
1925
|
+
const job = await pollStorageJob(client, jobId);
|
|
1926
|
+
if (job.status === "error") {
|
|
1927
|
+
throw new CliError(`Restore failed: ${job.error ?? "unknown error"}`);
|
|
1928
|
+
}
|
|
1929
|
+
console.log(`
|
|
1930
|
+
Restored ${selection.items.length} item(s).`);
|
|
1931
|
+
if (job.restartRequired) console.log("Restart Gezel to see them.");
|
|
1932
|
+
}
|
|
1933
|
+
);
|
|
1934
|
+
function resolvePath(file) {
|
|
1935
|
+
return isAbsolutePath(file) ? file : joinPath(process.cwd(), file);
|
|
1936
|
+
}
|
|
1937
|
+
async function confirmByTyping(prompt, required) {
|
|
1938
|
+
if (!process.stdin.isTTY) {
|
|
1939
|
+
throw new CliError(
|
|
1940
|
+
"Refusing to delete without a confirmation. Re-run in a terminal, or use --dry-run to preview."
|
|
1941
|
+
);
|
|
1942
|
+
}
|
|
1943
|
+
const { createInterface } = await import("readline/promises");
|
|
1944
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
1945
|
+
try {
|
|
1946
|
+
const answer = await rl.question(prompt);
|
|
1947
|
+
return answer.trim().toLowerCase() === required;
|
|
1948
|
+
} finally {
|
|
1949
|
+
rl.close();
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
async function pollStorageJob(client, jobId) {
|
|
1953
|
+
for (; ; ) {
|
|
1954
|
+
const job = await client.getStorageJob(jobId);
|
|
1955
|
+
if (job.status === "done" || job.status === "error" || job.status === "cancelled") {
|
|
1956
|
+
if (process.stderr.isTTY) process.stderr.write("\n");
|
|
1957
|
+
return job;
|
|
1958
|
+
}
|
|
1959
|
+
if (process.stderr.isTTY) {
|
|
1960
|
+
const label = job.currentLabel ? ` ${job.currentLabel}` : "";
|
|
1961
|
+
process.stderr.write(
|
|
1962
|
+
`\r${job.phase ?? "working"}${label} \u2014 ${job.itemsDone}/${job.totalItems} `
|
|
1963
|
+
);
|
|
1964
|
+
}
|
|
1965
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
program.parseAsync(process.argv).catch((err) => {
|
|
1969
|
+
if (err instanceof CliError) console.error(err.message);
|
|
1970
|
+
else console.error(err);
|
|
1971
|
+
process.exit(1);
|
|
1972
|
+
});
|