@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.
- package/LICENSE +32 -0
- package/README.md +468 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +26 -0
- package/dist/config.d.ts +10 -0
- package/dist/config.js +100 -0
- package/dist/control-client.d.ts +1 -0
- package/dist/control-client.js +65 -0
- package/dist/control-server.d.ts +29 -0
- package/dist/control-server.js +288 -0
- package/dist/core-defaults.d.ts +1 -0
- package/dist/core-defaults.js +2 -0
- package/dist/credentials.d.ts +17 -0
- package/dist/credentials.js +136 -0
- package/dist/debug-keys.d.ts +19 -0
- package/dist/debug-keys.js +141 -0
- package/dist/debugger/public/app.js +271 -0
- package/dist/debugger/public/index.html +71 -0
- package/dist/debugger/public/styles.css +4 -0
- package/dist/debugger/server/collector.js +460 -0
- package/dist/debugger/server/observe.js +286 -0
- package/dist/debugger/server/server.js +89 -0
- package/dist/debugger/server/turns.js +94 -0
- package/dist/debugger.d.ts +21 -0
- package/dist/debugger.js +468 -0
- package/dist/help.d.ts +24 -0
- package/dist/help.js +158 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +321 -0
- package/dist/text-file.d.ts +7 -0
- package/dist/text-file.js +15 -0
- package/package.json +41 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type DebuggerContext } from './debugger.js';
|
|
2
|
+
export declare class CliError extends Error {
|
|
3
|
+
readonly code: string;
|
|
4
|
+
readonly exitCode: number;
|
|
5
|
+
readonly details?: unknown | undefined;
|
|
6
|
+
constructor(code: string, message: string, exitCode?: number, details?: unknown | undefined);
|
|
7
|
+
}
|
|
8
|
+
export interface CliContext {
|
|
9
|
+
env?: Record<string, string | undefined>;
|
|
10
|
+
fetch?: typeof fetch;
|
|
11
|
+
stdout?: (value: string) => void;
|
|
12
|
+
stderr?: (value: string) => void;
|
|
13
|
+
readFile?: (path: string) => Promise<string>;
|
|
14
|
+
readCredential?: () => Promise<string>;
|
|
15
|
+
writeFile?: (path: string, text: string) => Promise<void>;
|
|
16
|
+
serveControl?: (options: {
|
|
17
|
+
token: string;
|
|
18
|
+
port: number;
|
|
19
|
+
origins: string[];
|
|
20
|
+
}) => Promise<unknown>;
|
|
21
|
+
selectRuntime?: DebuggerContext['selectRuntime'];
|
|
22
|
+
launchDebuggerService?: DebuggerContext['launch'];
|
|
23
|
+
}
|
|
24
|
+
type Args = Record<string, string>;
|
|
25
|
+
type Command = {
|
|
26
|
+
path: string;
|
|
27
|
+
summary: string;
|
|
28
|
+
positionals?: string[];
|
|
29
|
+
flags?: string[]; /** Flags given bare, as `true`. */
|
|
30
|
+
switches?: string[];
|
|
31
|
+
run: (args: Args, client: Client) => Promise<unknown>;
|
|
32
|
+
};
|
|
33
|
+
type Client = {
|
|
34
|
+
request: (path: string, method?: string, body?: unknown, credential?: string) => Promise<any>;
|
|
35
|
+
credential: () => Promise<{
|
|
36
|
+
key: string;
|
|
37
|
+
source: 'env' | 'stored';
|
|
38
|
+
}>;
|
|
39
|
+
readFile: (path: string, what: string) => Promise<string>;
|
|
40
|
+
context: CliContext;
|
|
41
|
+
env: Record<string, string | undefined>;
|
|
42
|
+
};
|
|
43
|
+
/** Declarative command tree: future Studio features add one descriptor. */
|
|
44
|
+
export declare const commands: readonly Command[];
|
|
45
|
+
export declare function help(prefix?: string): string;
|
|
46
|
+
export declare function runCli(argv: string[], context?: CliContext): Promise<number>;
|
|
47
|
+
export declare function readResponse(response: Response, limit?: number): Promise<any>;
|
|
48
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text from a file the person wrote: UTF-8, with or without a leading byte order mark.
|
|
3
|
+
* Windows PowerShell 5.1 writes a BOM with `-Encoding UTF8` and UTF-16 with `>` or `Out-File`.
|
|
4
|
+
* The BOM is dropped. UTF-16 is refused with the fix, rather than surfacing as invalid JSON.
|
|
5
|
+
* A string comes from an embedding's own reader (`CliContext.readFile`) and is already decoded.
|
|
6
|
+
*/
|
|
7
|
+
export declare function decodeTextFile(content: Uint8Array | string, what: string): string;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { CliError } from './index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Text from a file the person wrote: UTF-8, with or without a leading byte order mark.
|
|
4
|
+
* Windows PowerShell 5.1 writes a BOM with `-Encoding UTF8` and UTF-16 with `>` or `Out-File`.
|
|
5
|
+
* The BOM is dropped. UTF-16 is refused with the fix, rather than surfacing as invalid JSON.
|
|
6
|
+
* A string comes from an embedding's own reader (`CliContext.readFile`) and is already decoded.
|
|
7
|
+
*/
|
|
8
|
+
export function decodeTextFile(content, what) {
|
|
9
|
+
if (typeof content !== 'string') {
|
|
10
|
+
if (content.length >= 2 && ((content[0] === 0xff && content[1] === 0xfe) || (content[0] === 0xfe && content[1] === 0xff)))
|
|
11
|
+
throw new CliError('unsupported_encoding', `${what} is UTF-16 (${content[0] === 0xff ? 'little' : 'big'}-endian); save it as UTF-8. In Windows PowerShell 5.1 use [IO.File]::WriteAllText(path, text); in pwsh 7, Set-Content writes UTF-8.`);
|
|
12
|
+
content = Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString('utf8');
|
|
13
|
+
}
|
|
14
|
+
return content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
|
|
15
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@h1r-ai/croche-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
}
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
8
|
+
"description": "Croche account, project, and opt-in local Runtime controls.",
|
|
9
|
+
"type": "module",
|
|
10
|
+
"bin": {
|
|
11
|
+
"croche": "./dist/bin.js"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./control": {
|
|
19
|
+
"types": "./dist/control-server.d.ts",
|
|
20
|
+
"import": "./dist/control-server.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"THIRD-PARTY-NOTICES"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=22"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "node scripts/build.mjs",
|
|
34
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
35
|
+
"test": "vitest run --root ../.. packages/cli/tests",
|
|
36
|
+
"prepack": "npm run build"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/node": "^24.0.0",
|
|
40
|
+
"typescript": "^5.9.0",
|
|
41
|
+
"vitest": "^4.1.11"
|
|
42
|
+
}
|
|
43
|
+
}
|