@h1r-ai/croche-cli 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,468 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { constants } from 'node:fs';
4
+ import { lstat, mkdir, open, unlink } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { CliError } from './index.js';
9
+ import { requestControl } from './control-client.js';
10
+ import { decodeTextFile } from './text-file.js';
11
+ const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
12
+ const safeToken = (value, min = 16) => typeof value === 'string' && new RegExp(`^[A-Za-z0-9._~-]{${min},4096}$`).test(value);
13
+ /** Runtime metadata is untrusted text, not terminal formatting. */
14
+ const terminalLabel = (value) => value.replace(/[\u0000-\u001f\u007f-\u009f\u2028-\u202e\u2066-\u2069]/g, '').slice(0, 180);
15
+ function origin(value) {
16
+ let url;
17
+ try {
18
+ url = new URL(String(value));
19
+ }
20
+ catch {
21
+ throw new CliError('invalid_connection', 'Connection file needs a loopback HTTP origin.');
22
+ }
23
+ if (url.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== '/')
24
+ throw new CliError('invalid_connection', 'Connection file needs a loopback HTTP origin without credentials or a path.');
25
+ return url.origin;
26
+ }
27
+ function portNumber(value, fallback) { if (value === undefined)
28
+ return fallback; if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535)
29
+ throw new CliError('invalid_argument', 'Port must be an integer from 1 to 65535.'); return Number(value); }
30
+ export function defaultConnectionFile(kind, env = process.env, port = kind === 'debugger' ? 8790 : 8791) {
31
+ const state = process.platform === 'win32' ? (env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')) : process.platform === 'darwin' ? join(homedir(), 'Library', 'Application Support') : (env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'));
32
+ if (!isAbsolute(state))
33
+ throw new CliError('invalid_configuration', 'The OS user state directory must be absolute.');
34
+ return join(state, 'croche', kind, port === (kind === 'debugger' ? 8790 : 8791) ? 'connection.json' : `connection-${port}.json`);
35
+ }
36
+ function location(kind, args, env) {
37
+ const configured = kind === 'control' ? env.CROCHE_CONTROL_URL : undefined;
38
+ const url = configured ? origin(configured) : `http://127.0.0.1:${portNumber(kind === 'debugger' ? args.port : undefined, kind === 'debugger' ? 8790 : 8791)}`;
39
+ const port = Number(new URL(url).port || 80);
40
+ const file = resolve(kind === 'debugger' ? (args['connection-file'] ?? defaultConnectionFile(kind, env, port)) : (args['control-connection-file'] ?? env.CROCHE_CONTROL_CONNECTION_FILE ?? defaultConnectionFile(kind, env, port)));
41
+ return { url, file, explicitPort: kind === 'debugger' ? args.port !== undefined : Boolean(configured) };
42
+ }
43
+ async function readConnection(file, kind) {
44
+ let parent = dirname(file);
45
+ while (parent !== dirname(parent)) {
46
+ // Windows has no POSIX mode bits: libuv reports every directory without the read-only
47
+ // attribute as 0o666, so the group/other-write check would refuse every directory there.
48
+ // On win32 the directory relies on the user-profile ACL, like the file check below.
49
+ try {
50
+ const info = await lstat(parent);
51
+ if (info.isSymbolicLink() || (process.platform !== 'win32' && (info.mode & 0o022) !== 0 && (info.mode & 0o1000) === 0))
52
+ throw new CliError('insecure_connection_file', 'Connection directories must not be symbolic links or writable by other users.');
53
+ }
54
+ catch (error) {
55
+ if (error.code !== 'ENOENT')
56
+ throw error;
57
+ }
58
+ parent = dirname(parent);
59
+ }
60
+ let handle;
61
+ try {
62
+ handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
63
+ }
64
+ catch (error) {
65
+ if (error.code === 'ENOENT')
66
+ return;
67
+ throw new CliError('invalid_connection_file', 'The private connection file could not be opened.');
68
+ }
69
+ try {
70
+ const stat = await handle.stat();
71
+ if (!stat.isFile() || stat.size > 16384 || (process.platform !== 'win32' && ((stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid()))))
72
+ throw new CliError('insecure_connection_file', 'The connection file must be owned by this user with mode 0600.');
73
+ let data;
74
+ try {
75
+ data = JSON.parse(decodeTextFile(await handle.readFile(), 'The connection file'));
76
+ }
77
+ catch (error) {
78
+ if (error instanceof CliError)
79
+ throw error;
80
+ throw new CliError('invalid_connection_file', 'The connection file must contain valid JSON.');
81
+ }
82
+ const url = origin(data?.url), token = kind === 'debugger' ? data.pairingToken : data.token;
83
+ if (!safeToken(token, kind === 'control' ? 24 : 16))
84
+ throw new CliError('invalid_connection_file', 'The connection file does not contain a valid local token.');
85
+ // pairedUrl is deliberately rebuilt from validated fields, never trusted.
86
+ return { url, token, file };
87
+ }
88
+ finally {
89
+ await handle.close();
90
+ }
91
+ }
92
+ async function probe(kind, connection, transport) { return (await inspect(kind, connection, transport)).state; }
93
+ /** The probe, with the collector's own pid when it reports one (`debug stop` checks it). */
94
+ async function inspect(kind, connection, transport) {
95
+ let response;
96
+ try {
97
+ response = await transport(connection.url + (kind === 'debugger' ? '/api/probe' : '/v1/control/runtimes'), { headers: connection.token ? { Authorization: `Bearer ${connection.token}` } : {}, credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(1000) });
98
+ }
99
+ catch (error) {
100
+ return { state: error?.cause?.code === 'ECONNREFUSED' ? 'offline' : 'occupied' };
101
+ }
102
+ const reader = response.body?.getReader();
103
+ if (!reader)
104
+ return { state: 'occupied' };
105
+ try {
106
+ let raw = '', bytes = 0;
107
+ while (true) {
108
+ const next = await reader.read();
109
+ if (next.done)
110
+ break;
111
+ bytes += next.value.byteLength;
112
+ if (bytes > 65536)
113
+ return { state: 'occupied' };
114
+ raw += new TextDecoder().decode(next.value);
115
+ }
116
+ const data = JSON.parse(raw);
117
+ if (!(response.ok && (kind === 'debugger' ? data?.ok === true && typeof data.paused === 'boolean' : Array.isArray(data?.runtimes))))
118
+ return { state: 'occupied' };
119
+ return { state: 'running', ...(Number.isSafeInteger(data.pid) && data.pid > 0 ? { pid: data.pid } : {}) };
120
+ }
121
+ catch {
122
+ return { state: 'occupied' };
123
+ }
124
+ finally {
125
+ void reader.cancel().catch(() => { });
126
+ }
127
+ }
128
+ /** A dev Studio origin for --studio-origin: HTTPS, or HTTP on loopback only. */
129
+ function studioOrigin(value) {
130
+ if (value === undefined)
131
+ return [];
132
+ let url;
133
+ try {
134
+ url = new URL(value);
135
+ }
136
+ catch {
137
+ throw new CliError('invalid_argument', '--studio-origin must be an origin such as http://localhost:5173.');
138
+ }
139
+ if (url.origin !== value || !(url.protocol === 'https:' || (url.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(url.hostname))))
140
+ throw new CliError('invalid_argument', '--studio-origin must be an HTTPS origin, or an HTTP loopback origin, with no path.');
141
+ return [url.origin];
142
+ }
143
+ /** A fresh one-time Studio link from the running collector (docs/DEBUG-PAIRING.md P2). */
144
+ async function studioLink(connection, transport, wanted) {
145
+ let data;
146
+ try {
147
+ const response = await transport(connection.url + '/api/debug/codes', { method: 'POST', headers: { Authorization: `Bearer ${connection.token}` }, credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(2000) });
148
+ if (!response.ok)
149
+ throw new Error();
150
+ data = await response.json();
151
+ }
152
+ catch {
153
+ throw new CliError('studio_link_unavailable', 'The running debugger could not issue a Studio link. Restart it with this CLI version.', 4);
154
+ }
155
+ if (typeof data?.studioUrl !== 'string' || typeof data?.expires_at !== 'string')
156
+ throw new CliError('studio_link_unavailable', 'The running debugger returned no Studio link.', 4);
157
+ if (wanted.length && !data.studioUrl.startsWith(wanted[0] + '/'))
158
+ throw new CliError('studio_origin_unavailable', 'The running debugger was started without that Studio origin. Stop it, then run croche debug start --studio-origin ORIGIN.');
159
+ return { studioUrl: data.studioUrl, expiresAt: data.expires_at };
160
+ }
161
+ async function launch(kind, connection, options = {}) {
162
+ const port = new URL(connection.url).port || '80';
163
+ const script = fileURLToPath(new URL(kind === 'debugger' ? './debugger/server/server.js' : './bin.js', import.meta.url));
164
+ // The children (debugger server, control broker) never resolve the state directory or touch
165
+ // the connection file: the parent owns it and passes only the port and token. If a child ever
166
+ // does, pass the variables defaultConnectionFile reads (LOCALAPPDATA, USERPROFILE, XDG_STATE_HOME, HOME).
167
+ const env = {};
168
+ for (const name of ['PATH', 'SystemRoot', 'WINDIR', 'TMPDIR', 'TEMP'])
169
+ if (process.env[name])
170
+ env[name] = process.env[name];
171
+ if (kind === 'debugger') {
172
+ env.CROCHE_DEBUGGER_PORT = port;
173
+ env.CROCHE_DEBUGGER_TOKEN = connection.token;
174
+ if (options.studioOrigins?.length)
175
+ env.CROCHE_DEBUGGER_STUDIO_ORIGINS = options.studioOrigins.join(',');
176
+ }
177
+ else
178
+ env.CROCHE_CONTROL_TOKEN = connection.token;
179
+ const child = spawn(process.execPath, [script, ...(kind === 'control' ? ['control', 'serve', '--port', port] : [])], { detached: true, stdio: 'ignore', windowsHide: true, env });
180
+ await new Promise((yes, no) => { child.once('spawn', yes); child.once('error', () => no(new CliError('debug_start_failed', 'The bundled local service could not start.', 4))); });
181
+ child.unref();
182
+ return child.pid;
183
+ }
184
+ /** Where `debug start` records the collector it launched: `{pid,url}`, beside the connection file.
185
+ * It is never trusted alone: `debug stop` terminates that pid only when the collector, answering
186
+ * with the pairing token on the recorded URL, reports the same pid. */
187
+ const runFile = (file) => file + '.pid';
188
+ async function readRun(file) {
189
+ let handle;
190
+ try {
191
+ handle = await open(runFile(file), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
192
+ }
193
+ catch {
194
+ return;
195
+ }
196
+ try {
197
+ const stat = await handle.stat();
198
+ if (!stat.isFile() || stat.size > 1024)
199
+ return;
200
+ const data = JSON.parse((await handle.readFile()).toString('utf8'));
201
+ return Number.isSafeInteger(data?.pid) && data.pid > 0 && typeof data.url === 'string' ? { pid: data.pid, url: data.url } : undefined;
202
+ }
203
+ catch {
204
+ return;
205
+ }
206
+ finally {
207
+ await handle.close();
208
+ }
209
+ }
210
+ async function writeRun(file, pid, url) {
211
+ await unlink(runFile(file)).catch(() => { });
212
+ let handle;
213
+ try {
214
+ handle = await open(runFile(file), 'wx', 0o600);
215
+ await handle.writeFile(JSON.stringify({ pid, url }) + '\n');
216
+ }
217
+ catch { /* Without the record, stop still asks the collector to shut down; it only cannot fall back. */ }
218
+ finally {
219
+ await handle?.close();
220
+ }
221
+ }
222
+ /** One startup or stop at a time per connection file (the directory must exist). */
223
+ async function locked(file, body) {
224
+ const lockFile = file + '.lock', deadline = Date.now() + 6000;
225
+ let lock;
226
+ while (!lock) {
227
+ try {
228
+ lock = await open(lockFile, 'wx', 0o600);
229
+ }
230
+ catch (error) {
231
+ if (error.code !== 'EEXIST')
232
+ throw new CliError('connection_write_failed', 'The private connection directory is not writable.');
233
+ if (Date.now() >= deadline)
234
+ throw new CliError('connection_busy', 'Another local service startup or stop owns the connection lock. Retry after it finishes.');
235
+ await delay(100);
236
+ }
237
+ }
238
+ try {
239
+ return await body();
240
+ }
241
+ finally {
242
+ await lock.close();
243
+ await unlink(lockFile).catch(() => { });
244
+ }
245
+ }
246
+ async function ensure(kind, args, context, start) {
247
+ const selected = location(kind, args, context.env), transport = context.fetch ?? fetch;
248
+ async function load() {
249
+ const saved = await readConnection(selected.file, kind);
250
+ if (saved && selected.explicitPort && saved.url !== selected.url)
251
+ throw new CliError('connection_conflict', 'The configured port and saved connection do not match. Use a separate connection file.');
252
+ if (kind === 'control' && context.env.CROCHE_CONTROL_TOKEN) {
253
+ if (!safeToken(context.env.CROCHE_CONTROL_TOKEN, 24))
254
+ throw new CliError('invalid_configuration', 'CROCHE_CONTROL_TOKEN must be a valid local token.');
255
+ if (saved && (saved.token !== context.env.CROCHE_CONTROL_TOKEN || saved.url !== selected.url))
256
+ throw new CliError('connection_conflict', 'The control environment and saved connection do not match.');
257
+ return saved ?? { ...selected, token: context.env.CROCHE_CONTROL_TOKEN };
258
+ }
259
+ return saved;
260
+ }
261
+ let connection = await load();
262
+ let status = connection ? await probe(kind, connection, transport) : 'not_configured';
263
+ if (!start || status === 'running')
264
+ return { connection, status, started: false, file: selected.file, url: connection?.url ?? selected.url };
265
+ // An uncreatable directory (no permission, read-only volume) is the same failure as an unwritable one.
266
+ try {
267
+ await mkdir(dirname(selected.file), { recursive: true, mode: 0o700 });
268
+ }
269
+ catch (error) {
270
+ throw new CliError('connection_write_failed', `The private connection directory ${dirname(selected.file)} could not be created (${error.code ?? 'unknown error'}). Choose a writable location with --${kind === 'debugger' ? 'connection-file' : 'control-connection-file'}.`);
271
+ }
272
+ return locked(selected.file, async () => {
273
+ connection = await load();
274
+ const checked = connection ?? { ...selected, token: '' };
275
+ status = await probe(kind, checked, transport);
276
+ if (status === 'running')
277
+ return { connection, status, started: false, file: selected.file, url: checked.url };
278
+ if (status !== 'offline')
279
+ throw new CliError('local_port_occupied', 'The local port is occupied or cannot be authenticated. Import its existing private connection file; the running service was not changed.', 4);
280
+ if (!connection)
281
+ connection = { ...selected, token: randomBytes(32).toString('hex') };
282
+ // Exclusive create preserves an existing token and its live capture session.
283
+ let file;
284
+ try {
285
+ file = await open(selected.file, 'wx', 0o600);
286
+ await file.writeFile(JSON.stringify(kind === 'debugger' ? { url: connection.url, pairedUrl: `${connection.url}/#token=${connection.token}`, pairingToken: connection.token } : { url: connection.url, token: connection.token }) + '\n');
287
+ await file.sync();
288
+ }
289
+ catch (error) {
290
+ if (error.code !== 'EEXIST')
291
+ throw new CliError('connection_write_failed', 'The private connection file could not be saved.');
292
+ }
293
+ finally {
294
+ await file?.close();
295
+ }
296
+ const reread = await readConnection(selected.file, kind);
297
+ if (!reread || reread.token !== connection.token || reread.url !== connection.url)
298
+ throw new CliError('connection_conflict', 'The connection changed during startup; no service was launched.');
299
+ const pid = await (context.launch ?? launch)(kind, connection, { studioOrigins: studioOrigin(args['studio-origin']) });
300
+ if (kind === 'debugger' && typeof pid === 'number')
301
+ await writeRun(selected.file, pid, connection.url);
302
+ const readyDeadline = Date.now() + 5000;
303
+ while (Date.now() < readyDeadline) {
304
+ if (await probe(kind, connection, transport) === 'running')
305
+ return { connection, status: 'running', started: true, file: selected.file, url: connection.url };
306
+ await delay(100);
307
+ }
308
+ throw new CliError('debug_start_failed', 'The local service did not become ready. Its saved token was preserved; no existing service was stopped.', 4);
309
+ });
310
+ }
311
+ /** `croche debug stop`: asks the collector to shut down with its pairing token. Only when it is
312
+ * still running after that, and reports the very pid `debug start` recorded, is that pid
313
+ * terminated. An unanswered port, or a pid it cannot tie to the collector, is never killed. The
314
+ * connection file (and so the pairing token) is kept for the next start; the run record goes. */
315
+ async function stop(args, context) {
316
+ const selected = location('debugger', args, context.env), transport = context.fetch ?? fetch;
317
+ const saved = await readConnection(selected.file, 'debugger');
318
+ if (!saved)
319
+ return { status: 'not_configured', stopped: false, url: selected.url, connectionFile: selected.file, instruction: 'No debugger connection is saved here, so no debugger started by this CLI is running. Nothing was stopped.' };
320
+ return locked(selected.file, async () => {
321
+ const connection = await readConnection(selected.file, 'debugger');
322
+ if (!connection)
323
+ return { status: 'not_configured', stopped: false, url: selected.url, connectionFile: selected.file, instruction: 'No debugger connection is saved here. Nothing was stopped.' };
324
+ if (selected.explicitPort && connection.url !== selected.url)
325
+ throw new CliError('connection_conflict', 'The configured port and saved connection do not match. Use a separate connection file.');
326
+ const done = (method) => ({ status: 'offline', stopped: method !== undefined, ...(method ? { method } : {}), url: connection.url, connectionFile: selected.file,
327
+ instruction: method ? 'The debugger stopped; its captures are discarded. The pairing token is kept: croche debug start reuses it.' : 'The debugger is not running. Nothing was stopped. The pairing token is kept: croche debug start reuses it.' });
328
+ async function stopped(ms) { const deadline = Date.now() + ms; while (true) {
329
+ if (await probe('debugger', connection, transport) === 'offline')
330
+ return true;
331
+ if (Date.now() >= deadline)
332
+ return false;
333
+ await delay(100);
334
+ } }
335
+ const first = await inspect('debugger', connection, transport);
336
+ if (first.state === 'offline') {
337
+ await unlink(runFile(selected.file)).catch(() => { });
338
+ return done(undefined);
339
+ }
340
+ if (first.state === 'occupied')
341
+ throw new CliError('local_port_occupied', 'The debugger port is in use but did not answer as this collector (or not in time). Nothing was stopped.', 4);
342
+ // A collector from an older CLI has no shutdown endpoint (404); the wait below is the check.
343
+ let asked = false;
344
+ try {
345
+ asked = (await transport(connection.url + '/api/shutdown', { method: 'POST', headers: { Authorization: `Bearer ${connection.token}` }, credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(2000) })).ok;
346
+ }
347
+ catch {
348
+ asked = true;
349
+ }
350
+ if (await stopped(asked ? 5000 : 0)) {
351
+ await unlink(runFile(selected.file)).catch(() => { });
352
+ return done('shutdown');
353
+ }
354
+ // Still running: terminate it only if it is provably the process start recorded.
355
+ const run = await readRun(selected.file), now = await inspect('debugger', connection, transport);
356
+ if (run && run.url === connection.url && now.state === 'running' && now.pid === run.pid) {
357
+ try {
358
+ process.kill(run.pid);
359
+ }
360
+ catch (error) {
361
+ if (error.code !== 'ESRCH')
362
+ throw new CliError('debug_stop_failed', 'The debugger process could not be terminated.', 4);
363
+ }
364
+ if (await stopped(5000)) {
365
+ await unlink(runFile(selected.file)).catch(() => { });
366
+ return done('terminated');
367
+ }
368
+ }
369
+ throw new CliError('debug_stop_failed', `The debugger is still running${asked ? '' : ' (it predates croche debug stop)'} and its process could not be verified, so nothing was killed. Stop it from the terminal or task manager that shows its process.`, 4);
370
+ });
371
+ }
372
+ function publicStatus(value) { return { status: value.status, url: value.url, connectionFile: value.file, started: value.started }; }
373
+ export async function debugCommand(action, args, context) {
374
+ if (action === 'stop')
375
+ return stop(args, context);
376
+ if (action === 'status')
377
+ return publicStatus(await ensure('debugger', args, context, false));
378
+ if (action === 'token') {
379
+ const selected = await ensure('debugger', args, context, false);
380
+ if (!selected.connection)
381
+ throw new CliError('not_configured', 'Run croche debug start to create a debugger connection.');
382
+ return { pairingToken: selected.connection.token };
383
+ }
384
+ const origins = studioOrigin(args['studio-origin']);
385
+ if (action === 'start') {
386
+ const started = await ensure('debugger', args, context, true), next = 'Run croche debug to choose an available Runtime, or croche debug connect --runtime-id ID.';
387
+ // A collector still running from an older CLI has no Studio links; start still succeeds.
388
+ let link;
389
+ try {
390
+ link = await studioLink(started.connection, context.fetch ?? fetch, origins);
391
+ }
392
+ catch (error) {
393
+ if (error instanceof CliError && error.code === 'studio_link_unavailable' && !origins.length)
394
+ return { ...publicStatus(started), instruction: `${next} This debugger cannot issue Studio links; restart it with this CLI version to observe from Studio.` };
395
+ throw error;
396
+ }
397
+ return { ...publicStatus(started), ...link, instruction: `Open studioUrl in Studio to observe this debugger (one use, 10 minutes; croche debug --studio-link issues another). ${next}` };
398
+ }
399
+ if (action === 'choose' && args['studio-link'] !== undefined) {
400
+ if (args['studio-link'] !== 'true')
401
+ throw new CliError('invalid_argument', '--studio-link takes no value.');
402
+ const started = await ensure('debugger', args, context, true);
403
+ return { ...await studioLink(started.connection, context.fetch ?? fetch, origins), instruction: 'Open this link in Studio to observe runtime-visibility events from this debugger. It works once, for 10 minutes.' };
404
+ }
405
+ const control = await ensure('control', args, context, true), connection = control.connection;
406
+ const env = { ...context.env, CROCHE_CONTROL_URL: connection.url, CROCHE_CONTROL_TOKEN: connection.token };
407
+ async function discover() { try {
408
+ return await requestControl('list', {}, env, context.fetch);
409
+ }
410
+ catch {
411
+ throw new CliError('control_unavailable', 'The local control broker could not list Runtimes.', 4);
412
+ } }
413
+ let list = await discover();
414
+ if (!list.runtimes.length && ['choose', 'runtimes'].includes(action)) {
415
+ const deadline = Date.now() + 3000;
416
+ while (!list.runtimes.length && Date.now() < deadline) {
417
+ await delay(250);
418
+ list = await discover();
419
+ }
420
+ }
421
+ const runtimes = list.runtimes.map(entry => {
422
+ const appName = String(entry.runtime?.appName ?? entry.runtime?.projectId ?? 'Runtime'), appUrl = typeof entry.runtime?.appUrl === 'string' ? entry.runtime.appUrl : undefined;
423
+ return { id: String(entry.runtime?.runtimeInstanceId ?? ''), appName, ...(appUrl ? { appUrl } : {}), label: terminalLabel(appName) + (appUrl ? ` — ${terminalLabel(appUrl)}` : ''), debugAvailable: Array.isArray(entry.capabilities) && entry.capabilities.includes('debug.attach'), lastSeenAt: entry.last_seen_at };
424
+ });
425
+ if (action === 'runtimes' || (action === 'choose' && !context.selectRuntime))
426
+ return { runtimes, instruction: 'Choose a Runtime with debugAvailable=true, then run croche debug connect --runtime-id ID. Keep your development app open.' };
427
+ // Public builds provide runtime projection only. Explicit full is for private internal-debug
428
+ // builds; Core refuses it in public builds regardless of a debug key.
429
+ const visibility = args.visibility ?? 'runtime';
430
+ if (!['full', 'runtime'].includes(visibility))
431
+ throw new CliError('invalid_argument', '--visibility must be full or runtime.');
432
+ let runtimeId = args['runtime-id'];
433
+ if (action === 'choose') {
434
+ const available = runtimes.filter(runtime => runtime.debugAvailable);
435
+ if (!available.length)
436
+ return { runtimes, instruction: 'No debug-capable Runtime is attached. Open your development app, then run croche debug again.' };
437
+ runtimeId = await context.selectRuntime(available) ?? '';
438
+ if (!runtimeId)
439
+ return { cancelled: true };
440
+ }
441
+ if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(runtimeId ?? ''))
442
+ throw new CliError('invalid_argument', 'Supply a valid --runtime-id.');
443
+ if (action === 'disconnect') {
444
+ if (!list.runtimes.some((entry) => entry.runtime?.runtimeInstanceId === runtimeId && entry.capabilities?.includes('debug.detach')))
445
+ throw new CliError('runtime_not_available', 'The selected Runtime does not currently expose debugger detachment.', 1);
446
+ try {
447
+ await requestControl('debug.detach', { 'runtime-id': runtimeId, 'wait-ms': '30000' }, env, context.fetch, {});
448
+ }
449
+ catch {
450
+ throw new CliError('debug_detach_failed', 'Runtime debugger detachment did not complete. Inspect the Runtime and broker before retrying.', 1);
451
+ }
452
+ return { runtimeId, attached: false, instruction: 'Debugger detached from this Runtime. The server remains available with its captured traces.' };
453
+ }
454
+ if (!runtimes.some(runtime => runtime.id === runtimeId && runtime.debugAvailable))
455
+ throw new CliError('runtime_not_available', 'The selected Runtime is not currently attached with debugger capability.', 1);
456
+ const debuggerState = await ensure('debugger', args, context, true), debuggerConnection = debuggerState.connection;
457
+ try {
458
+ await requestControl('debug.attach', { 'runtime-id': runtimeId, 'wait-ms': '30000' }, env, context.fetch, { url: debuggerConnection.url, token: debuggerConnection.token, visibility });
459
+ }
460
+ catch {
461
+ throw new CliError('debug_attach_failed', 'Runtime debugger attachment did not complete. Inspect the Runtime and broker before retrying.', 1);
462
+ }
463
+ if (visibility === 'runtime') {
464
+ const link = await studioLink(debuggerConnection, context.fetch ?? fetch, origins);
465
+ return { runtimeId, attached: true, visibility, ...link, pairedUrl: `${debuggerConnection.url}/#token=${encodeURIComponent(debuggerConnection.token)}&runtime=${encodeURIComponent(runtimeId)}`, instruction: 'Attached in the public runtime view. Open studioUrl in Studio to observe it (one use, 10 minutes); the local link above shows the same public view.' };
466
+ }
467
+ return { runtimeId, attached: true, visibility, pairedUrl: `${debuggerConnection.url}/#token=${encodeURIComponent(debuggerConnection.token)}&runtime=${encodeURIComponent(runtimeId)}`, instruction: 'The selected Runtime is already attached to this debugger server. Open this URL to inspect its traces. Studio shows only the public view; attach with --visibility runtime to observe it there.' };
468
+ }
package/dist/help.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ export type HelpCommand = {
2
+ path: string;
3
+ summary: string;
4
+ positionals?: string[];
5
+ flags?: string[];
6
+ switches?: string[];
7
+ };
8
+ type Row = {
9
+ label: string;
10
+ brief: string;
11
+ paths: string[];
12
+ };
13
+ /** Every command appears in exactly one row (the help tests census this). */
14
+ export declare const sections: readonly {
15
+ title: string;
16
+ rows: readonly Row[];
17
+ }[];
18
+ /** `croche --help`: every section, one aligned line per command. */
19
+ export declare function overview(): string;
20
+ /** `croche <command> --help`: usage, what it does, one line per option. */
21
+ export declare function commandHelp(command: HelpCommand): string;
22
+ /** `croche <group> --help`, such as `croche debug --help`: the group's commands. */
23
+ export declare function groupHelp(prefix: string, group: readonly HelpCommand[]): string;
24
+ export {};
package/dist/help.js ADDED
@@ -0,0 +1,158 @@
1
+ // Help text for people: plain text within 80 columns, no colour. Command names and flags
2
+ // come from the command table in index.ts; this file only groups and words them.
3
+ const runtimeActions = ['list', 'status', 'history', 'send', 'cancel', 'sync', 'tools', 'budget get', 'budget set', 'result'];
4
+ const row = (path, brief) => ({ label: path, brief, paths: [path] });
5
+ /** Every command appears in exactly one row (the help tests census this). */
6
+ export const sections = [
7
+ { title: 'Getting started', rows: [
8
+ row('login', 'Save your account key (typed at a hidden prompt)'),
9
+ row('logout', 'Remove the saved account key'),
10
+ row('auth whoami', 'Show your account and where the key comes from'),
11
+ ] },
12
+ { title: 'Projects', rows: [
13
+ row('projects list', 'List your projects'),
14
+ row('projects create', 'Create a project with a $10 monthly budget'),
15
+ row('projects get', 'Show one project'),
16
+ row('projects update', 'Rename a project or change its model routing'),
17
+ row('projects usage', 'Usage per user and agent, and budget left'),
18
+ row('projects cost', 'All-time known cost'),
19
+ row('projects operations', 'Recent operations'),
20
+ row('runtimes list', 'Runtimes enrolled with Cloud for a project'),
21
+ ] },
22
+ { title: 'Keys', rows: [
23
+ row('debug-keys create', 'Issue a debug key and write it to .env'),
24
+ row('debug-keys list', 'List debug keys (no secrets)'),
25
+ row('debug-keys revoke', 'Revoke a debug key'),
26
+ row('keys development list', 'Debug keys with installs, last use, warnings'),
27
+ row('keys server list', 'Server keys with installs, last use, spend'),
28
+ row('attestation get', 'App Attest and Play Integrity settings'),
29
+ ] },
30
+ { title: 'Config', rows: [
31
+ row('config get', 'Read the draft, a revision or a version'),
32
+ row('config save', 'Save a draft over the version you last read'),
33
+ row('config list', 'Released versions and the draft'),
34
+ ] },
35
+ { title: 'Debugger (development only)', rows: [
36
+ row('debug start', 'Start the local debugger; prints a Studio link'),
37
+ row('debug', 'Pick a running app to watch (--studio-link)'),
38
+ row('debug status', 'Is the local debugger running?'),
39
+ row('debug runtimes', 'Running apps the debugger can see'),
40
+ row('debug connect', 'Attach one app and print its viewer link'),
41
+ row('debug disconnect', 'Detach the debugger from one app'),
42
+ row('debug token', 'Reveal the local pairing token'),
43
+ row('debug stop', 'Stop the local debugger'),
44
+ ] },
45
+ { title: 'Local Runtime control (advanced)', rows: [
46
+ row('control serve', 'Start the local control broker'),
47
+ { label: 'runtime <action>', brief: 'Drive a local Runtime: croche runtime --help', paths: runtimeActions.map(action => `runtime ${action}`) },
48
+ ] },
49
+ ];
50
+ const width = 24;
51
+ const line = (label, text) => ` ${label.padEnd(Math.max(width, label.length + 2))}${text}`.trimEnd();
52
+ const footer = [
53
+ 'Options',
54
+ line('-h, --help', 'Help; croche <command> --help for one command'),
55
+ line('--json', 'Machine-readable output for scripts and agents'),
56
+ line('--version', 'Print the CLI version'),
57
+ '',
58
+ 'Environment',
59
+ line('CROCHE_ACCOUNT_KEY', 'Account key, instead of croche login'),
60
+ line('CROCHE_CONTROL_TOKEN', 'Token for the local control broker'),
61
+ line('CROCHE_CONTROL_URL', 'Control broker (default http://127.0.0.1:8791)'),
62
+ '',
63
+ 'Examples',
64
+ ' croche login',
65
+ ' croche projects create --name "My app"',
66
+ ' croche debug-keys create --project <project-id>',
67
+ '',
68
+ 'Exit codes: 0 ok, 1 remote error, 2 usage or config, 3 auth, 4 network/timeout',
69
+ ];
70
+ /** `croche --help`: every section, one aligned line per command. */
71
+ export function overview() {
72
+ const body = sections.map(s => [s.title, ...s.rows.map(r => line(r.label, r.brief))].join('\n')).join('\n\n');
73
+ return ['Croche CLI: build apps on Croche from your terminal.', '', 'Usage: croche <command> [options]', '', body, '', ...footer].join('\n') + '\n';
74
+ }
75
+ const runtimeBriefs = {
76
+ 'runtime list': 'Runtimes attached to the control broker',
77
+ 'runtime status': 'Status of a local Runtime',
78
+ 'runtime history': 'Read a local Runtime\'s messages',
79
+ 'runtime send': 'Send a message to a local Runtime',
80
+ 'runtime cancel': 'Cancel a local Runtime\'s turn',
81
+ 'runtime sync': 'Sync a local Runtime with Cloud',
82
+ 'runtime tools': 'List a local Runtime\'s tools',
83
+ 'runtime budget get': 'Read a local Runtime\'s budget',
84
+ 'runtime budget set': 'Set a local Runtime\'s budget',
85
+ 'runtime result': 'Look up an earlier control request',
86
+ };
87
+ const briefs = { ...Object.fromEntries(sections.flatMap(s => s.rows.filter(r => r.paths.length === 1).map(r => [r.label, r.brief]))), ...runtimeBriefs };
88
+ // One line per flag: [value name, description]. `<path> <flag>` entries override for one command.
89
+ const flagHelp = {
90
+ project: ['ID', 'Project id'],
91
+ 'config project': ['ID', 'Project id (or set CROCHE_PROJECT)'],
92
+ 'project-id': ['ID', 'Project id'],
93
+ name: ['NAME', 'A name for the key'],
94
+ 'projects create name': ['NAME', 'Project name (required)'],
95
+ 'projects update name': ['NAME', 'New project name'],
96
+ 'env-file': ['PATH', 'Where to write CROCHE_DEBUG_KEY (default ./.env)'],
97
+ force: ['', 'Replace an existing CROCHE_DEBUG_KEY value'],
98
+ print: ['', 'Also print the key (hidden by default)'],
99
+ port: ['PORT', 'Debugger port (default 8790)'],
100
+ 'control serve port': ['PORT', 'Broker port (default 8791)'],
101
+ 'connection-file': ['PATH', 'Debugger connection file (default per OS)'],
102
+ 'control-connection-file': ['PATH', 'Control broker connection file'],
103
+ 'studio-origin': ['ORIGIN', 'A development Studio, e.g. http://localhost:5173'],
104
+ visibility: ['runtime', 'The view to attach (runtime)'],
105
+ 'studio-link': ['', 'Print a fresh one-time Studio link instead'],
106
+ 'runtime-id': ['ID', 'The Runtime to act on'],
107
+ revision: ['ID', 'Read this draft revision'],
108
+ version: ['N', 'Export released version N for bundling'],
109
+ output: ['PATH', 'Write to this file (-o PATH)'],
110
+ base: ['REVISION', 'Save over this revision (null: an empty draft)'],
111
+ note: ['TEXT', 'A note for this revision'],
112
+ 'policy-file': ['PATH', 'JSON runtime policy file'],
113
+ limit: ['N', 'How many to return (server limit 500)'],
114
+ 'runtime history limit': ['N', 'How many messages to return'],
115
+ status: ['STATUS', 'Only operations with this status'],
116
+ type: ['TYPE', 'Only operations of this type'],
117
+ query: ['TEXT', 'Only operations matching this text'],
118
+ period: ['PERIOD', 'week, month (default) or all'],
119
+ 'allow-origin': ['ORIGIN', 'Allow this browser origin (CORS is off otherwise)'],
120
+ 'control-url': ['URL', 'Broker URL (default CROCHE_CONTROL_URL, then :8791)'],
121
+ 'request-id': ['ID', 'Request id, so a retry is not sent twice'],
122
+ 'runtime result request-id': ['ID', 'The request to look up'],
123
+ 'wait-ms': ['MS', 'How long to wait (send 120000, others 15000)'],
124
+ offset: ['N', 'Skip this many messages'],
125
+ id: ['ID', 'Input id for this message'],
126
+ text: ['TEXT', 'Message text'],
127
+ 'text-file': ['PATH', 'Read the message text from a UTF-8 file'],
128
+ amount: ['AMOUNT', 'The new budget'],
129
+ };
130
+ function flagLine(path, flag) {
131
+ const [value, text] = flagHelp[`${path} ${flag}`] ?? flagHelp[`${path.split(' ')[0]} ${flag}`] ?? flagHelp[flag] ?? ['VALUE', ''];
132
+ return line(`--${flag}${value ? ' ' + value : ''}`, text);
133
+ }
134
+ function wrap(text, max = 80) {
135
+ const lines = [];
136
+ let current = '';
137
+ for (const word of text.split(' ')) {
138
+ if (current && current.length + 1 + word.length > max) {
139
+ lines.push(current);
140
+ current = word;
141
+ }
142
+ else
143
+ current = current ? current + ' ' + word : word;
144
+ }
145
+ return [...lines, current].join('\n');
146
+ }
147
+ /** `croche <command> --help`: usage, what it does, one line per option. */
148
+ export function commandHelp(command) {
149
+ const flags = [...(command.flags ?? []).filter(f => f !== 'cloud-url'), ...(command.switches ?? [])];
150
+ const usage = `Usage: croche ${command.path}${(command.positionals ?? []).map(p => ` <${p}>`).join('')}${flags.length ? ' [options]' : ''}`;
151
+ const options = flags.length ? ['', 'Options', ...flags.map(f => flagLine(command.path, f))] : [];
152
+ return [usage, '', wrap(command.summary), ...options, '', 'All commands: croche --help'].join('\n') + '\n';
153
+ }
154
+ /** `croche <group> --help`, such as `croche debug --help`: the group's commands. */
155
+ export function groupHelp(prefix, group) {
156
+ const rows = group.map(c => line(c.path, briefs[c.path] ?? ''));
157
+ return [`Commands under croche ${prefix}`, '', ...rows, '', 'Options for one command: croche <command> --help'].join('\n') + '\n';
158
+ }