@h1r-ai/croche-cli 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +267 -148
  2. package/THIRD-PARTY-NOTICES +7 -8
  3. package/dist/bin.js +29 -25
  4. package/dist/chunk-66EUX7EL.js +165 -0
  5. package/dist/chunk-DKT5HHSB.js +532 -0
  6. package/dist/chunk-K3UDT4EM.js +3110 -0
  7. package/dist/collector-credential.d.ts +9 -0
  8. package/dist/config-authoring.d.ts +19 -0
  9. package/dist/config-bases.d.ts +17 -0
  10. package/dist/config-push-base-35HX67AJ.js +2254 -0
  11. package/dist/config-push-base.d.ts +7 -0
  12. package/dist/control-address.d.ts +2 -0
  13. package/dist/control-server.d.ts +12 -15
  14. package/dist/control-server.js +9 -288
  15. package/dist/control-v2-auth.d.ts +24 -0
  16. package/dist/control-v2-capture.d.ts +34 -0
  17. package/dist/control-v2-json.d.ts +15 -0
  18. package/dist/control-v2-state.d.ts +90 -0
  19. package/dist/credentials.d.ts +2 -2
  20. package/dist/debugger/public/index.html +1 -0
  21. package/dist/debugger/public/stage-control.js +84 -0
  22. package/dist/debugger/public/stage-manifest.js +45 -0
  23. package/dist/debugger/public/stage-model.js +103 -0
  24. package/dist/debugger/public/stage-targets.js +18 -0
  25. package/dist/debugger/public/stage.css +459 -0
  26. package/dist/debugger/public/stage.html +17 -0
  27. package/dist/debugger/public/stage.js +113 -0
  28. package/dist/debugger/server/collector.js +42 -26
  29. package/dist/debugger/server/control-bridge.js +113 -0
  30. package/dist/debugger/server/server.js +10 -1
  31. package/dist/debugger/server/viewer-security.js +12 -0
  32. package/dist/debugger.d.ts +16 -6
  33. package/dist/index.d.ts +8 -1
  34. package/dist/index.js +17 -321
  35. package/dist/json-result.d.ts +2 -0
  36. package/package.json +2 -1
  37. package/dist/config.js +0 -100
  38. package/dist/control-client.js +0 -65
  39. package/dist/core-defaults.js +0 -2
  40. package/dist/credentials.js +0 -136
  41. package/dist/debug-keys.js +0 -141
  42. package/dist/debugger.js +0 -469
  43. package/dist/help.js +0 -158
  44. package/dist/text-file.js +0 -15
