@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.
- package/README.md +267 -148
- package/THIRD-PARTY-NOTICES +7 -8
- package/dist/bin.js +29 -25
- package/dist/chunk-66EUX7EL.js +165 -0
- package/dist/chunk-DKT5HHSB.js +532 -0
- package/dist/chunk-K3UDT4EM.js +3110 -0
- package/dist/collector-credential.d.ts +9 -0
- package/dist/config-authoring.d.ts +19 -0
- package/dist/config-bases.d.ts +17 -0
- package/dist/config-push-base-35HX67AJ.js +2254 -0
- package/dist/config-push-base.d.ts +7 -0
- package/dist/control-address.d.ts +2 -0
- package/dist/control-server.d.ts +12 -15
- package/dist/control-server.js +9 -288
- package/dist/control-v2-auth.d.ts +24 -0
- package/dist/control-v2-capture.d.ts +34 -0
- package/dist/control-v2-json.d.ts +15 -0
- package/dist/control-v2-state.d.ts +90 -0
- package/dist/credentials.d.ts +2 -2
- package/dist/debugger/public/index.html +1 -0
- package/dist/debugger/public/stage-control.js +84 -0
- package/dist/debugger/public/stage-manifest.js +45 -0
- package/dist/debugger/public/stage-model.js +103 -0
- package/dist/debugger/public/stage-targets.js +18 -0
- package/dist/debugger/public/stage.css +459 -0
- package/dist/debugger/public/stage.html +17 -0
- package/dist/debugger/public/stage.js +113 -0
- package/dist/debugger/server/collector.js +42 -26
- package/dist/debugger/server/control-bridge.js +113 -0
- package/dist/debugger/server/server.js +10 -1
- package/dist/debugger/server/viewer-security.js +12 -0
- package/dist/debugger.d.ts +16 -6
- package/dist/index.d.ts +8 -1
- package/dist/index.js +17 -321
- package/dist/json-result.d.ts +2 -0
- package/package.json +2 -1
- package/dist/config.js +0 -100
- package/dist/control-client.js +0 -65
- package/dist/core-defaults.js +0 -2
- package/dist/credentials.js +0 -136
- package/dist/debug-keys.js +0 -141
- package/dist/debugger.js +0 -469
- package/dist/help.js +0 -158
- package/dist/text-file.js +0 -15
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
type Context = {
|
|
2
|
+
env: Record<string, string | undefined>;
|
|
3
|
+
readFile: (path: string, what: string) => Promise<string>;
|
|
4
|
+
request: (path: string, method?: string, body?: unknown) => Promise<any>;
|
|
5
|
+
};
|
|
6
|
+
export declare function pushBase(args: Record<string, string>, context: Context): Promise<unknown>;
|
|
7
|
+
export {};
|
package/dist/control-server.d.ts
CHANGED
|
@@ -1,29 +1,26 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { type AuthOptions } from './control-v2-auth.js';
|
|
2
|
+
export interface ControlServerOptions extends AuthOptions {
|
|
3
3
|
port?: number;
|
|
4
4
|
origins?: string[];
|
|
5
|
+
remoteAddress?: string;
|
|
5
6
|
now?: () => number;
|
|
6
|
-
|
|
7
|
+
monotonic?: () => number;
|
|
7
8
|
}
|
|
8
|
-
/**
|
|
9
|
+
/** Bounded in-memory v2 transport; app consent and canonical operations remain in Core. */
|
|
9
10
|
export declare class ControlBroker {
|
|
10
11
|
private options;
|
|
11
|
-
private
|
|
12
|
-
private
|
|
12
|
+
private auth;
|
|
13
|
+
private state;
|
|
14
|
+
private capture;
|
|
13
15
|
private origins;
|
|
14
|
-
private
|
|
16
|
+
private timer;
|
|
15
17
|
constructor(options: ControlServerOptions);
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
private publicRequest;
|
|
19
|
-
private expire;
|
|
20
|
-
private detach;
|
|
21
|
-
private body;
|
|
22
|
-
handle(request: Request): Promise<Response>;
|
|
23
|
-
private dispatch;
|
|
18
|
+
close(): void;
|
|
19
|
+
handle(request: Request, remoteViewer?: boolean): Promise<Response>;
|
|
24
20
|
}
|
|
25
21
|
export declare function startControlServer(options: ControlServerOptions): Promise<{
|
|
26
22
|
url: string;
|
|
23
|
+
remoteUrl?: string;
|
|
27
24
|
broker: ControlBroker;
|
|
28
25
|
close: () => Promise<void>;
|
|
29
26
|
}>;
|
package/dist/control-server.js
CHANGED
|
@@ -1,288 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
ControlBroker,
|
|
3
|
+
startControlServer
|
|
4
|
+
} from "./chunk-DKT5HHSB.js";
|
|
5
|
+
import "./chunk-66EUX7EL.js";
|
|
6
|
+
export {
|
|
7
|
+
ControlBroker,
|
|
8
|
+
startControlServer
|
|
9
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface RoleGrant {
|
|
2
|
+
token: string;
|
|
3
|
+
role: 'observe' | 'control';
|
|
4
|
+
attachments: string[];
|
|
5
|
+
}
|
|
6
|
+
export interface AuthOptions {
|
|
7
|
+
token: string;
|
|
8
|
+
ingestToken?: string;
|
|
9
|
+
observeToken?: string;
|
|
10
|
+
ingestTokens?: string[];
|
|
11
|
+
grants?: RoleGrant[];
|
|
12
|
+
}
|
|
13
|
+
export interface Principal {
|
|
14
|
+
id: string;
|
|
15
|
+
role: 'ingest' | 'observe' | 'control';
|
|
16
|
+
attachments: Set<string> | null;
|
|
17
|
+
}
|
|
18
|
+
export declare class ControlAuth {
|
|
19
|
+
private values;
|
|
20
|
+
constructor(options: AuthOptions);
|
|
21
|
+
authenticate(request: Request, ingest: boolean, write: boolean): Principal;
|
|
22
|
+
permits(principal: Principal, attachmentId: string): boolean;
|
|
23
|
+
redact(value: unknown): unknown;
|
|
24
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type AgentRow } from './control-v2-state.js';
|
|
2
|
+
type Capture = {
|
|
3
|
+
seq: number;
|
|
4
|
+
event: Record<string, unknown>;
|
|
5
|
+
};
|
|
6
|
+
export declare class ControlCapture {
|
|
7
|
+
private streams;
|
|
8
|
+
used(): number;
|
|
9
|
+
ingest(b: Record<string, unknown>, redact: (v: unknown) => unknown, capacity: (extra: number) => void, validateRoster: (r: {
|
|
10
|
+
rosterRevision: number;
|
|
11
|
+
agents: AgentRow[];
|
|
12
|
+
}) => void): {
|
|
13
|
+
through: number;
|
|
14
|
+
roster?: {
|
|
15
|
+
rosterRevision: number;
|
|
16
|
+
agents: AgentRow[];
|
|
17
|
+
};
|
|
18
|
+
events: Record<string, unknown>[];
|
|
19
|
+
};
|
|
20
|
+
read(attachmentId: string, after: unknown): {
|
|
21
|
+
attachmentId: string;
|
|
22
|
+
entries: {
|
|
23
|
+
cursor: number;
|
|
24
|
+
capture: Capture;
|
|
25
|
+
}[];
|
|
26
|
+
through: number;
|
|
27
|
+
gaps: {
|
|
28
|
+
from: number;
|
|
29
|
+
through: number;
|
|
30
|
+
reason: string;
|
|
31
|
+
}[];
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare class ControlError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
readonly code: string;
|
|
4
|
+
constructor(status: number, code: string);
|
|
5
|
+
}
|
|
6
|
+
export declare function refuse(status: number, code: string): never;
|
|
7
|
+
export declare const reply: (value: unknown, status?: number) => Response;
|
|
8
|
+
export declare const object: (v: unknown) => v is Record<string, unknown>;
|
|
9
|
+
export declare const record: (v: unknown) => Record<string, unknown>;
|
|
10
|
+
export declare const id: (v: unknown) => v is string;
|
|
11
|
+
export declare const count: (v: unknown) => v is number;
|
|
12
|
+
export declare function same(a: unknown, b: unknown): boolean;
|
|
13
|
+
/** Duplicate-aware, portable JSON at the transport boundary, before any effect. */
|
|
14
|
+
export declare function parse(text: string): Record<string, unknown>;
|
|
15
|
+
export declare function body(request: Request): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { Principal } from './control-v2-auth.js';
|
|
2
|
+
export declare const CAPS: Set<string>;
|
|
3
|
+
export interface Target {
|
|
4
|
+
agentId: string;
|
|
5
|
+
instance: string | null;
|
|
6
|
+
openSequence: number;
|
|
7
|
+
}
|
|
8
|
+
export interface AgentRow {
|
|
9
|
+
agentId: string;
|
|
10
|
+
instance: string | null;
|
|
11
|
+
open: boolean;
|
|
12
|
+
runtimeInstanceId?: string;
|
|
13
|
+
openSequence?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface Attachment {
|
|
16
|
+
attachmentId: string;
|
|
17
|
+
principal: string;
|
|
18
|
+
runtime: Record<string, unknown>;
|
|
19
|
+
capabilities: string[];
|
|
20
|
+
state: 'connected' | 'disconnected';
|
|
21
|
+
rosterRevision: number;
|
|
22
|
+
agents: AgentRow[];
|
|
23
|
+
expires: number;
|
|
24
|
+
}
|
|
25
|
+
export interface Command {
|
|
26
|
+
attachmentId: string;
|
|
27
|
+
request_id: string;
|
|
28
|
+
command: string;
|
|
29
|
+
target?: Target;
|
|
30
|
+
payload: Record<string, unknown>;
|
|
31
|
+
viewerId: string;
|
|
32
|
+
status: 'queued' | 'dispatched' | 'completed' | 'failed';
|
|
33
|
+
created_at: number;
|
|
34
|
+
updated_at: number;
|
|
35
|
+
result?: unknown;
|
|
36
|
+
error?: {
|
|
37
|
+
code: string;
|
|
38
|
+
category?: string;
|
|
39
|
+
uncertain?: true;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export declare function target(value: unknown): Target;
|
|
43
|
+
export declare function roster(value: unknown): {
|
|
44
|
+
rosterRevision: number;
|
|
45
|
+
agents: AgentRow[];
|
|
46
|
+
};
|
|
47
|
+
export declare class ControlState {
|
|
48
|
+
readonly now: () => number;
|
|
49
|
+
readonly monotonic: () => number;
|
|
50
|
+
private project;
|
|
51
|
+
readonly attachments: Map<string, Attachment>;
|
|
52
|
+
readonly requests: Map<string, Command>;
|
|
53
|
+
constructor(now: () => number, monotonic: () => number, project?: (v: unknown) => unknown);
|
|
54
|
+
fits(value: unknown): void;
|
|
55
|
+
used(): number;
|
|
56
|
+
capacity(extra?: number): void;
|
|
57
|
+
rosterCapacity(candidate: Attachment): void;
|
|
58
|
+
expire(): void;
|
|
59
|
+
detach(a: Attachment): void;
|
|
60
|
+
owned(value: unknown, p: Principal): Attachment;
|
|
61
|
+
live(value: unknown, p: Principal): Attachment;
|
|
62
|
+
validateTarget(a: Attachment, t?: Target, command?: string): void;
|
|
63
|
+
checkRoster(a: Attachment, value: unknown): {
|
|
64
|
+
rosterRevision: number;
|
|
65
|
+
agents: AgentRow[];
|
|
66
|
+
};
|
|
67
|
+
updateRoster(a: Attachment, value: unknown): void;
|
|
68
|
+
register(b: Record<string, unknown>, p: Principal): {
|
|
69
|
+
attachmentId: string;
|
|
70
|
+
brokerVersion: string;
|
|
71
|
+
pollIntervalMs: number;
|
|
72
|
+
leaseMs: number;
|
|
73
|
+
};
|
|
74
|
+
queue(b: Record<string, unknown>, p: Principal, a: Attachment): Command;
|
|
75
|
+
poll(a: Attachment): {
|
|
76
|
+
attachmentId: string;
|
|
77
|
+
commands: {
|
|
78
|
+
payload: Record<string, unknown>;
|
|
79
|
+
viewerId: string;
|
|
80
|
+
target?: Target | undefined;
|
|
81
|
+
attachmentId: string;
|
|
82
|
+
request_id: string;
|
|
83
|
+
command: string;
|
|
84
|
+
}[];
|
|
85
|
+
};
|
|
86
|
+
result(b: Record<string, unknown>, a: Attachment): {
|
|
87
|
+
request_id: string;
|
|
88
|
+
retained: boolean;
|
|
89
|
+
};
|
|
90
|
+
}
|
package/dist/credentials.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export type CredentialEnv = Record<string, string | undefined>;
|
|
2
2
|
export declare const validCredential: (key: string) => boolean;
|
|
3
3
|
export declare function credentialPath(env: CredentialEnv, platform?: NodeJS.Platform, home?: string): string;
|
|
4
|
-
/**
|
|
4
|
+
/** Only the current account-key environment name participates in authentication. */
|
|
5
5
|
export declare function environmentCredential(env: CredentialEnv): string | undefined;
|
|
6
|
-
/** The environment
|
|
6
|
+
/** The environment variable that currently holds an account key. */
|
|
7
7
|
export declare function environmentCredentialNames(env: CredentialEnv): string[];
|
|
8
8
|
export declare function resolveCredential(env: CredentialEnv): Promise<{
|
|
9
9
|
key: string;
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
<span><span class="brand-name">croche</span><span class="brand-divider">/</span><span class="brand-product">Runtime debugger</span></span>
|
|
16
16
|
</a>
|
|
17
17
|
<div class="header-actions">
|
|
18
|
+
<a href="/stage" class="button">Stage view ↗</a>
|
|
18
19
|
<span id="connection-status" class="connection-status"><span class="status-dot"></span><span>Connecting</span></span>
|
|
19
20
|
<button id="connect-app" class="button button-primary">CLI connection <span aria-hidden="true">↗</span></button>
|
|
20
21
|
</div>
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Public v2 protocol only. No runtime imports, ingest credentials or credential persistence.
|
|
2
|
+
export function controlOrigin(value,remote=false){
|
|
3
|
+
const url=new URL(value),loopback=['127.0.0.1','localhost','[::1]'].includes(url.hostname),remoteIp=/^(?:\d{1,3}\.){3}\d{1,3}$/.test(url.hostname)||/^\[[0-9a-f:]+\]$/i.test(url.hostname);
|
|
4
|
+
if(url.protocol!=='http:'||(!loopback&&(!remote||!remoteIp))||url.username||url.password||url.pathname!=='/'||url.search||url.hash)throw Error('Use a loopback HTTP control origin, or explicitly enable the server-approved remote IP.');return url.origin;
|
|
5
|
+
}
|
|
6
|
+
export function userPayload(text,kind){if(typeof text!=='string'||(kind!==undefined&&!['user','app_event','app_state'].includes(kind)))throw Error('Invalid input text or kind.');return {id:crypto.randomUUID(),text,...(kind===undefined?{}:{kind})};}
|
|
7
|
+
const sameTarget=(a,b)=>a?.agentId===b?.agentId&&a?.instance===b?.instance&&a?.openSequence===b?.openSequence;
|
|
8
|
+
export function mountControl({getRuntime,onRoster=()=>{},onRemote=()=>{},onCapture=()=>{},request=fetch,root=document}){
|
|
9
|
+
const $=id=>root.getElementById(id);let grant=null,checking=null,epoch=0,busy=false,cancelling=false,pending=false,timer;
|
|
10
|
+
const status=text=>{$('control-status').textContent=text;};
|
|
11
|
+
function update(){
|
|
12
|
+
const selected=getRuntime();$('send-input').disabled=!grant||grant.role!=='control'||busy||pending||!selected?.capabilities?.includes('send');
|
|
13
|
+
const kinds=selected?.capabilities?.includes('send')&&selected.capabilities.includes('send.kind');
|
|
14
|
+
for(const option of $('input-kind').options??[])option.disabled=option.value!=='user'&&!kinds;
|
|
15
|
+
$('input-kind').title=kinds?'Input kind':'App event/state require this Runtime to advertise send.kind.';
|
|
16
|
+
if($('cancel-input'))$('cancel-input').disabled=!grant||grant.role!=='control'||cancelling||!selected?.capabilities?.includes('cancel');
|
|
17
|
+
$('revoke-control').hidden=!grant;$('attach-control').disabled=busy;
|
|
18
|
+
if($('projects'))$('projects').disabled=busy;if($('sessions'))$('sessions').disabled=busy;
|
|
19
|
+
}
|
|
20
|
+
function revoke(){epoch++;clearInterval(timer);grant?.abort.abort();checking?.abort.abort();checking=null;grant=null;onRemote(false);busy=false;cancelling=false;pending=false;$('control-token').value='';status('Read-only. App consent and a separate controller grant are required to send or cancel.');update();}
|
|
21
|
+
async function call(connection,path,body){
|
|
22
|
+
const response=await request(connection.origin+'/v2/control'+path,{method:body===undefined?'GET':'POST',headers:{Authorization:'Bearer '+connection.token,...(body===undefined?{}:{'Content-Type':'application/json'})},...(body===undefined?{}:{body:JSON.stringify(body)}),credentials:'omit',redirect:'error',signal:AbortSignal.any([connection.abort.signal,AbortSignal.timeout(5000)])});
|
|
23
|
+
if(!response.ok){await response.body?.cancel().catch(()=>{});throw Error('Control v2 refused ('+response.status+'). Check app consent, credential role and origin.');}
|
|
24
|
+
const reader=response.body?.getReader();if(!reader)throw Error('Empty control reply.');let bytes=0;const chunks=[];
|
|
25
|
+
try{for(;;){const next=await reader.read();if(next.done)break;bytes+=next.value.byteLength;if(bytes>1024*1024)throw Error('Control reply exceeds its bound.');chunks.push(next.value);}}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
|
|
26
|
+
const all=new Uint8Array(bytes);let at=0;for(const chunk of chunks){all.set(chunk,at);at+=chunk.byteLength;}connection.abort.signal.throwIfAborted();return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(all));
|
|
27
|
+
}
|
|
28
|
+
async function roster(connection){
|
|
29
|
+
const r=await call(connection,'/attachments');if(!Array.isArray(r.attachments))throw Error('Live attachment roster unavailable.');
|
|
30
|
+
connection.role=r.viewer?.role==='control'?'control':'observe';
|
|
31
|
+
if(connection.remote){
|
|
32
|
+
for(const a of r.attachments.filter(a=>a.state==='connected')){
|
|
33
|
+
const after=connection.cursors.get(a.attachmentId)??0,page=await call(connection,'/read',{attachmentId:a.attachmentId,after});
|
|
34
|
+
if(page.attachmentId!==a.attachmentId||!Number.isSafeInteger(page.through)||page.through<after||!Array.isArray(page.entries)||!Array.isArray(page.gaps))throw Error('Invalid remote capture cursor.');
|
|
35
|
+
const events=[];let last=after;for(const row of page.entries){if(!Number.isSafeInteger(row.cursor)||row.cursor<=last||row.cursor>page.through||!row.capture?.event)throw Error('Invalid remote capture entry.');last=row.cursor;if(row.capture.event.type!=='roster')events.push(row.capture.event);}
|
|
36
|
+
onCapture(events,page.gaps);connection.cursors.set(a.attachmentId,page.through);
|
|
37
|
+
}
|
|
38
|
+
onRemote(true);
|
|
39
|
+
}
|
|
40
|
+
onRoster(r.attachments);return r.attachments;
|
|
41
|
+
}
|
|
42
|
+
$('control-token').value='';
|
|
43
|
+
$('attach-control').onclick=async()=>{
|
|
44
|
+
const token=$('control-token').value;revoke();const current=epoch;
|
|
45
|
+
try{
|
|
46
|
+
if(!/^[A-Za-z0-9._~-]{24,4096}$/.test(token))throw Error('Enter the separate controller token, never the runtime ingest token.');
|
|
47
|
+
const remote=$('remote-control')?.checked===true;
|
|
48
|
+
const candidate={origin:controlOrigin($('control-url').value,remote),token,remote,cursors:new Map(),abort:new AbortController()};checking=candidate;busy=true;update();await roster(candidate);if(current!==epoch)return;
|
|
49
|
+
grant=candidate;checking=null;status('Viewer token enabled for this page. Commands require a controller grant. Reload or Revoke forgets it; accepted app work is not cancelled.');
|
|
50
|
+
timer=setInterval(()=>{if(grant===candidate&&!busy)void roster(candidate).then(update).catch(()=>{if(grant===candidate){revoke();status('Live roster disconnected or grant refused. Captures are not liveness; enable a fresh explicit grant.');}});},2000);
|
|
51
|
+
}catch(error){if(current===epoch)status(error.message);}
|
|
52
|
+
finally{if(current===epoch){busy=false;$('control-token').value='';update();}}
|
|
53
|
+
};
|
|
54
|
+
async function issue(command){
|
|
55
|
+
if(!grant||grant.role!=='control'||(command==='send'&&(busy||pending))||(command==='cancel'&&cancelling))return;
|
|
56
|
+
const selected=getRuntime();if(!selected?.target||!selected.capabilities?.includes(command)){status('Select an open agent with this capability.');return;}
|
|
57
|
+
if(command==='send'&&$('input-kind').value!=='user'&&!selected.capabilities.includes('send.kind')){status('This Runtime does not advertise send.kind; app event/state are unavailable.');return;}
|
|
58
|
+
const connection=grant,current=epoch,target={...selected.target},attachmentId=selected.attachmentId,request_id=crypto.randomUUID();
|
|
59
|
+
let submitted=false;try{
|
|
60
|
+
const payload=command==='send'?userPayload($('input-text').value,selected.capabilities.includes('send.kind')?$('input-kind').value:undefined):{};
|
|
61
|
+
if(command==='send'){busy=true;pending=true;}else cancelling=true;update();
|
|
62
|
+
const attachments=await roster(connection);if(current!==epoch)return;
|
|
63
|
+
const live=attachments.find(a=>a.attachmentId===attachmentId&&a.state==='connected');
|
|
64
|
+
if(!live?.capabilities?.includes(command)||!live.agents?.some(a=>a.open===true&&sameTarget(a,target)&&a.runtimeInstanceId===selected.runtimeInstanceId))throw Error('Target closed or reopened. Select its new open row explicitly.');
|
|
65
|
+
if(command==='send'&&payload.kind!==undefined&&!live.capabilities.includes('send.kind'))throw Error('Runtime no longer advertises send.kind. No command submitted.');
|
|
66
|
+
submitted=true;status(command==='send'?'Submitting input… No automatic resend.':'Cancelling this exact agent…');
|
|
67
|
+
let response=await call(connection,'/commands',{attachmentId,request_id,command,target,payload});const deadline=Date.now()+120000;
|
|
68
|
+
for(;;){
|
|
69
|
+
if(current!==epoch)return;const r=response?.request;
|
|
70
|
+
if(r?.request_id!==request_id||r.attachmentId!==attachmentId||r.command!==command||!sameTarget(r.target,target))throw Error('Uncorrelated reply; inspect the original request.');
|
|
71
|
+
if(!['queued','dispatched'].includes(r.status)||Date.now()>=deadline)break;
|
|
72
|
+
await new Promise(resolve=>setTimeout(resolve,200));if(current!==epoch)return;response=await call(connection,'/requests/'+encodeURIComponent(request_id));
|
|
73
|
+
}
|
|
74
|
+
if(response.request.status==='completed'){if(command==='send'){pending=false;$('input-text').value='';}status(command==='send'?'Input accepted by the agent. Follow its captured reply above.':'Cancel completed for the selected agent.');}
|
|
75
|
+
else if(response.request.status==='failed'&&!response.request.error?.uncertain){if(command==='send')pending=false;status('Command failed ('+(response.request.error?.code??'runtime_error')+'). No automatic resend.');}
|
|
76
|
+
else status('Delivery outcome unknown. Not resent. Inspect request '+request_id+' before acting again.');
|
|
77
|
+
}catch(error){if(current===epoch){if(!submitted&&command==='send')pending=false;status((submitted?'Delivery outcome unknown; no resend. ':'No command submitted. ')+error.message);}}
|
|
78
|
+
finally{if(current===epoch){if(command==='send')busy=false;else cancelling=false;update();}}
|
|
79
|
+
}
|
|
80
|
+
$('input-form').onsubmit=event=>{event.preventDefault();return issue('send');};
|
|
81
|
+
if($('cancel-input'))$('cancel-input').onclick=()=>issue('cancel');
|
|
82
|
+
$('revoke-control').onclick=revoke;const forget=()=>revoke();window.addEventListener('pagehide',forget);window.addEventListener('pageshow',forget);
|
|
83
|
+
revoke();return {revoke,update};
|
|
84
|
+
}
|