@cbxss/eoka 0.0.0-stage → 0.1.0-beta.2
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 +577 -2
- package/dist/LICENSE +21 -0
- package/dist/browser-install-diagnostics.d.ts +1 -0
- package/dist/browser-install-diagnostics.js +21 -0
- package/dist/browser-install-engine.d.ts +10 -0
- package/dist/browser-install-engine.js +286 -0
- package/dist/browser-install-inventory.d.ts +34 -0
- package/dist/browser-install-inventory.js +107 -0
- package/dist/browser-install-worker.d.ts +21 -0
- package/dist/browser-install-worker.js +65 -0
- package/dist/browser-install.d.ts +22 -0
- package/dist/browser-install.js +7 -0
- package/dist/browser.d.ts +59 -0
- package/dist/browser.js +445 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.js +1 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +44 -0
- package/dist/generated/protocol.d.ts +3929 -0
- package/dist/generated/protocol.js +2 -0
- package/dist/generated/schema-bundle.json +18964 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +11 -0
- package/dist/install-errors.d.ts +4 -0
- package/dist/install-errors.js +6 -0
- package/dist/operations.d.ts +22 -0
- package/dist/operations.js +87 -0
- package/dist/page.d.ts +77 -0
- package/dist/page.js +250 -0
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js +27 -0
- package/dist/recording.d.ts +27 -0
- package/dist/recording.js +124 -0
- package/dist/release-manifest.json +101 -0
- package/dist/release.d.ts +36 -0
- package/dist/release.js +76 -0
- package/dist/server-binary.d.ts +11 -0
- package/dist/server-binary.js +107 -0
- package/dist/transport.d.ts +89 -0
- package/dist/transport.js +737 -0
- package/examples/capture.mjs +36 -0
- package/examples/consume-schema.mjs +7 -0
- package/examples/explicit-paths.mjs +42 -0
- package/examples/install-browser.mjs +20 -0
- package/examples/offline.mjs +20 -0
- package/package.json +70 -4
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { TextDecoder } from 'node:util';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { Ajv2020 } from 'ajv/dist/2020.js';
|
|
5
|
+
import bundle from './generated/schema-bundle.json' with { type: 'json' };
|
|
6
|
+
import { protocolVersion } from './generated/protocol.js';
|
|
7
|
+
import { ConfigurationError, EokaError, ProtocolError, ServerOperationError, TransportError } from './errors.js';
|
|
8
|
+
const contracts = bundle.methods;
|
|
9
|
+
let ajv;
|
|
10
|
+
const validators = new Map();
|
|
11
|
+
const localMessageLimit = 32 * 1024 * 1024;
|
|
12
|
+
const localPendingLimit = 128;
|
|
13
|
+
const stderrLimit = 16 * 1024;
|
|
14
|
+
const maximumTimer = 2_147_483_647;
|
|
15
|
+
function duration(value, fallback, name) {
|
|
16
|
+
const result = value ?? fallback;
|
|
17
|
+
if (!Number.isFinite(result) || result < 0 || result > maximumTimer) {
|
|
18
|
+
throw new ConfigurationError(`${name} must be finite and between 0 and ${maximumTimer}`, { requestState: 'not_sent' });
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
function secretMatcher(values) {
|
|
23
|
+
const alternatives = new Set();
|
|
24
|
+
for (const value of values) {
|
|
25
|
+
if (!value)
|
|
26
|
+
continue;
|
|
27
|
+
alternatives.add(value);
|
|
28
|
+
alternatives.add(encodeURIComponent(value));
|
|
29
|
+
alternatives.add(JSON.stringify(value).slice(1, -1));
|
|
30
|
+
}
|
|
31
|
+
if (alternatives.size === 0)
|
|
32
|
+
return undefined;
|
|
33
|
+
const escaped = [...alternatives].sort((left, right) => right.length - left.length).map(value => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
34
|
+
return new RegExp(escaped.join('|'), 'g');
|
|
35
|
+
}
|
|
36
|
+
function redactLine(line, secrets) {
|
|
37
|
+
let result = line.replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s<>"']+/gi, text => {
|
|
38
|
+
if (secrets && text.replace(secrets, '[REDACTED]') !== text)
|
|
39
|
+
return '[REDACTED URL]';
|
|
40
|
+
try {
|
|
41
|
+
const url = new URL(text);
|
|
42
|
+
const path = url.pathname.replace(/\/devtools\/(?:browser|page)\/.*/gi, '/devtools/[REDACTED]');
|
|
43
|
+
return `${url.protocol}//${url.host}${path}${url.search ? '?[REDACTED]' : ''}${url.hash ? '#[REDACTED]' : ''}`;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return '[REDACTED URL]';
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
if (secrets)
|
|
50
|
+
result = result.replace(secrets, '[REDACTED]');
|
|
51
|
+
result = result.replace(/(\b["']?(?:[a-z\d]+[-_])*(?:proxy[-_]?authorization|authorization|authentication|auth|set[-_]?cookie|cookie|(?:access[-_]?|refresh[-_]?)?token|password|passwd|secret|api[-_]?key)["']?\s*[:=]\s*).*/gi, '$1[REDACTED]');
|
|
52
|
+
result = result.replace(/(\b(?:Bearer|Basic)\s+).*/gi, '$1[REDACTED]');
|
|
53
|
+
return result.replace(/(\B--(?:password|passwd|token|api[-_]?key)\s+).*/gi, '$1[REDACTED]');
|
|
54
|
+
}
|
|
55
|
+
function object(value) {
|
|
56
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
57
|
+
}
|
|
58
|
+
function receiptEvidence(receipt) {
|
|
59
|
+
if (receipt.outcome === 'verified_complete' && (!receipt.verification || (receipt.dispatch !== 'acknowledged' && !receipt.already_satisfied))) {
|
|
60
|
+
throw new ProtocolError('Verified receipt is missing completion or dispatch evidence');
|
|
61
|
+
}
|
|
62
|
+
if (receipt.outcome === 'not_dispatched' && receipt.dispatch !== 'not_sent') {
|
|
63
|
+
throw new ProtocolError('Receipt contradicts its dispatch state');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function operationEvidence(record, expectedId) {
|
|
67
|
+
if (expectedId !== undefined && record.id !== expectedId)
|
|
68
|
+
throw new ProtocolError('Operation response has a different operation ID');
|
|
69
|
+
if (record.receipt) {
|
|
70
|
+
receiptEvidence(record.receipt);
|
|
71
|
+
if (record.receipt.outcome !== record.outcome || record.receipt.action !== record.action || record.receipt.target_id !== record.target_id) {
|
|
72
|
+
throw new ProtocolError('Operation record contradicts its receipt');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (record.outcome === 'verified_complete' && (record.state !== 'finished' || !record.receipt || record.finished_at_ms == null)) {
|
|
76
|
+
throw new ProtocolError('Verified operation is missing terminal receipt evidence');
|
|
77
|
+
}
|
|
78
|
+
if (record.state === 'running' && (record.receipt != null || record.finished_at_ms != null)) {
|
|
79
|
+
throw new ProtocolError('Running operation contains terminal evidence');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export class SidecarTransport {
|
|
83
|
+
child;
|
|
84
|
+
shutdownTimeoutMs;
|
|
85
|
+
pending = new Map();
|
|
86
|
+
decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
87
|
+
greeting;
|
|
88
|
+
supported = new Set();
|
|
89
|
+
nextId = 1;
|
|
90
|
+
messageLimit = localMessageLimit;
|
|
91
|
+
pendingLimit = localPendingLimit;
|
|
92
|
+
frame = Buffer.alloc(0);
|
|
93
|
+
frameLength = 0;
|
|
94
|
+
queuedBytes = 0;
|
|
95
|
+
blocked = false;
|
|
96
|
+
closing = false;
|
|
97
|
+
quiescing = false;
|
|
98
|
+
finished = false;
|
|
99
|
+
exited = false;
|
|
100
|
+
stderrBytes = Buffer.alloc(0);
|
|
101
|
+
stderrClipped = false;
|
|
102
|
+
finalStderr;
|
|
103
|
+
secrets;
|
|
104
|
+
escalating = false;
|
|
105
|
+
failure;
|
|
106
|
+
cleanupError;
|
|
107
|
+
closeCompletion;
|
|
108
|
+
teardownTimer;
|
|
109
|
+
shutdownId;
|
|
110
|
+
closed = Promise.withResolvers();
|
|
111
|
+
terminationConfirmed = false;
|
|
112
|
+
shutdownAcknowledged = false;
|
|
113
|
+
childClosed = false;
|
|
114
|
+
windowsTreeTerminated = false;
|
|
115
|
+
constructor(child, shutdownTimeoutMs, secrets) {
|
|
116
|
+
void this.closed.promise.catch(() => { });
|
|
117
|
+
this.child = child;
|
|
118
|
+
this.shutdownTimeoutMs = shutdownTimeoutMs;
|
|
119
|
+
this.secrets = secrets;
|
|
120
|
+
child.stdout.on('data', this.onData);
|
|
121
|
+
child.stdout.on('end', this.onEnd);
|
|
122
|
+
child.stdout.on('error', this.onStreamError);
|
|
123
|
+
child.stderr.on('data', this.onStderr);
|
|
124
|
+
child.stderr.on('error', this.onStreamError);
|
|
125
|
+
child.stdin.on('error', this.onStreamError);
|
|
126
|
+
child.stdin.on('drain', this.onDrain);
|
|
127
|
+
child.on('error', this.onProcessError);
|
|
128
|
+
child.on('exit', this.onExit);
|
|
129
|
+
child.on('close', this.onClose);
|
|
130
|
+
}
|
|
131
|
+
static async start(options) {
|
|
132
|
+
const timeoutMs = duration(options.timeoutMs, 30_000, 'timeoutMs');
|
|
133
|
+
const shutdownTimeoutMs = duration(options.shutdownTimeoutMs, 45_000, 'shutdownTimeoutMs');
|
|
134
|
+
const secrets = secretMatcher(options.redactionValues ?? []);
|
|
135
|
+
if (!options.serverPath)
|
|
136
|
+
throw new ConfigurationError('An explicit serverPath is required', { requestState: 'not_sent' });
|
|
137
|
+
if (options.signal?.aborted)
|
|
138
|
+
throw new TransportError('Aborted', 'Sidecar startup was aborted before spawning', { requestState: 'not_sent', cause: options.signal.reason });
|
|
139
|
+
let child;
|
|
140
|
+
try {
|
|
141
|
+
child = spawn(options.serverPath, [], { shell: false, stdio: 'pipe', detached: process.platform !== 'win32', ...(options.env === undefined ? {} : { env: options.env }) });
|
|
142
|
+
}
|
|
143
|
+
catch (cause) {
|
|
144
|
+
throw new TransportError('Spawn', 'Could not spawn the sidecar', { cause, requestState: 'not_sent' });
|
|
145
|
+
}
|
|
146
|
+
const transport = new SidecarTransport(child, shutdownTimeoutMs, secrets);
|
|
147
|
+
try {
|
|
148
|
+
options.onTransport?.(transport);
|
|
149
|
+
const hello = await transport.request('server.hello', { protocol: protocolVersion }, { timeoutMs, ...(options.signal === undefined ? {} : { signal: options.signal }) });
|
|
150
|
+
if (transport.failure)
|
|
151
|
+
throw transport.failure;
|
|
152
|
+
if (transport.closing || transport.finished)
|
|
153
|
+
throw new TransportError('Closed', 'Sidecar closed during handshake');
|
|
154
|
+
if (hello.protocol.major !== protocolVersion.major || hello.protocol.minor < protocolVersion.minor) {
|
|
155
|
+
throw new ProtocolError('Sidecar protocol is incompatible with this SDK');
|
|
156
|
+
}
|
|
157
|
+
const shutdownBytes = Buffer.byteLength(JSON.stringify({ id: Number.MAX_SAFE_INTEGER, method: 'server.shutdown', params: {} }));
|
|
158
|
+
if (hello.limits.maxInFlight < 1 || hello.limits.maxMessageBytes < shutdownBytes || !hello.methods.includes('server.shutdown')) {
|
|
159
|
+
throw new ProtocolError('Sidecar advertised unusable transport limits or shutdown support');
|
|
160
|
+
}
|
|
161
|
+
transport.greeting = hello;
|
|
162
|
+
transport.supported = new Set(hello.methods);
|
|
163
|
+
transport.messageLimit = Math.min(localMessageLimit, hello.limits.maxMessageBytes);
|
|
164
|
+
transport.pendingLimit = Math.min(localPendingLimit, hello.limits.maxInFlight);
|
|
165
|
+
if (transport.frameLength > transport.messageLimit)
|
|
166
|
+
throw new ProtocolError('Buffered peer frame exceeds negotiated limit');
|
|
167
|
+
return transport;
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
if (error instanceof EokaError)
|
|
171
|
+
transport.failure ??= error;
|
|
172
|
+
try {
|
|
173
|
+
await transport.close();
|
|
174
|
+
}
|
|
175
|
+
catch (cleanup) {
|
|
176
|
+
throw new TransportError('StartupCleanup', 'Sidecar startup failed and cleanup did not complete gracefully', { cause: new AggregateError([error, cleanup]), stderr: transport.stderr });
|
|
177
|
+
}
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
get hello() {
|
|
182
|
+
if (!this.greeting)
|
|
183
|
+
throw new ProtocolError('Sidecar handshake has not completed');
|
|
184
|
+
return this.greeting;
|
|
185
|
+
}
|
|
186
|
+
get pid() {
|
|
187
|
+
return this.child.pid;
|
|
188
|
+
}
|
|
189
|
+
get stderr() {
|
|
190
|
+
if (this.finalStderr !== undefined)
|
|
191
|
+
return this.finalStderr;
|
|
192
|
+
const text = this.stderrBytes.toString('utf8');
|
|
193
|
+
const first = this.stderrClipped ? text.indexOf('\n') + 1 : 0;
|
|
194
|
+
const last = text.lastIndexOf('\n');
|
|
195
|
+
if (last < first || (this.stderrClipped && first === 0))
|
|
196
|
+
return text ? '[REDACTED partial stderr omitted]' : '';
|
|
197
|
+
const lines = text.slice(first, last).split('\n');
|
|
198
|
+
const safe = [];
|
|
199
|
+
let bytes = 0;
|
|
200
|
+
for (const line of lines) {
|
|
201
|
+
let redacted = redactLine(line, this.secrets);
|
|
202
|
+
let length = Buffer.byteLength(redacted) + 1;
|
|
203
|
+
if (length > stderrLimit) {
|
|
204
|
+
redacted = '[REDACTED oversized stderr line]';
|
|
205
|
+
length = Buffer.byteLength(redacted) + 1;
|
|
206
|
+
}
|
|
207
|
+
while (bytes + length > stderrLimit && safe.length > 0)
|
|
208
|
+
bytes -= Buffer.byteLength(safe.shift()) + 1;
|
|
209
|
+
safe.push(redacted);
|
|
210
|
+
bytes += length;
|
|
211
|
+
}
|
|
212
|
+
return safe.join('\n');
|
|
213
|
+
}
|
|
214
|
+
supports(method) { return this.supported.has(method); }
|
|
215
|
+
hasCapability(name) { return this.greeting?.capabilities.includes(name) === true; }
|
|
216
|
+
invoke(method, params, options = {}) {
|
|
217
|
+
return this.request(method, params, options);
|
|
218
|
+
}
|
|
219
|
+
invokeTracked(method, params, options = {}) {
|
|
220
|
+
const { promise: completion, resolve, reject } = Promise.withResolvers();
|
|
221
|
+
const callbacks = { resolve: value => resolve(value), reject };
|
|
222
|
+
void completion.catch(() => { });
|
|
223
|
+
const result = this.request(method, params, options, callbacks);
|
|
224
|
+
return { result, completion };
|
|
225
|
+
}
|
|
226
|
+
quiesce() {
|
|
227
|
+
this.quiescing = true;
|
|
228
|
+
this.rejectPending(new TransportError('Closed', 'Sidecar transport is being disposed'));
|
|
229
|
+
}
|
|
230
|
+
invokeCleanup(method, params, options = {}) {
|
|
231
|
+
if (method !== 'browser.close_tab')
|
|
232
|
+
return Promise.reject(new ConfigurationError('Only exact-tab cleanup is permitted during disposal', { requestState: 'not_sent' }));
|
|
233
|
+
return this.request(method, params, options, undefined, true);
|
|
234
|
+
}
|
|
235
|
+
validate(key, schema, value) {
|
|
236
|
+
const compiler = ajv ??= new Ajv2020({ strict: false, validateFormats: false });
|
|
237
|
+
let validator = validators.get(key);
|
|
238
|
+
if (!validator) {
|
|
239
|
+
validator = compiler.compile(schema);
|
|
240
|
+
validators.set(key, validator);
|
|
241
|
+
}
|
|
242
|
+
if (!validator(value))
|
|
243
|
+
throw new ProtocolError(`Invalid ${key}: ${compiler.errorsText(validator.errors)}`);
|
|
244
|
+
}
|
|
245
|
+
request(method, params, options, completion, cleanup = false) {
|
|
246
|
+
let entry;
|
|
247
|
+
let operationId;
|
|
248
|
+
try {
|
|
249
|
+
const data = params;
|
|
250
|
+
operationId = options.operationId ?? (object(data) && typeof data.operation_id === 'string' ? data.operation_id : typeof method === 'string' && method.startsWith('operations.') && object(data) && typeof data.id === 'string' ? data.id : undefined);
|
|
251
|
+
const timeoutMs = options.timeoutMs === undefined ? undefined : duration(options.timeoutMs, 0, 'timeoutMs');
|
|
252
|
+
const deadline = timeoutMs === undefined ? undefined : performance.now() + timeoutMs;
|
|
253
|
+
const details = { operationId, requestState: 'not_sent' };
|
|
254
|
+
if (this.closing || this.failure || (this.quiescing && !cleanup))
|
|
255
|
+
throw new TransportError('Closed', 'Sidecar transport is closed', { ...details, cause: this.failure });
|
|
256
|
+
if (options.signal?.aborted)
|
|
257
|
+
throw new TransportError('Aborted', 'Request aborted before dispatch', { ...details, cause: options.signal.reason });
|
|
258
|
+
if (timeoutMs === 0)
|
|
259
|
+
throw new TransportError('DeadlineExceeded', 'Request deadline expired before dispatch', details);
|
|
260
|
+
if (!Object.hasOwn(contracts, method) || (this.greeting && !this.supported.has(method)))
|
|
261
|
+
throw new TransportError('UnsupportedMethod', `Sidecar does not support ${method}`, details);
|
|
262
|
+
if (method !== 'server.shutdown' && this.pending.size >= this.pendingLimit)
|
|
263
|
+
throw new TransportError('PendingLimit', 'Sidecar in-flight request limit reached', details);
|
|
264
|
+
if (this.nextId > Number.MAX_SAFE_INTEGER)
|
|
265
|
+
throw new TransportError('RequestIdExhausted', 'Safe request IDs have been exhausted', details);
|
|
266
|
+
try {
|
|
267
|
+
this.validate(`${method} params`, contracts[method].params, params);
|
|
268
|
+
}
|
|
269
|
+
catch (cause) {
|
|
270
|
+
throw new ConfigurationError(`Invalid parameters for ${method}`, { ...details, cause });
|
|
271
|
+
}
|
|
272
|
+
const id = this.nextId++;
|
|
273
|
+
let serialized;
|
|
274
|
+
try {
|
|
275
|
+
serialized = JSON.stringify({ id, method, params });
|
|
276
|
+
}
|
|
277
|
+
catch (cause) {
|
|
278
|
+
throw new ConfigurationError('Request parameters must be JSON serializable', { ...details, requestId: id, cause });
|
|
279
|
+
}
|
|
280
|
+
const bytes = Buffer.byteLength(serialized);
|
|
281
|
+
if (bytes > this.messageLimit)
|
|
282
|
+
throw new TransportError('MessageTooLarge', 'Request exceeds negotiated message limit', { ...details, requestId: id });
|
|
283
|
+
if (method !== 'server.shutdown' && this.queuedBytes + bytes + 1 > localMessageLimit + 1)
|
|
284
|
+
throw new TransportError('PendingLimit', 'Buffered request byte limit reached', { ...details, requestId: id });
|
|
285
|
+
const frame = Buffer.from(`${serialized}\n`);
|
|
286
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
287
|
+
entry = { id, method, operationId, sent: false, frame, resolve: value => resolve(value), reject, completion, signal: options.signal, abort: undefined, timer: undefined };
|
|
288
|
+
const current = entry;
|
|
289
|
+
this.pending.set(id, current);
|
|
290
|
+
this.queuedBytes += frame.length;
|
|
291
|
+
if (options.signal) {
|
|
292
|
+
current.abort = () => this.cancel(current, 'Aborted', options.signal?.reason);
|
|
293
|
+
options.signal.addEventListener('abort', current.abort, { once: true });
|
|
294
|
+
}
|
|
295
|
+
if (deadline !== undefined) {
|
|
296
|
+
const remaining = deadline - performance.now();
|
|
297
|
+
if (remaining <= 0)
|
|
298
|
+
this.cancel(current, 'DeadlineExceeded');
|
|
299
|
+
else
|
|
300
|
+
current.timer = setTimeout(() => this.cancel(current, 'DeadlineExceeded'), remaining);
|
|
301
|
+
}
|
|
302
|
+
if (this.pending.has(current.id) && (method === 'server.shutdown' || method === 'browser.close'))
|
|
303
|
+
void this.beginClose(current).catch(() => { });
|
|
304
|
+
else
|
|
305
|
+
this.flush();
|
|
306
|
+
return promise;
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
if (entry)
|
|
310
|
+
this.remove(entry);
|
|
311
|
+
if (error instanceof EokaError) {
|
|
312
|
+
error.operationId ??= operationId;
|
|
313
|
+
error.requestState ??= 'not_sent';
|
|
314
|
+
error.stderr ??= this.stderr;
|
|
315
|
+
}
|
|
316
|
+
completion?.reject(error);
|
|
317
|
+
return Promise.reject(error);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
details(entry, stderr = this.stderr) {
|
|
321
|
+
return { requestId: entry.id, operationId: entry.operationId, requestState: entry.sent ? 'may_have_been_sent' : 'not_sent', stderr };
|
|
322
|
+
}
|
|
323
|
+
detach(entry) {
|
|
324
|
+
clearTimeout(entry.timer);
|
|
325
|
+
if (entry.signal && entry.abort)
|
|
326
|
+
entry.signal.removeEventListener('abort', entry.abort);
|
|
327
|
+
entry.timer = undefined;
|
|
328
|
+
entry.signal = undefined;
|
|
329
|
+
entry.abort = undefined;
|
|
330
|
+
}
|
|
331
|
+
remove(entry) {
|
|
332
|
+
this.detach(entry);
|
|
333
|
+
if (entry.frame)
|
|
334
|
+
this.queuedBytes -= entry.frame.length;
|
|
335
|
+
entry.frame = undefined;
|
|
336
|
+
this.pending.delete(entry.id);
|
|
337
|
+
}
|
|
338
|
+
cancel(entry, code, cause) {
|
|
339
|
+
if (!entry.reject)
|
|
340
|
+
return;
|
|
341
|
+
const reject = entry.reject;
|
|
342
|
+
this.detach(entry);
|
|
343
|
+
entry.reject = undefined;
|
|
344
|
+
entry.resolve = undefined;
|
|
345
|
+
const error = new TransportError(code, entry.sent ? 'Local request cancelled after possible dispatch; the action was not rolled back' : 'Local request cancelled before dispatch', { ...this.details(entry), cause });
|
|
346
|
+
reject(error);
|
|
347
|
+
if (!entry.sent) {
|
|
348
|
+
entry.completion?.reject(error);
|
|
349
|
+
this.remove(entry);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
flush() {
|
|
353
|
+
if (this.blocked || this.closing)
|
|
354
|
+
return;
|
|
355
|
+
for (const entry of this.pending.values()) {
|
|
356
|
+
if (!entry.frame)
|
|
357
|
+
continue;
|
|
358
|
+
const frame = entry.frame;
|
|
359
|
+
this.queuedBytes -= frame.length;
|
|
360
|
+
entry.frame = undefined;
|
|
361
|
+
entry.sent = true;
|
|
362
|
+
try {
|
|
363
|
+
if (!this.child.stdin.write(frame)) {
|
|
364
|
+
this.blocked = true;
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
catch (cause) {
|
|
369
|
+
this.fail(new TransportError('Write', 'Writing to the sidecar failed', { cause }));
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
onDrain = () => {
|
|
375
|
+
this.blocked = false;
|
|
376
|
+
this.flush();
|
|
377
|
+
};
|
|
378
|
+
onStderr = (chunk) => {
|
|
379
|
+
const total = this.stderrBytes.length + chunk.length;
|
|
380
|
+
this.stderrClipped ||= total > stderrLimit;
|
|
381
|
+
if (chunk.length >= stderrLimit)
|
|
382
|
+
this.stderrBytes = Buffer.from(chunk.subarray(chunk.length - stderrLimit));
|
|
383
|
+
else {
|
|
384
|
+
const keep = Math.min(this.stderrBytes.length, stderrLimit - chunk.length);
|
|
385
|
+
this.stderrBytes = Buffer.concat([this.stderrBytes.subarray(this.stderrBytes.length - keep), chunk], keep + chunk.length);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
onData = (chunk) => {
|
|
389
|
+
if (this.finished || this.failure)
|
|
390
|
+
return;
|
|
391
|
+
try {
|
|
392
|
+
let offset = 0;
|
|
393
|
+
while (offset < chunk.length) {
|
|
394
|
+
const newline = chunk.indexOf(10, offset);
|
|
395
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
396
|
+
const length = end - offset;
|
|
397
|
+
if (this.frameLength + length > this.messageLimit + 1)
|
|
398
|
+
throw new ProtocolError('Peer frame exceeds negotiated message limit');
|
|
399
|
+
let frame;
|
|
400
|
+
if (this.frameLength === 0 && newline >= 0) {
|
|
401
|
+
frame = chunk.subarray(offset, end);
|
|
402
|
+
this.frameLength = length;
|
|
403
|
+
}
|
|
404
|
+
else {
|
|
405
|
+
const needed = this.frameLength + length;
|
|
406
|
+
if (needed > this.frame.length) {
|
|
407
|
+
const capacity = Math.min(this.messageLimit + 1, Math.max(needed, this.frame.length * 2, 4096));
|
|
408
|
+
const next = Buffer.allocUnsafe(capacity);
|
|
409
|
+
this.frame.copy(next, 0, 0, this.frameLength);
|
|
410
|
+
this.frame = next;
|
|
411
|
+
}
|
|
412
|
+
chunk.copy(this.frame, this.frameLength, offset, end);
|
|
413
|
+
this.frameLength = needed;
|
|
414
|
+
if (newline < 0)
|
|
415
|
+
return;
|
|
416
|
+
frame = this.frame.subarray(0, this.frameLength);
|
|
417
|
+
}
|
|
418
|
+
let frameEnd = frame.length;
|
|
419
|
+
if (frameEnd > 0 && frame[frameEnd - 1] === 13)
|
|
420
|
+
frameEnd--;
|
|
421
|
+
if (frameEnd > this.messageLimit)
|
|
422
|
+
throw new ProtocolError('Peer frame exceeds negotiated message limit');
|
|
423
|
+
if (frameEnd === 0)
|
|
424
|
+
throw new ProtocolError('Peer emitted an empty NDJSON frame');
|
|
425
|
+
const text = this.decoder.decode(frameEnd === frame.length ? frame : frame.subarray(0, frameEnd));
|
|
426
|
+
this.frameLength = 0;
|
|
427
|
+
this.response(JSON.parse(text));
|
|
428
|
+
offset = newline + 1;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
catch (cause) {
|
|
432
|
+
this.fail(cause instanceof ProtocolError ? cause : new ProtocolError('Peer emitted malformed JSON or UTF-8', { cause }));
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
response(value) {
|
|
436
|
+
if (!object(value) || Object.keys(value).length !== 2 || !Object.hasOwn(value, 'id') || Object.hasOwn(value, 'result') === Object.hasOwn(value, 'error')) {
|
|
437
|
+
throw new ProtocolError('Peer emitted an invalid response envelope');
|
|
438
|
+
}
|
|
439
|
+
if (Object.hasOwn(value, 'error'))
|
|
440
|
+
this.validate('server error', bundle.types.ServerError, value.error);
|
|
441
|
+
if (value.id === null && Object.hasOwn(value, 'error')) {
|
|
442
|
+
throw new ProtocolError('Peer emitted an uncorrelated error', { cause: new ServerOperationError(value.error) });
|
|
443
|
+
}
|
|
444
|
+
if (typeof value.id !== 'number' || !Number.isSafeInteger(value.id) || value.id <= 0)
|
|
445
|
+
throw new ProtocolError('Peer response ID is not a safe positive integer');
|
|
446
|
+
const entry = this.pending.get(value.id);
|
|
447
|
+
if (!entry || !entry.sent)
|
|
448
|
+
throw new ProtocolError('Peer response has an unknown or undispatched request ID');
|
|
449
|
+
if (Object.hasOwn(value, 'error')) {
|
|
450
|
+
const details = { ...this.details(entry), requestState: 'acknowledged' };
|
|
451
|
+
const wireError = value.error;
|
|
452
|
+
if (wireError.data?.receipt)
|
|
453
|
+
receiptEvidence(wireError.data.receipt);
|
|
454
|
+
if (entry.operationId && wireError.data?.operation_id && entry.operationId !== wireError.data.operation_id)
|
|
455
|
+
throw new ProtocolError('Server error has a different operation ID');
|
|
456
|
+
const error = new ServerOperationError(wireError, details);
|
|
457
|
+
if (entry.id === this.shutdownId)
|
|
458
|
+
this.cleanupError = error;
|
|
459
|
+
entry.reject?.(error);
|
|
460
|
+
entry.completion?.reject(error);
|
|
461
|
+
}
|
|
462
|
+
else {
|
|
463
|
+
const schema = contracts[entry.method].result;
|
|
464
|
+
this.validate(`${entry.method} result`, schema, value.result);
|
|
465
|
+
if (schema.title === 'OperationRecord')
|
|
466
|
+
operationEvidence(value.result, entry.operationId);
|
|
467
|
+
else if (schema.title === 'Array_of_OperationRecord')
|
|
468
|
+
for (const record of value.result)
|
|
469
|
+
operationEvidence(record);
|
|
470
|
+
else if (schema.title === 'AgentStepResult') {
|
|
471
|
+
const result = value.result;
|
|
472
|
+
if (entry.operationId && result.operation_id !== entry.operationId)
|
|
473
|
+
throw new ProtocolError('Agent response has a different operation ID');
|
|
474
|
+
if (result.operation)
|
|
475
|
+
operationEvidence(result.operation, result.operation_id);
|
|
476
|
+
}
|
|
477
|
+
if (entry.id === this.shutdownId)
|
|
478
|
+
this.shutdownAcknowledged = true;
|
|
479
|
+
entry.resolve?.(value.result);
|
|
480
|
+
entry.completion?.resolve(value.result);
|
|
481
|
+
}
|
|
482
|
+
this.remove(entry);
|
|
483
|
+
if (entry.id === this.shutdownId && entry.method === 'browser.close')
|
|
484
|
+
this.child.stdin.end();
|
|
485
|
+
}
|
|
486
|
+
rejectPending(error) {
|
|
487
|
+
let stderr;
|
|
488
|
+
for (const entry of this.pending.values()) {
|
|
489
|
+
if (entry.id === this.shutdownId && !this.failure)
|
|
490
|
+
continue;
|
|
491
|
+
const details = { ...this.details(entry, stderr ??= this.stderr), cause: error };
|
|
492
|
+
const local = error instanceof ProtocolError ? new ProtocolError(error.message, details) : new TransportError(error.code, error.message, details);
|
|
493
|
+
entry.reject?.(local);
|
|
494
|
+
if (this.failure || !entry.sent) {
|
|
495
|
+
entry.completion?.reject(local);
|
|
496
|
+
entry.completion = undefined;
|
|
497
|
+
}
|
|
498
|
+
entry.reject = undefined;
|
|
499
|
+
entry.resolve = undefined;
|
|
500
|
+
this.detach(entry);
|
|
501
|
+
if (!entry.sent)
|
|
502
|
+
this.remove(entry);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
fail(error) {
|
|
506
|
+
if (this.finished)
|
|
507
|
+
return;
|
|
508
|
+
this.failure ??= error;
|
|
509
|
+
if (this.closing)
|
|
510
|
+
this.cleanupError ??= error;
|
|
511
|
+
this.rejectPending(error);
|
|
512
|
+
if (this.closing && !this.child.stdin.writableEnded && !this.child.stdin.destroyed) {
|
|
513
|
+
try {
|
|
514
|
+
this.child.stdin.end();
|
|
515
|
+
}
|
|
516
|
+
catch (cause) {
|
|
517
|
+
this.cleanupError = new TransportError('ShutdownWrite', 'Could not end sidecar input after a fatal failure', { cause: new AggregateError([this.cleanupError ?? error, cause]), stderr: this.stderr });
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
void this.close().catch(() => { });
|
|
521
|
+
}
|
|
522
|
+
onEnd = () => {
|
|
523
|
+
if (this.frameLength !== 0)
|
|
524
|
+
this.fail(new ProtocolError('Peer ended with an unterminated NDJSON frame'));
|
|
525
|
+
else if (!this.closing)
|
|
526
|
+
this.fail(new TransportError('EOF', 'Sidecar stdout ended before transport disposal'));
|
|
527
|
+
};
|
|
528
|
+
onStreamError = (cause) => {
|
|
529
|
+
this.fail(new TransportError('Stream', 'Sidecar stream failed', { cause, stderr: this.stderr }));
|
|
530
|
+
};
|
|
531
|
+
onProcessError = (cause) => {
|
|
532
|
+
this.fail(new TransportError('Process', 'Sidecar process failed', { cause, stderr: this.stderr }));
|
|
533
|
+
};
|
|
534
|
+
onExit = (code, signal) => {
|
|
535
|
+
this.exited = true;
|
|
536
|
+
if (code !== 0 || signal !== null) {
|
|
537
|
+
const error = new TransportError('ProcessExit', `Sidecar exited with ${signal ?? `code ${code}`}`, { stderr: this.stderr });
|
|
538
|
+
if (this.closing)
|
|
539
|
+
this.cleanupError ??= error;
|
|
540
|
+
else
|
|
541
|
+
this.fail(error);
|
|
542
|
+
}
|
|
543
|
+
else if (!this.closing)
|
|
544
|
+
this.fail(new TransportError('ProcessExit', 'Sidecar exited before transport disposal', { stderr: this.stderr }));
|
|
545
|
+
};
|
|
546
|
+
onClose = () => {
|
|
547
|
+
this.childClosed = true;
|
|
548
|
+
if (!this.closing)
|
|
549
|
+
this.fail(new TransportError('ProcessExit', 'Sidecar process closed before disposal', { stderr: this.stderr }));
|
|
550
|
+
if (this.escalating) {
|
|
551
|
+
if (process.platform !== 'win32' && !this.ownedGroupAlive())
|
|
552
|
+
this.finishClose();
|
|
553
|
+
}
|
|
554
|
+
else if (process.platform !== 'win32' && this.ownedGroupAlive())
|
|
555
|
+
void this.terminate();
|
|
556
|
+
else
|
|
557
|
+
this.finishClose();
|
|
558
|
+
};
|
|
559
|
+
close() {
|
|
560
|
+
return this.beginClose();
|
|
561
|
+
}
|
|
562
|
+
whenClosed() {
|
|
563
|
+
return this.closed.promise;
|
|
564
|
+
}
|
|
565
|
+
get ownedProcessesTerminated() {
|
|
566
|
+
return this.terminationConfirmed;
|
|
567
|
+
}
|
|
568
|
+
beginClose(terminal) {
|
|
569
|
+
if (this.closeCompletion)
|
|
570
|
+
return this.closeCompletion.promise;
|
|
571
|
+
this.closeCompletion = Promise.withResolvers();
|
|
572
|
+
this.closing = true;
|
|
573
|
+
if (terminal)
|
|
574
|
+
this.shutdownId = terminal.id;
|
|
575
|
+
this.rejectPending(new TransportError('Closed', 'Sidecar transport is closing'));
|
|
576
|
+
if (this.finished)
|
|
577
|
+
return this.closeCompletion.promise;
|
|
578
|
+
try {
|
|
579
|
+
if (terminal?.frame) {
|
|
580
|
+
const frame = terminal.frame;
|
|
581
|
+
this.queuedBytes -= frame.length;
|
|
582
|
+
terminal.frame = undefined;
|
|
583
|
+
terminal.sent = true;
|
|
584
|
+
if (terminal.method === 'browser.close')
|
|
585
|
+
this.child.stdin.write(frame);
|
|
586
|
+
else
|
|
587
|
+
this.child.stdin.end(frame);
|
|
588
|
+
}
|
|
589
|
+
else if (!this.failure && !this.exited && !this.child.stdin.destroyed && this.nextId <= Number.MAX_SAFE_INTEGER) {
|
|
590
|
+
const id = this.nextId++;
|
|
591
|
+
this.shutdownId = id;
|
|
592
|
+
this.pending.set(id, { id, method: 'server.shutdown', operationId: undefined, sent: true, frame: undefined, resolve: undefined, reject: undefined, signal: undefined, abort: undefined, timer: undefined });
|
|
593
|
+
this.child.stdin.end(`${JSON.stringify({ id, method: 'server.shutdown', params: {} })}\n`);
|
|
594
|
+
}
|
|
595
|
+
else
|
|
596
|
+
this.child.stdin.end();
|
|
597
|
+
}
|
|
598
|
+
catch (cause) {
|
|
599
|
+
this.cleanupError ??= new TransportError('ShutdownWrite', 'Could not send sidecar shutdown; cleanup may be incomplete', { cause, stderr: this.stderr });
|
|
600
|
+
}
|
|
601
|
+
this.teardownTimer = setTimeout(() => { void this.terminate(); }, this.shutdownTimeoutMs);
|
|
602
|
+
return this.closeCompletion.promise;
|
|
603
|
+
}
|
|
604
|
+
ownedGroupAlive() {
|
|
605
|
+
if (this.child.pid === undefined)
|
|
606
|
+
return false;
|
|
607
|
+
try {
|
|
608
|
+
process.kill(-this.child.pid, 0);
|
|
609
|
+
return true;
|
|
610
|
+
}
|
|
611
|
+
catch (cause) {
|
|
612
|
+
return !object(cause) || cause.code !== 'ESRCH';
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
async signalOwnedTree(force) {
|
|
616
|
+
const pid = this.child.pid;
|
|
617
|
+
if (pid === undefined)
|
|
618
|
+
return false;
|
|
619
|
+
if (process.platform !== 'win32') {
|
|
620
|
+
try {
|
|
621
|
+
process.kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
|
|
622
|
+
return true;
|
|
623
|
+
}
|
|
624
|
+
catch (cause) {
|
|
625
|
+
if (object(cause) && cause.code === 'ESRCH')
|
|
626
|
+
return false;
|
|
627
|
+
throw cause;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
const root = process.env.SystemRoot ?? process.env.WINDIR;
|
|
631
|
+
if (!root)
|
|
632
|
+
throw new Error('Windows SystemRoot is required for owned-process-tree termination');
|
|
633
|
+
const executable = join(root, 'System32', 'taskkill.exe');
|
|
634
|
+
return new Promise((resolve, reject) => {
|
|
635
|
+
const killer = spawn(executable, ['/PID', String(pid), '/T', '/F'], { shell: false, stdio: 'ignore', windowsHide: true });
|
|
636
|
+
const timer = setTimeout(() => {
|
|
637
|
+
try {
|
|
638
|
+
killer.kill('SIGKILL');
|
|
639
|
+
}
|
|
640
|
+
catch (cause) {
|
|
641
|
+
reject(cause);
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
reject(new Error('Owned-process-tree termination command exceeded its deadline'));
|
|
645
|
+
}, 1000);
|
|
646
|
+
killer.once('error', cause => {
|
|
647
|
+
clearTimeout(timer);
|
|
648
|
+
reject(cause);
|
|
649
|
+
});
|
|
650
|
+
killer.once('close', code => {
|
|
651
|
+
clearTimeout(timer);
|
|
652
|
+
if (code === 0)
|
|
653
|
+
resolve(true);
|
|
654
|
+
else
|
|
655
|
+
reject(new Error(`Owned-process-tree termination command exited with code ${code}`));
|
|
656
|
+
});
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
async terminate() {
|
|
660
|
+
if (this.finished)
|
|
661
|
+
return;
|
|
662
|
+
clearTimeout(this.teardownTimer);
|
|
663
|
+
this.teardownTimer = undefined;
|
|
664
|
+
this.escalating = true;
|
|
665
|
+
this.cleanupError ??= new TransportError('ShutdownTimeout', 'Graceful sidecar cleanup exceeded its deadline; file and profile cleanup is uncertain', { stderr: this.stderr });
|
|
666
|
+
if (process.platform !== 'win32') {
|
|
667
|
+
try {
|
|
668
|
+
if (!await this.signalOwnedTree(false)) {
|
|
669
|
+
this.finishClose();
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
catch (cause) {
|
|
674
|
+
this.cleanupError = new TransportError('Terminate', 'Could not terminate the owned sidecar process group', { cause: new AggregateError([this.cleanupError, cause]), stderr: this.stderr });
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
this.teardownTimer = setTimeout(() => { void this.forceOwnedTree(); }, process.platform === 'win32' ? 0 : 1000);
|
|
678
|
+
}
|
|
679
|
+
async forceOwnedTree() {
|
|
680
|
+
if (this.finished)
|
|
681
|
+
return;
|
|
682
|
+
try {
|
|
683
|
+
const killed = await this.signalOwnedTree(true);
|
|
684
|
+
if (process.platform === 'win32' && killed)
|
|
685
|
+
this.windowsTreeTerminated = true;
|
|
686
|
+
if (killed)
|
|
687
|
+
this.cleanupError = new TransportError('ForcedKill', 'Owned sidecar process tree required forced termination; file and profile cleanup is uncertain', { cause: this.cleanupError, stderr: this.stderr });
|
|
688
|
+
}
|
|
689
|
+
catch (cause) {
|
|
690
|
+
this.cleanupError = new TransportError('ForcedKill', 'Could not force-kill the owned sidecar process tree; cleanup is uncertain', { cause: new AggregateError([this.cleanupError, cause]), stderr: this.stderr });
|
|
691
|
+
}
|
|
692
|
+
this.teardownTimer = setTimeout(() => this.finishClose(), 1000);
|
|
693
|
+
}
|
|
694
|
+
finishClose() {
|
|
695
|
+
if (this.finished)
|
|
696
|
+
return;
|
|
697
|
+
this.terminationConfirmed = process.platform === 'win32'
|
|
698
|
+
? this.child.pid === undefined || this.windowsTreeTerminated || (this.childClosed && this.exited && this.shutdownAcknowledged && this.cleanupError === undefined)
|
|
699
|
+
: !this.ownedGroupAlive();
|
|
700
|
+
this.finished = true;
|
|
701
|
+
clearTimeout(this.teardownTimer);
|
|
702
|
+
this.teardownTimer = undefined;
|
|
703
|
+
const stderr = this.stderr;
|
|
704
|
+
for (const entry of this.pending.values()) {
|
|
705
|
+
const error = new TransportError('Closed', 'Sidecar closed before native request completion; dispatch outcome is uncertain', { ...this.details(entry, stderr), cause: this.cleanupError ?? this.failure });
|
|
706
|
+
entry.reject?.(error);
|
|
707
|
+
entry.completion?.reject(error);
|
|
708
|
+
this.remove(entry);
|
|
709
|
+
}
|
|
710
|
+
this.frame = Buffer.alloc(0);
|
|
711
|
+
this.frameLength = 0;
|
|
712
|
+
this.child.stdout.off('data', this.onData);
|
|
713
|
+
this.child.stdout.off('end', this.onEnd);
|
|
714
|
+
this.child.stdout.off('error', this.onStreamError);
|
|
715
|
+
this.child.stderr.off('data', this.onStderr);
|
|
716
|
+
this.child.stderr.off('error', this.onStreamError);
|
|
717
|
+
this.child.stdin.off('error', this.onStreamError);
|
|
718
|
+
this.child.stdin.off('drain', this.onDrain);
|
|
719
|
+
this.child.off('error', this.onProcessError);
|
|
720
|
+
this.child.off('exit', this.onExit);
|
|
721
|
+
this.child.off('close', this.onClose);
|
|
722
|
+
this.child.stdin.destroy();
|
|
723
|
+
this.child.stdout.destroy();
|
|
724
|
+
this.child.stderr.destroy();
|
|
725
|
+
this.finalStderr = stderr;
|
|
726
|
+
this.stderrBytes = Buffer.alloc(0);
|
|
727
|
+
if (this.cleanupError) {
|
|
728
|
+
this.cleanupError.stderr = this.stderr;
|
|
729
|
+
this.closeCompletion?.reject(this.cleanupError);
|
|
730
|
+
this.closed.reject(this.cleanupError);
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
this.closeCompletion?.resolve();
|
|
734
|
+
this.closed.resolve();
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|