@h1r-ai/croche-cli 0.0.0-stage → 0.5.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.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from './index.js';
3
+ import { startControlServer } from './control-server.js';
4
+ import { createInterface } from 'node:readline/promises';
5
+ process.exitCode = await runCli(process.argv.slice(2), { ...(process.stdin.isTTY && process.stdout.isTTY ? { selectRuntime: async (runtimes) => {
6
+ process.stdout.write('Available local Runtimes\n' + runtimes.map((runtime, index) => ` ${index + 1}. ${runtime.label} (${runtime.id})`).join('\n') + '\n');
7
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
8
+ try {
9
+ const choice = (await reader.question('Choose a number, or press Enter to cancel: ')).trim();
10
+ if (!choice)
11
+ return;
12
+ const index = Number(choice) - 1;
13
+ if (!/^\d+$/.test(choice) || !runtimes[index])
14
+ throw new Error('Invalid selection.');
15
+ return runtimes[index].id;
16
+ }
17
+ finally {
18
+ reader.close();
19
+ }
20
+ } } : {}), serveControl: async (options) => {
21
+ const server = await startControlServer(options);
22
+ const close = () => void server.close();
23
+ process.once('SIGINT', close);
24
+ process.once('SIGTERM', close);
25
+ return { url: server.url, local: true, authentication: 'CROCHE_CONTROL_TOKEN', storage: 'in-memory; Runtime owns durable input receipts' };
26
+ } });
@@ -0,0 +1,10 @@
1
+ type Args = Record<string, string>;
2
+ type Context = {
3
+ env: Record<string, string | undefined>;
4
+ request: (path: string, method?: string, body?: unknown) => Promise<any>;
5
+ readFile: (path: string, what: string) => Promise<string>;
6
+ writeFile?: (path: string, text: string) => Promise<void>;
7
+ stderr: (text: string) => void;
8
+ };
9
+ export declare function configCommand(action: string, args: Args, c: Context): Promise<unknown>;
10
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,100 @@
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
+ }
@@ -0,0 +1 @@
1
+ export declare function requestControl(command: string, args: Record<string, string>, env: Record<string, string | undefined>, transport?: typeof fetch, commandPayload?: Record<string, unknown>): Promise<any>;
@@ -0,0 +1,65 @@
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
+ }
@@ -0,0 +1,29 @@
1
+ export interface ControlServerOptions {
2
+ token: string;
3
+ port?: number;
4
+ origins?: string[];
5
+ now?: () => number;
6
+ heartbeatTimeoutMs?: number;
7
+ }
8
+ /** Authenticated in-memory delivery broker. It never opens a Runtime store. */
9
+ export declare class ControlBroker {
10
+ private options;
11
+ private runtimes;
12
+ private requests;
13
+ private origins;
14
+ private now;
15
+ constructor(options: ControlServerOptions);
16
+ private timestamp;
17
+ private usedBytes;
18
+ private publicRequest;
19
+ private expire;
20
+ private detach;
21
+ private body;
22
+ handle(request: Request): Promise<Response>;
23
+ private dispatch;
24
+ }
25
+ export declare function startControlServer(options: ControlServerOptions): Promise<{
26
+ url: string;
27
+ broker: ControlBroker;
28
+ close: () => Promise<void>;
29
+ }>;
@@ -0,0 +1,288 @@
1
+ import { createServer } from 'node:http';
2
+ import { timingSafeEqual } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { Readable } from 'node:stream';
5
+ const PREFIX = '/v1/control';
6
+ const COMMANDS = new Map([['status', 'status'], ['history', 'history'], ['send', 'send'], ['cancel', 'cancel'], ['sync', 'sync'], ['budget-get', 'budget.get'], ['budget-set', 'budget.set'], ['tools', 'tools'], ['debug-attach', 'debug.attach'], ['debug-detach', 'debug.detach']]);
7
+ const MAX_BODY = 1024 * 1024, MAX_MEMORY = 8 * 1024 * 1024, MAX_RUNTIMES = 100, MAX_REQUESTS = 1000;
8
+ class ControlError extends Error {
9
+ status;
10
+ code;
11
+ constructor(status, code, message) {
12
+ super(message);
13
+ this.status = status;
14
+ this.code = code;
15
+ }
16
+ }
17
+ function failure(status, code, message) { throw new ControlError(status, code, message); }
18
+ const response = (body, status = 200) => Response.json(body, { status, headers: { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } });
19
+ const identifier = (value) => typeof value === 'string' && /^[A-Za-z0-9_.:-]{1,200}$/.test(value);
20
+ function record(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
21
+ return failure(400, 'invalid_request', 'Expected a JSON object.'); return value; }
22
+ function authEqual(actual, expected) { const a = Buffer.from(actual), b = Buffer.from(expected); return a.length === b.length && timingSafeEqual(a, b); }
23
+ /** Authenticated in-memory delivery broker. It never opens a Runtime store. */
24
+ export class ControlBroker {
25
+ options;
26
+ runtimes = new Map();
27
+ requests = new Map();
28
+ origins;
29
+ now;
30
+ constructor(options) {
31
+ this.options = options;
32
+ if (!/^[A-Za-z0-9._~-]{24,4096}$/.test(options.token))
33
+ throw new Error('Control token must contain 24–4096 URL-safe characters.');
34
+ this.origins = new Set((options.origins ?? []).map(value => { const url = new URL(value); if (!['http:', 'https:'].includes(url.protocol) || url.origin !== value)
35
+ throw new Error('Allowed control origins must be exact HTTP(S) origins.'); return value; }));
36
+ this.now = options.now ?? Date.now;
37
+ }
38
+ timestamp() { return new Date(this.now()).toISOString(); }
39
+ // Reserve terminal-error metadata for every retained request as well as its current bytes.
40
+ usedBytes() { let bytes = this.requests.size * 2048; for (const entry of this.runtimes.values())
41
+ bytes += Buffer.byteLength(JSON.stringify(entry)); for (const entry of this.requests.values())
42
+ bytes += Buffer.byteLength(JSON.stringify(entry)); return bytes; }
43
+ publicRequest(entry) { const { client_id, ...publicValue } = entry; return entry.command === 'debug.attach' ? { ...publicValue, payload: { ...entry.payload, token: '[redacted]' } } : publicValue; }
44
+ expire() {
45
+ for (const [id, runtime] of this.runtimes)
46
+ if (this.now() - runtime.lastSeen > (this.options.heartbeatTimeoutMs ?? 15000))
47
+ this.detach(id, runtime.client_id);
48
+ for (const [id, entry] of this.requests)
49
+ if (['completed', 'failed'].includes(entry.status) && this.now() - Date.parse(entry.updated_at) > 30 * 60 * 1000)
50
+ this.requests.delete(id);
51
+ }
52
+ detach(id, client) {
53
+ if (this.runtimes.get(id)?.client_id !== client)
54
+ return;
55
+ this.runtimes.delete(id);
56
+ for (const entry of this.requests.values())
57
+ if (entry.runtime_instance_id === id && entry.client_id === client && ['queued', 'dispatched'].includes(entry.status)) {
58
+ entry.error = { code: 'runtime_disconnected', message: 'Runtime detached. No command was automatically replayed.', uncertain: entry.status === 'dispatched' };
59
+ entry.status = 'failed';
60
+ entry.updated_at = this.timestamp();
61
+ }
62
+ }
63
+ async body(request) {
64
+ if (Number(request.headers.get('content-length') ?? 0) > MAX_BODY)
65
+ failure(413, 'request_too_large', 'Control messages are limited to 1 MiB.');
66
+ const reader = request.body?.getReader();
67
+ if (!reader)
68
+ return failure(400, 'invalid_request', 'A JSON body is required.');
69
+ let timer;
70
+ try {
71
+ const bytes = await Promise.race([(async () => { const parts = []; let length = 0; while (true) {
72
+ const part = await reader.read();
73
+ if (part.done)
74
+ break;
75
+ length += part.value.byteLength;
76
+ if (length > MAX_BODY)
77
+ failure(413, 'request_too_large', 'Control messages are limited to 1 MiB.');
78
+ parts.push(part.value);
79
+ } return Buffer.concat(parts, length); })(), new Promise((_, reject) => { timer = setTimeout(() => reject(new ControlError(408, 'request_timeout', 'Control body timed out.')), 5000); })]);
80
+ try {
81
+ return record(JSON.parse(bytes.toString('utf8')));
82
+ }
83
+ catch (error) {
84
+ if (error instanceof ControlError)
85
+ throw error;
86
+ return failure(400, 'invalid_json', 'Control body must contain JSON.');
87
+ }
88
+ }
89
+ finally {
90
+ clearTimeout(timer);
91
+ void reader.cancel().catch(() => { });
92
+ }
93
+ }
94
+ async handle(request) {
95
+ let allowedOrigin;
96
+ try {
97
+ const url = new URL(request.url), host = request.headers.get('Host') ?? url.host;
98
+ let suppliedHost;
99
+ try {
100
+ suppliedHost = new URL(`http://${host}`);
101
+ }
102
+ catch {
103
+ return failure(403, 'host_forbidden', 'Invalid control host.');
104
+ }
105
+ if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || !['localhost', '127.0.0.1', '[::1]'].includes(suppliedHost.hostname) || suppliedHost.port !== url.port || suppliedHost.username || suppliedHost.password || suppliedHost.pathname !== '/')
106
+ failure(403, 'host_forbidden', 'Control is available only on its loopback address.');
107
+ const origin = request.headers.get('Origin');
108
+ if (origin) {
109
+ if (!this.origins.has(origin))
110
+ failure(403, 'origin_forbidden', 'This browser origin is not allowed to use local control.');
111
+ allowedOrigin = origin;
112
+ }
113
+ if (url.search || url.hash)
114
+ failure(404, 'not_found', 'Control endpoints do not accept query parameters.');
115
+ if (request.method === 'OPTIONS') {
116
+ if (!allowedOrigin)
117
+ failure(403, 'origin_forbidden', 'Preflight requires an explicitly allowed browser origin.');
118
+ return new Response(null, { status: 204, headers: { 'Access-Control-Allow-Origin': allowedOrigin, 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Authorization, Content-Type', 'Access-Control-Allow-Private-Network': 'true', 'Vary': 'Origin' } });
119
+ }
120
+ if (!authEqual(request.headers.get('Authorization') ?? '', `Bearer ${this.options.token}`))
121
+ failure(401, 'unauthorized', 'A valid local control token is required.');
122
+ this.expire();
123
+ const result = await this.dispatch(request, url.pathname);
124
+ if (allowedOrigin) {
125
+ result.headers.set('Access-Control-Allow-Origin', allowedOrigin);
126
+ result.headers.set('Vary', 'Origin');
127
+ }
128
+ return result;
129
+ }
130
+ catch (error) {
131
+ const issue = error instanceof ControlError ? error : new ControlError(500, 'internal_error', 'The control request could not be completed.');
132
+ const result = response({ error: { code: issue.code, message: issue.message } }, issue.status);
133
+ if (allowedOrigin)
134
+ result.headers.set('Access-Control-Allow-Origin', allowedOrigin);
135
+ return result;
136
+ }
137
+ }
138
+ async dispatch(request, path) {
139
+ if (path === `${PREFIX}/runtimes` && request.method === 'GET')
140
+ return response({ runtimes: [...this.runtimes.values()].map(entry => ({ runtime: entry.runtime, capabilities: entry.capabilities, last_seen_at: new Date(entry.lastSeen).toISOString() })) });
141
+ const lookup = path.match(/^\/v1\/control\/requests\/([A-Za-z0-9_.:-]{1,200})$/);
142
+ if (lookup && request.method === 'GET') {
143
+ const entry = this.requests.get(lookup[1]);
144
+ if (!entry)
145
+ failure(404, 'not_found', 'Control request not found or expired.');
146
+ return response({ request: this.publicRequest(entry) });
147
+ }
148
+ if (request.method !== 'POST')
149
+ return failure(405, 'method_not_allowed', 'Control uses GET for inspection and POST for commands.');
150
+ if ([`${PREFIX}/register`, `${PREFIX}/poll`, `${PREFIX}/results`, `${PREFIX}/unregister`].includes(path)) {
151
+ const body = await this.body(request), client = body.client_id;
152
+ if (!identifier(client))
153
+ failure(400, 'invalid_identity', 'A client_id is required.');
154
+ if (path.endsWith('/register')) {
155
+ const status = record(body.runtime), id = status.runtimeInstanceId;
156
+ if (!identifier(id) || !Array.isArray(body.capabilities) || body.capabilities.some(value => typeof value !== 'string' || ![...COMMANDS.values()].includes(value)))
157
+ failure(400, 'invalid_registration', 'Runtime identity and supported capabilities are required.');
158
+ const previous = this.runtimes.get(id);
159
+ if (previous && previous.client_id !== client)
160
+ failure(409, 'runtime_already_attached', 'This Runtime already has an active control attachment.');
161
+ if (!previous && this.runtimes.size >= MAX_RUNTIMES)
162
+ failure(429, 'control_capacity', 'Runtime attachment limit reached.');
163
+ if (Buffer.byteLength(JSON.stringify(body)) > 32768 || this.usedBytes() > MAX_MEMORY - 32768)
164
+ failure(413, 'control_capacity', 'Registration metadata exceeds the control limit.');
165
+ this.runtimes.set(id, { client_id: client, runtime: status, capabilities: [...new Set(body.capabilities)], lastSeen: this.now() });
166
+ return response({ ok: true, poll_interval_ms: 500 });
167
+ }
168
+ const id = body.runtime_instance_id, entry = this.runtimes.get(String(id));
169
+ if (!entry || entry.client_id !== client)
170
+ failure(409, 'attachment_lost', 'Runtime attachment no longer belongs to this client.');
171
+ entry.lastSeen = this.now();
172
+ if (path.endsWith('/unregister')) {
173
+ this.detach(String(id), String(client));
174
+ return response({ ok: true });
175
+ }
176
+ if (path.endsWith('/poll')) {
177
+ const ready = [...this.requests.values()].filter(item => item.runtime_instance_id === id && item.client_id === client && item.status === 'queued').slice(0, 8);
178
+ for (const item of ready) {
179
+ item.status = 'dispatched';
180
+ item.updated_at = this.timestamp();
181
+ }
182
+ return response({ commands: ready.map(item => ({ request_id: item.request_id, command: item.command, payload: item.payload })) });
183
+ }
184
+ const target = this.requests.get(String(body.request_id));
185
+ if (!target || target.runtime_instance_id !== id || target.client_id !== client)
186
+ failure(404, 'not_found', 'Matching control request not found.');
187
+ if (target.status === 'queued')
188
+ failure(409, 'not_dispatched', 'The command has not been dispatched.');
189
+ if (target.status === 'failed')
190
+ return response({ ok: true, retained: true });
191
+ const hasResult = Object.hasOwn(body, 'result'), hasError = Object.hasOwn(body, 'error');
192
+ if (hasResult === hasError)
193
+ failure(400, 'invalid_result', 'Supply exactly one result or error.');
194
+ if (target.status === 'completed') {
195
+ if (!isDeepStrictEqual(target.result, body.result))
196
+ failure(409, 'result_conflict', 'A different result is already retained.');
197
+ return response({ ok: true, duplicate: true });
198
+ }
199
+ if (this.usedBytes() + Buffer.byteLength(JSON.stringify(body)) > MAX_MEMORY)
200
+ failure(413, 'control_capacity', 'Control result storage is full.');
201
+ if (hasError) {
202
+ const error = record(body.error);
203
+ target.error = { code: typeof error.code === 'string' ? error.code.slice(0, 100) : 'runtime_error', message: typeof error.message === 'string' ? error.message.slice(0, 1000) : 'Runtime command failed.', uncertain: error.uncertain === true };
204
+ target.status = 'failed';
205
+ }
206
+ else {
207
+ target.result = body.result;
208
+ target.status = 'completed';
209
+ }
210
+ target.updated_at = this.timestamp();
211
+ return response({ ok: true });
212
+ }
213
+ const action = path.match(/^\/v1\/control\/runtimes\/([A-Za-z0-9_.:-]{1,200})\/([a-z-]+)$/);
214
+ const command = action ? COMMANDS.get(action[2]) : undefined;
215
+ if (!action || !command)
216
+ failure(404, 'not_found', 'Control endpoint not found.');
217
+ const body = await this.body(request), requestId = body.request_id, payload = record(body.payload ?? {});
218
+ if (!identifier(requestId))
219
+ failure(400, 'invalid_identity', 'A stable control request_id is required.');
220
+ if (command === 'debug.attach') {
221
+ let url;
222
+ try {
223
+ url = new URL(String(payload.url));
224
+ }
225
+ catch {
226
+ return failure(400, 'invalid_command', 'Debugger attachment requires a loopback HTTP origin.');
227
+ }
228
+ if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(url.hostname) || url.username || url.password || url.search || url.hash || url.pathname !== '/' || typeof payload.token !== 'string' || !/^[A-Za-z0-9._~-]{16,4096}$/.test(payload.token) || !['full', 'runtime'].includes(String(payload.visibility)) || Object.keys(payload).some(key => !['url', 'token', 'visibility'].includes(key)))
229
+ failure(400, 'invalid_command', 'Debugger attachment requires a loopback origin, pairing token and supported visibility.');
230
+ }
231
+ if (command === 'debug.detach' && Object.keys(payload).length)
232
+ failure(400, 'invalid_command', 'Debugger detach takes an empty payload.');
233
+ // Replays are compared as JSON values, never as serialized text: hosts do not share a key
234
+ // order (Swift dictionaries iterate in a per-process random order), and a retry is the same input.
235
+ const previous = this.requests.get(String(requestId));
236
+ if (previous) {
237
+ if (!isDeepStrictEqual([previous.runtime_instance_id, previous.command, previous.payload], [action[1], command, payload]))
238
+ failure(409, 'request_conflict', 'Request ID already has different command input.');
239
+ return response({ request: this.publicRequest(previous) }, ['queued', 'dispatched'].includes(previous.status) ? 202 : 200);
240
+ }
241
+ const runtime = this.runtimes.get(action[1]);
242
+ if (!runtime)
243
+ failure(404, 'runtime_not_attached', 'Runtime is not currently attached to this broker.');
244
+ if (!runtime.capabilities.includes(command))
245
+ failure(409, 'unsupported_capability', 'This Runtime attachment does not expose that capability.');
246
+ const entry = { request_id: String(requestId), runtime_instance_id: action[1], client_id: runtime.client_id, command, payload, status: 'queued', created_at: this.timestamp(), updated_at: this.timestamp() };
247
+ if (this.requests.size >= MAX_REQUESTS || this.usedBytes() + Buffer.byteLength(JSON.stringify(entry)) + 2048 > MAX_MEMORY)
248
+ failure(429, 'control_capacity', 'Control request storage is full.');
249
+ this.requests.set(entry.request_id, entry);
250
+ return response({ request: this.publicRequest(entry) }, 202);
251
+ }
252
+ }
253
+ export async function startControlServer(options) {
254
+ const broker = new ControlBroker(options);
255
+ const server = createServer(async (incoming, outgoing) => {
256
+ try {
257
+ const address = server.address();
258
+ const headers = new Headers();
259
+ for (const [key, value] of Object.entries(incoming.headers))
260
+ if (value !== undefined)
261
+ headers.set(key, Array.isArray(value) ? value.join(',') : value);
262
+ const origin = `http://127.0.0.1:${address.port}`;
263
+ // Absolute-form proxy requests are never treated as arbitrary targets.
264
+ if (!incoming.url?.startsWith('/')) {
265
+ outgoing.writeHead(400);
266
+ outgoing.end();
267
+ return;
268
+ }
269
+ const init = { method: incoming.method, headers };
270
+ if (!['GET', 'HEAD'].includes(incoming.method ?? 'GET')) {
271
+ init.body = Readable.toWeb(incoming);
272
+ init.duplex = 'half';
273
+ }
274
+ const result = await broker.handle(new Request(origin + incoming.url, init));
275
+ outgoing.writeHead(result.status, Object.fromEntries(result.headers));
276
+ outgoing.end(Buffer.from(await result.arrayBuffer()));
277
+ }
278
+ catch {
279
+ if (!outgoing.headersSent)
280
+ outgoing.writeHead(500, { 'Content-Type': 'application/json' });
281
+ outgoing.end('{"error":{"code":"internal_error","message":"Control request failed."}}');
282
+ }
283
+ });
284
+ server.requestTimeout = 6000;
285
+ server.headersTimeout = 5000;
286
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(options.port ?? 8791, '127.0.0.1', () => { server.off('error', reject); resolve(); }); });
287
+ return { url: `http://127.0.0.1:${server.address().port}`, broker, close: async () => { server.closeAllConnections(); await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); } };
288
+ }
@@ -0,0 +1 @@
1
+ export declare const DEFAULT_CLOUD_URL = "https://api.croche.ai";
@@ -0,0 +1,2 @@
1
+ // Generated from the Rust Core by scripts/build-core.ts. Do not edit.
2
+ export const DEFAULT_CLOUD_URL = "https://api.croche.ai";
@@ -0,0 +1,13 @@
1
+ export type CredentialEnv = Record<string, string | undefined>;
2
+ export declare const validCredential: (key: string) => boolean;
3
+ export declare function credentialPath(env: CredentialEnv, platform?: NodeJS.Platform, home?: string): string;
4
+ export declare function resolveCredential(env: CredentialEnv): Promise<{
5
+ key: string;
6
+ source: 'env' | 'stored';
7
+ }>;
8
+ export declare function storeCredential(env: CredentialEnv, key: string): Promise<string>;
9
+ export declare function removeCredential(env: CredentialEnv): Promise<void>;
10
+ /** Human input only: never accept a credential in argv or echo its bytes. */
11
+ export declare function readCredentialInput(input?: NodeJS.ReadStream & {
12
+ fd: 0;
13
+ }, prompt?: (text: string) => void): Promise<string>;