@myagentroam/marctl 0.11.3 → 0.11.5

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.
@@ -0,0 +1,179 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { gzipSync } from 'node:zlib';
4
+ import { MarctlError } from './errors.mjs';
5
+ import { DirectRejectedError } from './direct-errors.mjs';
6
+ import { runTerminalSession } from './terminal.mjs';
7
+ import { parseFrame } from './terminal-frame.mjs';
8
+ import { ByteChannel } from './scp-channel.mjs';
9
+
10
+ const script = gzipSync(readFileSync(new URL('./scp-worker.cjs', import.meta.url))).toString(
11
+ 'base64'
12
+ );
13
+ const expression = `eval(require('zlib').gunzipSync(Buffer.from('${script}','base64')).toString())`;
14
+
15
+ function workerArguments(mode, file, size, metadata, preserve, sourceBasename) {
16
+ const encoded = Buffer.from(file, 'utf8').toString('base64url');
17
+ return [
18
+ mode,
19
+ encoded,
20
+ ...(size === undefined
21
+ ? []
22
+ : [
23
+ String(size),
24
+ metadata.toString('base64url'),
25
+ preserve ? '1' : '0',
26
+ Buffer.from(sourceBasename, 'utf8').toString('base64url')
27
+ ])
28
+ ];
29
+ }
30
+
31
+ function workerCommand(mode, file, size, metadata, preserve, sourceBasename) {
32
+ return `node -e "${expression}" ${workerArguments(mode, file, size, metadata, preserve, sourceBasename).join(' ')}`;
33
+ }
34
+
35
+ async function withLocalWorker(
36
+ mode,
37
+ file,
38
+ size,
39
+ metadata,
40
+ preserve,
41
+ sourceBasename,
42
+ use,
43
+ controller
44
+ ) {
45
+ const child = spawn(
46
+ process.execPath,
47
+ ['-e', expression, ...workerArguments(mode, file, size, metadata, preserve, sourceBasename)],
48
+ {
49
+ stdio: ['pipe', 'pipe', 'pipe'],
50
+ windowsHide: true
51
+ }
52
+ );
53
+ child.stdin.on('error', () => undefined);
54
+ child.stderr.resume();
55
+ const channel = new ByteChannel(
56
+ (bytes) =>
57
+ new Promise((resolve, reject) => {
58
+ child.stdin.write(bytes, (error) => (error ? reject(error) : resolve()));
59
+ }),
60
+ controller
61
+ );
62
+ child.stdout.on('data', (bytes) => channel.feed(bytes));
63
+ child.once('error', (error) => channel.fail(error));
64
+ const closed = new Promise((resolve) => {
65
+ child.once('close', (code) => {
66
+ channel.finish(code ?? 1);
67
+ resolve();
68
+ });
69
+ });
70
+ try {
71
+ return await use(channel);
72
+ } finally {
73
+ if (child.exitCode === null) child.kill();
74
+ await closed;
75
+ }
76
+ }
77
+
78
+ async function withRemoteWorker(
79
+ {
80
+ client,
81
+ WebSocketClass,
82
+ nodeId,
83
+ file,
84
+ mode,
85
+ size,
86
+ metadata,
87
+ preserve,
88
+ sourceBasename,
89
+ translate,
90
+ controller
91
+ },
92
+ use
93
+ ) {
94
+ return runTerminalSession({
95
+ client,
96
+ WebSocketClass,
97
+ nodeId,
98
+ command: workerCommand(mode, file, size, metadata, preserve, sourceBasename),
99
+ binary: true,
100
+ raceConnections: true,
101
+ signal: controller.signal,
102
+ translate,
103
+ attached: async ({ transport, terminalId }) => {
104
+ const channel = new ByteChannel(
105
+ (bytes) =>
106
+ transport.send(
107
+ JSON.stringify({ type: 'input', terminalId, data: bytes.toString('base64') })
108
+ ),
109
+ controller
110
+ );
111
+ let sequence = 0;
112
+ const onMessage = (raw, isBinary) => {
113
+ try {
114
+ const frame = parseFrame(raw, isBinary, terminalId, translate);
115
+ if (frame.type === 'output') {
116
+ if (frame.sequence !== sequence + 1)
117
+ throw new MarctlError('Copy output sequence is invalid.');
118
+ sequence = frame.sequence;
119
+ const bytes = Buffer.from(frame.data, 'base64');
120
+ if (bytes.toString('base64') !== frame.data)
121
+ throw new MarctlError('Copy output is not valid base64.');
122
+ channel.feed(bytes);
123
+ } else if (frame.type === 'exit') channel.finish(frame.exitCode ?? 1);
124
+ else if (frame.type === 'error')
125
+ channel.fail(new MarctlError(translate('errors.terminalRemoteError')));
126
+ else throw new MarctlError(translate('errors.terminalUnexpectedFrame'));
127
+ } catch (error) {
128
+ channel.fail(error);
129
+ }
130
+ };
131
+ const onError = (error) =>
132
+ channel.connectionEnded(
133
+ error instanceof DirectRejectedError
134
+ ? new MarctlError(`${translate('errors.terminalConnectionFailed')} [${error.code}]`, {
135
+ code: error.code
136
+ })
137
+ : new MarctlError(translate('errors.terminalConnectionFailed'))
138
+ );
139
+ const onClose = () =>
140
+ channel.connectionEnded(new MarctlError(translate('errors.terminalConnectionLost')));
141
+ transport.on('message', onMessage);
142
+ transport.on('error', onError);
143
+ transport.on('close', onClose);
144
+ try {
145
+ transport.activate?.();
146
+ return await use(channel);
147
+ } finally {
148
+ transport.removeListener?.('message', onMessage);
149
+ transport.removeListener?.('error', onError);
150
+ transport.removeListener?.('close', onClose);
151
+ }
152
+ }
153
+ });
154
+ }
155
+
156
+ export async function withWorker(endpoint, mode, size, metadata, context, use) {
157
+ if (endpoint.nodeId === undefined)
158
+ return withLocalWorker(
159
+ mode,
160
+ endpoint.path,
161
+ size,
162
+ metadata,
163
+ context.preserve,
164
+ context.sourceBasename,
165
+ use,
166
+ context.controller
167
+ );
168
+ return withRemoteWorker(
169
+ {
170
+ ...context,
171
+ nodeId: endpoint.nodeId,
172
+ file: endpoint.path,
173
+ mode,
174
+ size,
175
+ metadata
176
+ },
177
+ use
178
+ );
179
+ }
package/src/scp.mjs CHANGED
@@ -1,336 +1,7 @@
1
- import { spawn } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
3
- import path from 'node:path';
4
- import { gzipSync } from 'node:zlib';
5
- import { MarctlError } from './config.mjs';
6
- import { parseFrame, runTerminalSession } from './terminal.mjs';
7
-
8
- const CHUNK = 32 * 1024;
9
- const WINDOW = 8;
10
- const MAX_BUFFERED_BYTES = WINDOW * (CHUNK + 4) + 64;
11
- const script = gzipSync(readFileSync(new URL('./scp-worker.cjs', import.meta.url))).toString(
12
- 'base64'
13
- );
14
- const expression = `eval(require('zlib').gunzipSync(Buffer.from('${script}','base64')).toString())`;
15
-
16
- export function parseScpEndpoint(value) {
17
- if (typeof value !== 'string' || !value || value.includes('\0'))
18
- throw new MarctlError('Invalid copy endpoint.');
19
- const explicit = value.indexOf('://');
20
- const separator = explicit >= 0 ? explicit : value.indexOf(':');
21
- if (separator < 0 || (separator === 1 && /^[A-Za-z]:[\\/]/u.test(value))) {
22
- // Let the filesystem resolve dot components and symlink parents.
23
- return { path: path.isAbsolute(value) ? value : `${process.cwd()}${path.sep}${value}` };
24
- }
25
- const host = value.slice(0, separator);
26
- const file = value.slice(separator + (explicit >= 0 ? 3 : 1));
27
- if (!host || !file || (!file.startsWith('/') && !/^[A-Za-z]:[\\/]/u.test(file)))
28
- throw new MarctlError('Invalid Node file path.');
29
- return { host, path: file };
30
- }
31
-
32
- export function scpSourceBasename(value) {
33
- const windowsPath = /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\');
34
- if (value.endsWith('/') || (windowsPath && value.endsWith('\\')))
35
- throw new MarctlError('Invalid source filename.');
36
- const sourcePath = windowsPath ? path.win32 : path.posix;
37
- const basename = sourcePath.basename(value);
38
- if (!basename || basename === '.' || basename === '..')
39
- throw new MarctlError('Invalid source filename.');
40
- return basename;
41
- }
42
-
43
- function workerArguments(mode, file, size, metadata, preserve, sourceBasename) {
44
- const encoded = Buffer.from(file, 'utf8').toString('base64url');
45
- return [
46
- mode,
47
- encoded,
48
- ...(size === undefined
49
- ? []
50
- : [
51
- String(size),
52
- metadata.toString('base64url'),
53
- preserve ? '1' : '0',
54
- Buffer.from(sourceBasename, 'utf8').toString('base64url')
55
- ])
56
- ];
57
- }
58
-
59
- function workerCommand(mode, file, size, metadata, preserve, sourceBasename) {
60
- return `node -e "${expression}" ${workerArguments(mode, file, size, metadata, preserve, sourceBasename).join(' ')}`;
61
- }
62
-
63
- class ByteChannel {
64
- #buffer = Buffer.alloc(0);
65
- #waiting = [];
66
- #sending = new Map();
67
- #ended;
68
- #failure;
69
- #controller;
70
-
71
- constructor(send, controller) {
72
- this.#controller = controller;
73
- const signal = controller.signal;
74
- this.send = (bytes) => {
75
- if (this.#failure) throw this.#failure;
76
- if (this.#ended !== undefined) throw new MarctlError('Copy stream ended unexpectedly.');
77
- return new Promise((resolve, reject) => {
78
- this.#sending.set(reject, resolve);
79
- const settle = (complete, value) => {
80
- this.#sending.delete(reject);
81
- complete(value);
82
- };
83
- try {
84
- Promise.resolve(send(bytes)).then(
85
- (value) => settle(resolve, value),
86
- (error) => settle(reject, error)
87
- );
88
- } catch (error) {
89
- settle(reject, error);
90
- }
91
- });
92
- };
93
- if (signal) {
94
- if (signal.aborted) this.fail(signal.reason);
95
- else
96
- signal.addEventListener('abort', () => this.fail(signal.reason), {
97
- once: true
98
- });
99
- }
100
- }
101
-
102
- feed(bytes) {
103
- if (this.#failure) return;
104
- this.#buffer = Buffer.concat([this.#buffer, bytes]);
105
- if (this.#buffer.length > MAX_BUFFERED_BYTES)
106
- return this.fail(new MarctlError('Copy output exceeded the bounded window.'));
107
- this.#wake();
108
- }
109
-
110
- finish(code) {
111
- this.#ended = code;
112
- if (code !== 0) return this.fail(new MarctlError('Remote copy command failed.'));
113
- // A successful exit confirms the worker consumed its final protocol input.
114
- for (const resolve of this.#sending.values()) resolve();
115
- this.#sending.clear();
116
- this.#wake();
117
- }
118
-
119
- connectionEnded(error) {
120
- if (this.#ended === undefined) this.fail(error);
121
- }
122
-
123
- fail(error) {
124
- if (this.#failure !== undefined) return;
125
- this.#failure = error;
126
- for (const reject of this.#sending.keys()) reject(this.#failure);
127
- this.#sending.clear();
128
- this.#wake();
129
- // Any endpoint failure must wake reads and writes across the entire copy.
130
- this.#controller.abort(error);
131
- }
132
-
133
- #wake() {
134
- for (const resolve of this.#waiting.splice(0)) resolve();
135
- }
136
-
137
- async read(length) {
138
- if (this.#failure) throw this.#failure;
139
- while (this.#buffer.length < length) {
140
- if (this.#failure) throw this.#failure;
141
- if (this.#ended !== undefined) throw new MarctlError('Copy stream ended unexpectedly.');
142
- await new Promise((resolve) => this.#waiting.push(resolve));
143
- }
144
- const bytes = this.#buffer.subarray(0, length);
145
- this.#buffer = this.#buffer.subarray(length);
146
- return bytes;
147
- }
148
-
149
- async done() {
150
- if (this.#failure) throw this.#failure;
151
- while (this.#ended === undefined && this.#failure === undefined)
152
- await new Promise((resolve) => this.#waiting.push(resolve));
153
- if (this.#failure) throw this.#failure;
154
- if (this.#ended !== 0) throw new MarctlError('Remote copy command failed.');
155
- }
156
- }
157
-
158
- async function copyBytes(source, destination) {
159
- const sizeBytes = await source.read(8);
160
- const size = sizeBytes.readBigUInt64BE();
161
- if (size > BigInt(Number.MAX_SAFE_INTEGER)) throw new MarctlError('Copy source is too large.');
162
- const metadata = await source.read(20);
163
- await destination.open(Number(size), metadata, async (target) => {
164
- if ((await target.read(1))[0] !== 1)
165
- throw new MarctlError('Copy target did not accept the file.');
166
- let remaining = Number(size);
167
- let acknowledged = Promise.resolve();
168
- const pending = [];
169
- for (;;) {
170
- const header = await source.read(4);
171
- const length = header.readUInt32BE();
172
- if (length > CHUNK || length > remaining)
173
- throw new MarctlError('Copy source sent an invalid chunk.');
174
- await target.send(header);
175
- if (length === 0) {
176
- await acknowledged;
177
- await target.send(await source.read(32));
178
- if (remaining !== 0 || (await target.read(1))[0] !== 2)
179
- throw new MarctlError('Copy target did not verify the file.');
180
- break;
181
- }
182
- await target.send(await source.read(length));
183
- // Keep one ordered ACK reader while sending up to a bounded window ahead.
184
- acknowledged = acknowledged.then(async () => {
185
- if ((await target.read(1))[0] !== 1)
186
- throw new MarctlError('Copy target rejected the chunk.');
187
- await source.send(Buffer.from([1]));
188
- });
189
- acknowledged.catch((error) => {
190
- // ACK failures use the same copy-wide cancellation as transport failures.
191
- source.fail(error);
192
- });
193
- pending.push(acknowledged);
194
- remaining -= length;
195
- if (pending.length >= WINDOW) await pending.shift();
196
- }
197
- await target.done();
198
- });
199
- await source.done();
200
- }
201
-
202
- async function withLocalWorker(
203
- mode,
204
- file,
205
- size,
206
- metadata,
207
- preserve,
208
- sourceBasename,
209
- use,
210
- controller
211
- ) {
212
- const child = spawn(
213
- process.execPath,
214
- ['-e', expression, ...workerArguments(mode, file, size, metadata, preserve, sourceBasename)],
215
- {
216
- stdio: ['pipe', 'pipe', 'pipe'],
217
- windowsHide: true
218
- }
219
- );
220
- child.stdin.on('error', () => undefined);
221
- child.stderr.resume();
222
- const channel = new ByteChannel(
223
- (bytes) =>
224
- new Promise((resolve, reject) => {
225
- child.stdin.write(bytes, (error) => (error ? reject(error) : resolve()));
226
- }),
227
- controller
228
- );
229
- child.stdout.on('data', (bytes) => channel.feed(bytes));
230
- child.once('error', (error) => channel.fail(error));
231
- child.once('close', (code) => channel.finish(code ?? 1));
232
- try {
233
- return await use(channel);
234
- } finally {
235
- if (child.exitCode === null) child.kill();
236
- }
237
- }
238
-
239
- async function withRemoteWorker(
240
- {
241
- client,
242
- WebSocketClass,
243
- nodeId,
244
- file,
245
- mode,
246
- size,
247
- metadata,
248
- preserve,
249
- sourceBasename,
250
- translate,
251
- controller
252
- },
253
- use
254
- ) {
255
- return runTerminalSession({
256
- client,
257
- WebSocketClass,
258
- nodeId,
259
- command: workerCommand(mode, file, size, metadata, preserve, sourceBasename),
260
- binary: true,
261
- raceConnections: true,
262
- translate,
263
- attached: async ({ transport, terminalId }) => {
264
- const channel = new ByteChannel(
265
- (bytes) =>
266
- transport.send(
267
- JSON.stringify({ type: 'input', terminalId, data: bytes.toString('base64') })
268
- ),
269
- controller
270
- );
271
- let sequence = 0;
272
- const onMessage = (raw, isBinary) => {
273
- try {
274
- const frame = parseFrame(raw, isBinary, terminalId, translate);
275
- if (frame.type === 'output') {
276
- if (frame.sequence !== sequence + 1)
277
- throw new MarctlError('Copy output sequence is invalid.');
278
- sequence = frame.sequence;
279
- const bytes = Buffer.from(frame.data, 'base64');
280
- if (bytes.toString('base64') !== frame.data)
281
- throw new MarctlError('Copy output is not valid base64.');
282
- channel.feed(bytes);
283
- } else if (frame.type === 'exit') channel.finish(frame.exitCode ?? 1);
284
- else if (frame.type === 'error')
285
- channel.fail(new MarctlError(translate('errors.terminalRemoteError')));
286
- else throw new MarctlError(translate('errors.terminalUnexpectedFrame'));
287
- } catch (error) {
288
- channel.fail(error);
289
- }
290
- };
291
- const onError = () =>
292
- channel.connectionEnded(new MarctlError(translate('errors.terminalConnectionFailed')));
293
- const onClose = () =>
294
- channel.connectionEnded(new MarctlError(translate('errors.terminalConnectionLost')));
295
- transport.on('message', onMessage);
296
- transport.on('error', onError);
297
- transport.on('close', onClose);
298
- try {
299
- transport.activate?.();
300
- return await use(channel);
301
- } finally {
302
- transport.removeListener?.('message', onMessage);
303
- transport.removeListener?.('error', onError);
304
- transport.removeListener?.('close', onClose);
305
- }
306
- }
307
- });
308
- }
309
-
310
- async function withWorker(endpoint, mode, size, metadata, context, use) {
311
- if (endpoint.nodeId === undefined)
312
- return withLocalWorker(
313
- mode,
314
- endpoint.path,
315
- size,
316
- metadata,
317
- context.preserve,
318
- context.sourceBasename,
319
- use,
320
- context.controller
321
- );
322
- return withRemoteWorker(
323
- {
324
- ...context,
325
- nodeId: endpoint.nodeId,
326
- file: endpoint.path,
327
- mode,
328
- size,
329
- metadata
330
- },
331
- use
332
- );
333
- }
1
+ import { MarctlError } from './errors.mjs';
2
+ import { parseScpEndpoint, scpSourceBasename } from './scp-endpoint.mjs';
3
+ import { copyBytes } from './scp-copy.mjs';
4
+ import { withWorker } from './scp-workers.mjs';
334
5
 
335
6
  export async function runScp({
336
7
  source,
@@ -340,23 +11,33 @@ export async function runScp({
340
11
  WebSocketClass,
341
12
  resolveNodeId,
342
13
  translate,
343
- signals = process
14
+ signal
344
15
  }) {
345
16
  const from = parseScpEndpoint(source);
346
17
  const to = parseScpEndpoint(destination);
347
18
  const sourceBasename = scpSourceBasename(from.path);
348
19
  if (!from.host && !to.host) throw new MarctlError('At least one copy endpoint must be a Node.');
349
20
  const references = [...new Set([from.host, to.host].filter(Boolean))];
350
- const ids = await Promise.all(references.map((host) => resolveNodeId(host)));
351
- const resolved = (endpoint) => ({
352
- path: endpoint.path,
353
- ...(endpoint.host ? { nodeId: ids[references.indexOf(endpoint.host)] } : {})
354
- });
355
21
  const controller = new AbortController();
356
- const interrupt = () => controller.abort(new MarctlError('Copy was interrupted.'));
357
- signals.on?.('SIGINT', interrupt);
358
- signals.on?.('SIGTERM', interrupt);
22
+ let rejectResolution;
23
+ const interrupt = () => {
24
+ controller.abort(new MarctlError('Copy was interrupted.'));
25
+ rejectResolution?.(controller.signal.reason);
26
+ };
27
+ signal?.addEventListener('abort', interrupt, { once: true });
28
+ if (signal?.aborted) interrupt();
359
29
  try {
30
+ controller.signal.throwIfAborted();
31
+ const ids = await new Promise((resolve, reject) => {
32
+ rejectResolution = reject;
33
+ Promise.all(references.map((host) => resolveNodeId(host))).then(resolve, reject);
34
+ });
35
+ rejectResolution = undefined;
36
+ controller.signal.throwIfAborted();
37
+ const resolved = (endpoint) => ({
38
+ path: endpoint.path,
39
+ ...(endpoint.host ? { nodeId: ids[references.indexOf(endpoint.host)] } : {})
40
+ });
360
41
  const context = {
361
42
  client,
362
43
  WebSocketClass,
@@ -371,12 +52,13 @@ export async function runScp({
371
52
  withWorker(resolved(to), 'write', size, metadata, context, use)
372
53
  })
373
54
  );
55
+ controller.signal.throwIfAborted();
374
56
  return 0;
375
57
  } catch (error) {
376
58
  controller.abort(error);
377
59
  throw error;
378
60
  } finally {
379
- signals.removeListener?.('SIGINT', interrupt);
380
- signals.removeListener?.('SIGTERM', interrupt);
61
+ rejectResolution = undefined;
62
+ signal?.removeEventListener('abort', interrupt);
381
63
  }
382
64
  }