package/dist/index.js CHANGED
@@ -1,321 +1,17 @@
1
- import { commandHelp, groupHelp, overview } from './help.js';
2
- import { resolveCredential, storeCredential, removeCredential, readCredentialInput, validCredential, environmentCredentialNames } from './credentials.js';
3
- import { configCommand } from './config.js';
4
- import { DEFAULT_CLOUD_URL } from './core-defaults.js';
5
- import { debugKeys } from './debug-keys.js';
6
- import { readFileSync } from 'node:fs';
7
- import { readFile as readLocalFile } from 'node:fs/promises';
8
- import { decodeTextFile } from './text-file.js';
9
- import { requestControl } from './control-client.js';
10
- import { debugCommand } from './debugger.js';
11
- export class CliError extends Error {
12
- code;
13
- exitCode;
14
- details;
15
- constructor(code, message, exitCode = 2, details) {
16
- super(message);
17
- this.code = code;
18
- this.exitCode = exitCode;
19
- this.details = details;
20
- }
21
- }
22
- const segment = (value) => { if (!value || value.length > 200 || !/^[A-Za-z0-9_.:-]+$/.test(value))
23
- throw new CliError('invalid_argument', 'Identifiers must contain 1–200 letters, digits, dots, colons, underscores or hyphens.'); return encodeURIComponent(value); };
24
- function required(args, key) { const value = args[key]; if (value === undefined || !value.trim())
25
- throw new CliError('missing_argument', `Supply --${key}.`); return value; }
26
- function number(value, key, min = 0, max = 10000) { if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value) || !Number.isFinite(Number(value)) || Number(value) < min || Number(value) > max)
27
- throw new CliError('invalid_argument', `${key} must be a number between ${min} and ${max}.`); return Number(value); }
28
- function integer(value, key, min, max) { const result = number(value, key, min, max); if (!Number.isInteger(result))
29
- throw new CliError('invalid_argument', `${key} must be an integer.`); return result; }
30
- const project = (args) => `/api/studio/projects/${segment(required(args, 'project-id'))}`;
31
- function projectBody(args) { return args.name !== undefined ? { name: args.name } : {}; }
32
- const localCommands = ['status', 'history', 'send', 'cancel', 'sync', 'budget get', 'budget set', 'tools'];
33
- /** Declarative command tree: future Studio features add one descriptor. */
34
- export const commands = [
35
- ...['create', 'list', 'revoke'].map(action => ({ path: `debug-keys ${action}`, summary: { create: 'Issue a debug key and safely write CROCHE_DEBUG_KEY to .env; the secret is hidden unless --print is explicit.', list: 'List debug-key metadata without secrets.', revoke: 'Revoke a debug key.' }[action], positionals: action === 'revoke' ? ['key-id'] : [], flags: ['project', ...(action === 'create' ? ['name', 'env-file'] : [])], switches: action === 'create' ? ['force', 'print'] : [], run: (a, c) => debugKeys(action, a, c) })),
36
- ...['choose', 'start', 'stop', 'status', 'connect', 'disconnect', 'token', 'runtimes'].map(action => ({ path: action === 'choose' ? 'debug' : `debug ${action}`, summary: { choose: 'Discover local Runtimes and select one interactively; automation gets a list. --studio-link prints a fresh one-time Studio link instead.', start: 'Start or reuse the bundled local debugger without clearing captures, and print a one-time Studio link.', stop: 'Stop the local debugger that debug start launched (its captures are discarded); the pairing token is kept. Not running is success.', status: 'Inspect local debugger availability without printing credentials.', connect: 'Attach one Runtime and print its authenticated viewer link. --visibility runtime attaches the public view and prints a Studio link.', disconnect: 'Detach the debugger from one Runtime while retaining server captures.', token: 'Explicitly reveal the saved local debugger pairing token.', runtimes: 'List local Runtimes and their debugger capability.' }[action], flags: ['port', 'connection-file', ...(action === 'stop' ? [] : ['control-connection-file']), ...(['connect', 'disconnect'].includes(action) ? ['runtime-id'] : []), ...(['choose', 'start', 'connect'].includes(action) ? ['studio-origin'] : []), ...(['choose', 'connect'].includes(action) ? ['visibility'] : [])], switches: action === 'choose' ? ['studio-link'] : [], run: (a, c) => debugCommand(action, a, { env: c.env, fetch: c.context.fetch, selectRuntime: c.context.selectRuntime, launch: c.context.launchDebuggerService }) })),
37
- ...['get', 'save', 'list'].map(action => ({ path: `config ${action}`, summary: { get: 'Read the draft or one revision/version. Version exports carry their bundled version.', save: 'Save a draft against its last read base; a conflict never retries over another editor.', list: 'List released versions, applied counts, and the draft head.' }[action], positionals: action === 'save' ? ['file'] : [], flags: ['project', 'cloud-url', ...{ get: ['revision', 'version', 'output'], save: ['base', 'note'], list: [] }[action]], run: (a, c) => configCommand(action, a, { ...c, writeFile: c.context.writeFile, stderr: c.context.stderr ?? (text => process.stderr.write(text)) }) })),
38
- { path: 'login', summary: 'Human-only: validate and save an account key from hidden terminal input or stdin. Never pass a key as an argument.', run: async (_, c) => {
39
- const key = await (c.context.readCredential ?? readCredentialInput)();
40
- if (!validCredential(key))
41
- throw new CliError('invalid_credentials', 'Supply a valid account key.', 3);
42
- const account = await c.request('/api/studio/account', 'GET', undefined, key);
43
- const file = await storeCredential(c.env, key);
44
- return { account: account.account, stored_in: file };
45
- } },
46
- { path: 'logout', summary: 'Remove the saved account key; a key in the environment remains set.', run: async (_, c) => {
47
- await removeCredential(c.env);
48
- const active = environmentCredentialNames(c.env);
49
- return { logged_out: true, ...(active.length ? { notice: `${active.join(' and ')} ${active.length > 1 ? 'remain' : 'remains'} set in your environment.` } : {}) };
50
- } },
51
- { path: 'auth whoami', summary: 'Show your account and credential source with a prefix only.', run: async (_, c) => {
52
- const credential = await c.credential();
53
- return { ...await c.request('/api/studio/account', 'GET', undefined, credential.key), credential: { source: credential.source, prefix: credential.key.slice(0, 11) } };
54
- } },
55
- { path: 'projects list', summary: 'List your projects.', run: (_, c) => c.request('/api/studio/projects') },
56
- { path: 'projects create', summary: 'Create a project with a $10 monthly budget and app access enabled.', flags: ['name'], run: (a, c) => c.request('/api/studio/projects', 'POST', { ...projectBody(a), name: required(a, 'name') }) },
57
- { path: 'projects get', summary: 'Inspect a project.', positionals: ['project-id'], run: (a, c) => c.request(project(a)) },
58
- { path: 'projects update', summary: 'Rename a project or update routing from a JSON runtime policy file.', positionals: ['project-id'], flags: ['name', 'policy-file'], run: async (a, c) => { const body = projectBody(a); if (a['policy-file']) {
59
- try {
60
- const policy = JSON.parse(await c.readFile(a['policy-file'], 'The runtime policy file'));
61
- if (!policy || typeof policy !== 'object' || Array.isArray(policy) || Object.keys(policy).length !== 1 || !Object.hasOwn(policy, 'routing'))
62
- throw new CliError('invalid_policy', 'The runtime policy file may contain only routing. Change budgets, allowances and security settings in web Studio.');
63
- body.runtime_policy = policy;
64
- }
65
- catch (error) {
66
- if (error instanceof CliError)
67
- throw error;
68
- throw new CliError('invalid_file', 'Runtime policy file must contain a readable JSON object.');
69
- }
70
- } if (!Object.keys(body).length)
71
- throw new CliError('missing_argument', 'Supply at least one project setting.'); return c.request(project(a), 'PATCH', body); } },
72
- { path: 'projects operations', summary: 'List recent operations (server limit 500).', positionals: ['project-id'], flags: ['limit', 'status', 'type', 'query'], run: (a, c) => { const query = new URLSearchParams(); for (const flag of ['limit', 'status', 'type', 'query'])
73
- if (a[flag] !== undefined)
74
- query.set(flag === 'query' ? 'q' : flag, flag === 'limit' ? String(integer(a[flag], flag, 1, 500)) : a[flag]); return c.request(`${project(a)}/operations?${query}`); } },
75
- { path: 'projects cost', summary: 'Show all-time known cost and explicitly unresolved operations.', positionals: ['project-id'], run: (a, c) => c.request(`${project(a)}/cost`) },
76
- // Key metadata is readable with an account key; issuance and revocation belong to web Studio.
77
- ...[['development', 'debug-tokens', 'debug key (cdt_) for simulators and your own devices'], ['server', 'server-keys', 'server key (csk_) for a web app\'s own backend']].flatMap(([kind, route]) => [
78
- { path: `keys ${kind} list`, summary: `List a project's ${kind === 'development' ? 'debug' : kind} keys with installations, last use${kind === 'server' ? ' and Runtime Credit spent' : ' and misuse warnings'}.`, positionals: ['project-id'], run: (a, c) => c.request(`${project(a)}/${route}`) },
79
- ]),
80
- { path: 'projects usage', summary: 'Usage per end user and per agent, project budget left and the weekly development allowance left.', positionals: ['project-id'], flags: ['period'], run: (a, c) => { const period = a.period ?? 'month'; if (!['week', 'month', 'all'].includes(period))
81
- throw new CliError('invalid_argument', 'period must be week, month or all.'); return c.request(`${project(a)}/usage?period=${period}`); } },
82
- { path: 'attestation get', summary: 'Show the App Attest and Play Integrity settings (the decryption key is never returned).', positionals: ['project-id'], run: (a, c) => c.request(`${project(a)}/attestation`) },
83
- { path: 'runtimes list', summary: 'List Cloud Runtime enrollments for a project.', flags: ['project-id'], run: (a, c) => c.request(`${project(a)}/runtimes`) },
84
- { path: 'control serve', summary: 'Start an opt-in loopback broker. Requires CROCHE_CONTROL_TOKEN.', flags: ['port', 'allow-origin'], run: async (a, c) => { if (!c.context.serveControl)
85
- throw new CliError('unavailable', 'Control server is unavailable in this embedding.', 1); const token = c.env.CROCHE_CONTROL_TOKEN; if (!token)
86
- throw new CliError('missing_configuration', 'Set CROCHE_CONTROL_TOKEN before starting control.'); return c.context.serveControl({ token, port: integer(a.port ?? '8791', 'port', 1, 65535), origins: a['allow-origin'] ? a['allow-origin'].split(',') : [] }); } },
87
- { path: 'runtime list', summary: 'List Runtimes explicitly attached to the local control broker.', flags: ['control-url'], run: (a, c) => requestControl('list', a, c.env, c.context.fetch) },
88
- { path: 'runtime result', summary: 'Inspect a prior control request without resubmitting it.', flags: ['request-id', 'control-url'], run: (a, c) => requestControl('result', { ...a, 'request-id': required(a, 'request-id') }, c.env, c.context.fetch) },
89
- ...localCommands.map(action => ({ path: `runtime ${action}`, summary: `Run local Runtime ${action}; requires its advertised capability.`, flags: ['runtime-id', 'control-url', 'request-id', 'wait-ms', ...(action === 'send' ? ['id', 'text', 'text-file'] : []), ...(action === 'history' ? ['offset', 'limit'] : []), ...(action === 'budget set' ? ['amount'] : [])], run: async (a, c) => {
90
- required(a, 'runtime-id');
91
- if (action === 'send') {
92
- required(a, 'id');
93
- if (Boolean(a.text) === Boolean(a['text-file']))
94
- throw new CliError('invalid_argument', 'Supply exactly one of --text or --text-file.');
95
- if (a['text-file']) {
96
- try {
97
- a = { ...a, text: await c.readFile(a['text-file'], 'The text file') };
98
- }
99
- catch (error) {
100
- if (error instanceof CliError)
101
- throw error;
102
- throw new CliError('invalid_file', 'The text file could not be read.');
103
- }
104
- }
105
- }
106
- return requestControl(action.replace(' ', '.'), a, c.env, c.context.fetch);
107
- } })),
108
- ];
109
- export function help(prefix = '') {
110
- if (!prefix)
111
- return overview();
112
- const visible = commands.filter(command => command.path === prefix || command.path.startsWith(prefix + ' '));
113
- if (!visible.length)
114
- throw new CliError('unknown_command', 'Unknown command. Run croche --help.');
115
- const exact = visible.find(command => command.path === prefix);
116
- if (visible.length === 1 && exact)
117
- return commandHelp(exact);
118
- // `croche debug` is a command and a group: its own usage follows the group's list.
119
- return groupHelp(prefix, visible) + (exact ? '\n' + commandHelp(exact) : '');
120
- }
121
- // Global flags are recognized only outside option values. Literal message text
122
- // such as --help or --json must reach the Runtime unchanged.
123
- function globalOptions(argv) {
124
- const words = [];
125
- let json = false, asking = false, version = false;
126
- for (let index = 0; index < argv.length; index++) {
127
- const token = argv[index];
128
- if (token === '--json') {
129
- json = true;
130
- continue;
131
- }
132
- if (token === '--version' && !(argv[0] === 'config' && argv[1] === 'get' && index > 1)) {
133
- version = true;
134
- continue;
135
- }
136
- if (token === '--help' || token === '-h') {
137
- asking = true;
138
- continue;
139
- }
140
- words.push(token);
141
- if (token.startsWith('--') && !token.includes('=') && !commands.some(c => c.switches?.includes(token.slice(2))) && index + 1 < argv.length)
142
- words.push(argv[++index]);
143
- }
144
- return { words, json, asking, version };
145
- }
146
- // Read only when asked, from the package this file ships in (src/ in the repo, dist/ installed).
147
- function cliVersion() {
148
- try {
149
- return String(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
150
- }
151
- catch {
152
- throw new CliError('unavailable', 'The CLI version could not be read.', 1);
153
- }
154
- }
155
- function parse(argv) {
156
- const { words, json, asking, version } = globalOptions(argv);
157
- if (version && !asking)
158
- return { args: {}, json, version: cliVersion() };
159
- if (!words.length || asking) {
160
- const prefix = words.slice(0, words.findIndex(word => word.startsWith('--')) < 0 ? undefined : words.findIndex(word => word.startsWith('--'))).join(' ');
161
- const exact = commands.find(c => prefix === c.path || prefix.startsWith(c.path + ' '));
162
- return { args: {}, json, help: help(exact?.path ?? prefix) };
163
- }
164
- const command = [...commands].sort((a, b) => b.path.length - a.path.length).find(c => c.path.split(' ').every((word, index) => words[index] === word));
165
- if (!command)
166
- throw new CliError('unknown_command', 'Unknown command. Run croche --help.');
167
- const rest = words.slice(command.path.split(' ').length), args = {}, positional = [...(command.positionals ?? [])];
168
- for (let index = 0; index < rest.length; index++) {
169
- const token = rest[index] === '-o' && command.path === 'config get' ? '--output' : rest[index];
170
- if (!token.startsWith('--')) {
171
- const key = positional.shift();
172
- if (!key)
173
- throw new CliError('unexpected_argument', 'Unexpected positional argument.');
174
- if (args[key] !== undefined)
175
- throw new CliError('duplicate_argument', `Duplicate ${key}.`);
176
- args[key] = token;
177
- continue;
178
- }
179
- const equals = token.indexOf('='), key = token.slice(2, equals < 0 ? undefined : equals);
180
- if (command.switches?.includes(key) && equals < 0) {
181
- if (args[key] !== undefined)
182
- throw new CliError('duplicate_argument', `Duplicate --${key}.`);
183
- args[key] = 'true';
184
- continue;
185
- }
186
- if (![...(command.flags ?? []), ...(command.switches ?? []), ...(command.positionals ?? [])].includes(key))
187
- throw new CliError('unknown_option', `Unknown option --${key}. Credentials must be supplied through the documented environment variables.`);
188
- if (args[key] !== undefined)
189
- throw new CliError('duplicate_argument', `Duplicate --${key}.`);
190
- const value = equals < 0 ? rest[++index] : token.slice(equals + 1);
191
- if (value === undefined)
192
- throw new CliError('missing_argument', `Supply a value for --${key}.`);
193
- args[key] = value;
194
- }
195
- for (const key of command.positionals ?? [])
196
- required(args, key);
197
- return { command, args, json };
198
- }
199
- function cloudUrl(value) {
200
- if (value === undefined)
201
- return DEFAULT_CLOUD_URL;
202
- let url;
203
- try {
204
- url = new URL(value);
205
- }
206
- catch {
207
- throw new CliError('invalid_configuration', 'CROCHE_CLOUD_URL must be an absolute HTTPS origin.');
208
- }
209
- if (url.username || url.password || url.search || url.hash || url.pathname !== '/' || !(url.protocol === 'https:' || (url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))))
210
- throw new CliError('invalid_configuration', 'CROCHE_CLOUD_URL must be HTTPS, or HTTP on loopback, without credentials, query, fragment, or path.');
211
- return url.origin;
212
- }
213
- export async function runCli(argv, context = {}) {
214
- const env = context.env ?? process.env, stdout = context.stdout ?? (text => process.stdout.write(text)), stderr = context.stderr ?? (text => process.stderr.write(text));
215
- const jsonMode = globalOptions(argv).json;
216
- const secrets = new Set([env.CROCHE_ACCOUNT_KEY, env.CROCHE_DEVELOPER_KEY, env.CROCHE_CONTROL_TOKEN].filter((value) => Boolean(value)));
217
- try {
218
- const parsed = parse(argv);
219
- if (parsed.help) {
220
- stdout(parsed.json ? JSON.stringify({ ok: true, data: { help: parsed.help } }) + '\n' : parsed.help);
221
- return 0;
222
- }
223
- if (parsed.version) {
224
- stdout(parsed.json ? JSON.stringify({ ok: true, data: { version: parsed.version } }) + '\n' : `croche ${parsed.version}\n`);
225
- return 0;
226
- }
227
- const clientEnv = { ...env, ...(parsed.command?.path.startsWith('config ') && parsed.args['cloud-url'] !== undefined ? { CROCHE_CLOUD_URL: parsed.args['cloud-url'] } : {}) };
228
- // Same identity for implicit production and explicit production; local commands still
229
- // need no Cloud validation or credentials. Explicit invalid values remain for refusal.
230
- if (clientEnv.CROCHE_CLOUD_URL === undefined)
231
- clientEnv.CROCHE_CLOUD_URL = DEFAULT_CLOUD_URL;
232
- const client = { env: clientEnv, credential: () => resolveCredential(clientEnv), context: parsed.json ? { ...context, selectRuntime: undefined } : context, readFile: async (path, what) => decodeTextFile(context.readFile ? await context.readFile(path) : await readLocalFile(path), what), request: async (path, method = 'GET', body, override) => {
233
- const credential = override ?? (await resolveCredential(clientEnv)).key;
234
- secrets.add(credential);
235
- const origin = cloudUrl(clientEnv.CROCHE_CLOUD_URL);
236
- const headers = { Authorization: `Bearer ${credential}` };
237
- if (body !== undefined)
238
- headers['Content-Type'] = 'application/json';
239
- let response;
240
- try {
241
- response = await (context.fetch ?? fetch)(origin + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(30000) });
242
- }
243
- catch {
244
- throw new CliError('transport_error', 'Cloud request failed or timed out; no automatic retry was made.', 4);
245
- }
246
- const data = await readResponse(response);
247
- if (!response.ok)
248
- throw new CliError(String(data?.error?.code ?? 'remote_error'), String(data?.error?.message ?? 'Cloud rejected the request.') + (data?.error?.code === 'draft_conflict' ? ` Current head: ${data.error.details?.head ?? 'null'}.` : ''), [401, 403].includes(response.status) ? 3 : 1, data?.error?.details);
249
- return data;
250
- } };
251
- const result = await parsed.command.run(parsed.args, client);
252
- if (!parsed.json && parsed.command.path.startsWith('debug')) {
253
- const debugResult = result;
254
- if (debugResult.pairedUrl)
255
- stdout(`${debugResult.pairedUrl}${debugResult.studioUrl ? `\n${debugResult.studioUrl}` : ''}\n\n${debugResult.instruction}\n`);
256
- else if (debugResult.studioUrl && !debugResult.status)
257
- stdout(`${debugResult.studioUrl}\n\n${debugResult.instruction}\n`);
258
- else if (debugResult.pairingToken)
259
- stdout(`${debugResult.pairingToken}\n`);
260
- else
261
- stdout(JSON.stringify(result, null, 2) + '\n');
262
- return 0;
263
- }
264
- stdout(JSON.stringify(parsed.json ? { ok: true, data: result } : result, null, parsed.json ? undefined : 2) + '\n');
265
- return 0;
266
- }
267
- catch (error) {
268
- const issue = error instanceof CliError ? error : new CliError('internal_error', 'The command could not be completed.', 1);
269
- let message = issue.message;
270
- for (const secret of secrets)
271
- if (secret)
272
- message = message.replaceAll(secret, '[redacted]');
273
- const output = { ok: false, error: { code: issue.code, message, ...(issue.details ? { details: issue.details } : {}) } };
274
- let rendered = jsonMode ? JSON.stringify(output) + '\n' : `${issue.code}: ${message}\n`;
275
- for (const secret of secrets)
276
- if (secret)
277
- rendered = rendered.replaceAll(secret, '[redacted]');
278
- if (jsonMode)
279
- stdout(rendered);
280
- else
281
- stderr(rendered);
282
- return issue.exitCode;
283
- }
284
- }
285
- export async function readResponse(response, limit = 1024 * 1024) {
286
- const reader = response.body?.getReader();
287
- if (!reader)
288
- throw new CliError('invalid_response', 'The server returned an empty response.', 4);
289
- const chunks = [];
290
- let length = 0;
291
- try {
292
- while (true) {
293
- const part = await reader.read();
294
- if (part.done)
295
- break;
296
- length += part.value.byteLength;
297
- if (length > limit)
298
- throw new CliError('response_too_large', 'The response exceeded its size limit; request a smaller page.', 4);
299
- chunks.push(part.value);
300
- }
301
- }
302
- catch (error) {
303
- void reader.cancel().catch(() => { });
304
- throw error instanceof CliError ? error : new CliError('transport_error', 'The response body could not be read.', 4);
305
- }
306
- finally {
307
- reader.releaseLock();
308
- }
309
- const bytes = new Uint8Array(length);
310
- let offset = 0;
311
- for (const chunk of chunks) {
312
- bytes.set(chunk, offset);
313
- offset += chunk.byteLength;
314
- }
315
- try {
316
- return JSON.parse(new TextDecoder().decode(bytes));
317
- }
318
- catch {
319
- throw new CliError('invalid_response', 'The server returned invalid JSON.', 4);
320
- }
321
- }
1
+ import {
2
+ CliError,
3
+ commands,
4
+ help,
5
+ readResponse,
6
+ runCli,
7
+ studioUrl
8
+ } from "./chunk-K3UDT4EM.js";
9
+ import "./chunk-66EUX7EL.js";
10
+ export {
11
+ CliError,
12
+ commands,
13
+ help,
14
+ readResponse,
15
+ runCli,
16
+ studioUrl
17
+ };
@@ -0,0 +1,2 @@
1
+ export declare const resultNouns: Readonly<Record<string, string>>;
2
+ export declare function jsonResult(path: string, result: unknown): unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@h1r-ai/croche-cli",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -36,6 +36,7 @@
36
36
  "prepack": "npm run build"
37
37
  },
38
38
  "devDependencies": {
39
+ "esbuild": "0.25.12",
39
40
  "@types/node": "^24.0.0",
40
41
  "typescript": "^5.9.0",
41
42
  "vitest": "^4.1.11"
package/dist/config.js DELETED
@@ -1,100 +0,0 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
- import { dirname, isAbsolute, join } from 'node:path';
4
- import { defaultConnectionFile } from './debugger.js';
5
- import { CliError } from './index.js';
6
- const identity = /^sha256:[a-f0-9]{64}$/;
7
- function revision(value) { if (!identity.test(value))
8
- throw new CliError('invalid_argument', 'Revision must be sha256:<64 lowercase hex characters>.'); return value; }
9
- function version(value) { if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)))
10
- throw new CliError('invalid_argument', 'Version must be a positive integer.'); return Number(value); }
11
- function stateFile(c, project) {
12
- const dir = c.env.CROCHE_CLI_STATE_DIR ?? join(dirname(defaultConnectionFile('debugger', c.env)), '..', 'config');
13
- if (!isAbsolute(dir))
14
- throw new CliError('invalid_configuration', 'CROCHE_CLI_STATE_DIR must be absolute.');
15
- return join(dir, createHash('sha256').update(`${c.env.CROCHE_CLOUD_URL}|${project}`).digest('hex') + '.json');
16
- }
17
- async function readBase(c, project) {
18
- try {
19
- const data = JSON.parse(await readFile(stateFile(c, project), 'utf8'));
20
- if (data.revision_id === null)
21
- return null;
22
- return revision(data.revision_id);
23
- }
24
- catch (error) {
25
- if (error.code === 'ENOENT')
26
- return null;
27
- throw new CliError('invalid_state', 'Saved config base cannot be read; use --base with an explicit revision.');
28
- }
29
- }
30
- async function remember(c, project, id) {
31
- const file = stateFile(c, project), temp = file + '.' + randomUUID() + '.tmp';
32
- await mkdir(dirname(file), { recursive: true, mode: 0o700 });
33
- await writeFile(temp, JSON.stringify({ revision_id: id }), { mode: 0o600 });
34
- await rename(temp, file);
35
- }
36
- export async function configCommand(action, args, c) {
37
- const project = args.project ?? c.env.CROCHE_PROJECT;
38
- if (!project || !/^[A-Za-z0-9_.:-]{1,200}$/.test(project))
39
- throw new CliError('missing_argument', 'Supply --project or CROCHE_PROJECT.');
40
- const path = `/api/studio/projects/${encodeURIComponent(project)}/config`;
41
- if (action === 'get') {
42
- if (args.revision && args.version)
43
- throw new CliError('invalid_argument', 'Choose --revision or --version.');
44
- let id = null, document = null, exportVersion;
45
- if (args.version) {
46
- exportVersion = version(args.version);
47
- const listed = await c.request(path + '/versions');
48
- const v = listed.versions.find((v) => v.version === exportVersion);
49
- if (!v)
50
- throw new CliError('not_found', 'Config version not found.', 1);
51
- id = v.revision_id;
52
- document = (await c.request(path + '/revisions/' + encodeURIComponent(id))).revision.document;
53
- }
54
- else if (args.revision) {
55
- id = revision(args.revision);
56
- document = (await c.request(path + '/revisions/' + encodeURIComponent(id))).revision.document;
57
- }
58
- else {
59
- const { draft } = await c.request(path + '/draft');
60
- id = draft?.revision_id ?? null;
61
- document = draft?.document ?? null;
62
- await remember(c, project, id);
63
- }
64
- if (id)
65
- c.stderr(id + '\n');
66
- const result = exportVersion === undefined ? document : { version: exportVersion, revision: id, config: document.config };
67
- if (args.output) {
68
- const text = JSON.stringify(result, null, 2) + '\n';
69
- if (c.writeFile)
70
- await c.writeFile(args.output, text);
71
- else
72
- await writeFile(args.output, text, 'utf8');
73
- return { file: args.output, revision_id: id, ...(exportVersion === undefined ? {} : { version: exportVersion }) };
74
- }
75
- return result;
76
- }
77
- if (action === 'save') {
78
- let document;
79
- try {
80
- document = JSON.parse(await c.readFile(args.file, 'The config file'));
81
- }
82
- catch (e) {
83
- if (e instanceof CliError)
84
- throw e;
85
- throw new CliError('invalid_file', 'Config file must contain JSON.');
86
- }
87
- // Version exports round-trip as a project document; release metadata is never hashed.
88
- if (document && typeof document === 'object' && 'version' in document && 'revision' in document && 'config' in document)
89
- document = { schema: 2, config: document.config };
90
- const base = args.base === undefined ? await readBase(c, project) : args.base === 'null' ? null : revision(args.base);
91
- const result = await c.request(path + '/draft', 'PUT', { document, base_revision_id: base, ...(args.note ? { note: args.note } : {}) });
92
- await remember(c, project, result.revision_id);
93
- return result;
94
- }
95
- if (action === 'list') {
96
- const [{ versions }, { draft }] = await Promise.all([c.request(path + '/versions'), c.request(path + '/draft')]);
97
- return { versions, draft };
98
- }
99
- throw new CliError('unknown_command', 'Unknown config command.');
100
- }
@@ -1,65 +0,0 @@
1
- import { CliError, readResponse } from './index.js';
2
- function endpoint(value) { let url; try {
3
- url = new URL(value);
4
- }
5
- catch {
6
- throw new CliError('invalid_configuration', 'Control URL must be a loopback HTTP origin.');
7
- } if (url.protocol !== 'http:' || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== '/')
8
- throw new CliError('invalid_configuration', 'Control URL must be a loopback HTTP origin without credentials or a path.'); return url.origin; }
9
- function integer(value, fallback, min, max) { if (value === undefined)
10
- return fallback; if (!/^\d+$/.test(value) || Number(value) < min || Number(value) > max)
11
- throw new CliError('invalid_argument', `Expected an integer between ${min} and ${max}.`); return Number(value); }
12
- export async function requestControl(command, args, env, transport = fetch, commandPayload) {
13
- const origin = endpoint(args['control-url'] ?? env.CROCHE_CONTROL_URL ?? 'http://127.0.0.1:8791'), token = env.CROCHE_CONTROL_TOKEN;
14
- if (!token || !/^[A-Za-z0-9._~-]{24,4096}$/.test(token))
15
- throw new CliError('missing_credentials', 'Set CROCHE_CONTROL_TOKEN to the local broker credential.', 3);
16
- const request = async (path, method = 'GET', body) => {
17
- let result;
18
- try {
19
- result = await transport(origin + '/v1/control' + path, { method, headers: { Authorization: `Bearer ${token}`, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) }, body: body === undefined ? undefined : JSON.stringify(body), credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(10000) });
20
- }
21
- catch {
22
- throw new CliError('transport_error', 'Local control request failed; it was not resubmitted.', 4);
23
- }
24
- const data = await readResponse(result);
25
- if (!result.ok)
26
- throw new CliError(data?.error?.code ?? 'control_error', data?.error?.message ?? 'Local control rejected the request.', [401, 403].includes(result.status) ? 3 : 1);
27
- return data;
28
- };
29
- if (command === 'list')
30
- return request('/runtimes');
31
- if (command === 'result') {
32
- if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(args['request-id'] ?? ''))
33
- throw new CliError('invalid_argument', 'Supply a valid --request-id.');
34
- return request(`/requests/${encodeURIComponent(args['request-id'])}`);
35
- }
36
- if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(args['runtime-id'] ?? ''))
37
- throw new CliError('invalid_argument', 'Supply a valid --runtime-id.');
38
- const requestId = args['request-id'] ?? crypto.randomUUID();
39
- if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(requestId))
40
- throw new CliError('invalid_argument', 'Invalid --request-id.');
41
- let payload = commandPayload ?? {};
42
- if (command === 'send') {
43
- if (!/^[A-Za-z0-9_.:-]{1,200}$/.test(args.id ?? '') || !args.text?.trim() || args.text.length > 32000)
44
- throw new CliError('invalid_argument', 'send requires a stable --id and 1–32,000 characters of text.');
45
- payload = { id: args.id, text: args.text };
46
- }
47
- if (command === 'history')
48
- payload = { offset: integer(args.offset, 0, 0, 1000000), limit: integer(args.limit, 100, 1, 200) };
49
- if (command === 'budget.set') {
50
- if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(args.amount ?? '') || !Number.isFinite(Number(args.amount)))
51
- throw new CliError('invalid_argument', 'budget set requires a finite non-negative --amount in USD.');
52
- payload = { amount: Number(args.amount) };
53
- }
54
- const wait = integer(args['wait-ms'], command === 'send' ? 120000 : 15000, 0, 600000), deadline = Date.now() + wait;
55
- let response = await request(`/runtimes/${encodeURIComponent(args['runtime-id'])}/${command.replace('.', '-')}`, 'POST', { request_id: requestId, payload });
56
- while (['queued', 'dispatched'].includes(response.request.status) && Date.now() < deadline) {
57
- await new Promise(resolve => setTimeout(resolve, 200));
58
- response = await request(`/requests/${encodeURIComponent(requestId)}`);
59
- }
60
- if (response.request.status === 'failed')
61
- throw new CliError(response.request.error.code, response.request.error.message, 1, { request_id: requestId, uncertain: response.request.error.uncertain === true });
62
- if (response.request.status !== 'completed')
63
- throw new CliError('control_pending', 'The command is still pending. Inspect its request ID; do not create a replacement automatically.', 4, { request_id: requestId, status: response.request.status });
64
- return response;
65
- }
@@ -1,2 +0,0 @@
1
- // Generated from the Rust Core by scripts/build-core.ts. Do not edit.
2
- export const DEFAULT_CLOUD_URL = "https://api.croche.ai";