@myagentroam/node 0.11.74 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/code-navigation/index.js +2 -0
  2. package/dist/code-navigation/languages/c-family.js +9 -0
  3. package/dist/code-navigation/languages/c-preprocessor.js +30 -0
  4. package/dist/code-navigation/languages/c.js +8 -0
  5. package/dist/code-navigation/languages/cpp.js +10 -0
  6. package/dist/code-navigation/languages/csharp.js +18 -0
  7. package/dist/code-navigation/languages/css.js +7 -0
  8. package/dist/code-navigation/languages/ecmascript.js +44 -0
  9. package/dist/code-navigation/languages/file-target.js +9 -0
  10. package/dist/code-navigation/languages/go.js +32 -0
  11. package/dist/code-navigation/languages/html.js +7 -0
  12. package/dist/code-navigation/languages/jvm.js +17 -0
  13. package/dist/code-navigation/languages/less.js +7 -0
  14. package/dist/code-navigation/languages/markdown.js +113 -0
  15. package/dist/code-navigation/languages/markup-reference.js +27 -0
  16. package/dist/code-navigation/languages/objective-c.js +11 -0
  17. package/dist/code-navigation/languages/objective-cpp.js +10 -0
  18. package/dist/code-navigation/languages/python.js +17 -0
  19. package/dist/code-navigation/languages/rust.js +18 -0
  20. package/dist/code-navigation/languages/sass.js +7 -0
  21. package/dist/code-navigation/languages/scss.js +7 -0
  22. package/dist/code-navigation/languages/stylesheet-reference.js +37 -0
  23. package/dist/code-navigation/languages/vue.js +75 -0
  24. package/dist/code-navigation/registry.js +72 -0
  25. package/dist/code-navigation/source-ranges.js +17 -0
  26. package/dist/code-navigation/symbol-maps.js +257 -0
  27. package/dist/code-navigation/symbol-matcher.js +48 -0
  28. package/dist/code-navigation/symbol-navigation.js +1 -0
  29. package/dist/code-navigation/types.js +1 -0
  30. package/dist/ctags-binary.js +3 -3
  31. package/dist/marctl/bin/marctl.mjs +6 -0
  32. package/dist/marctl/bin/marnodes.mjs +6 -0
  33. package/dist/marctl/bin/marscp.mjs +6 -0
  34. package/dist/marctl/bin/marssh.mjs +6 -0
  35. package/dist/marctl/package.json +1 -0
  36. package/dist/marctl/src/cli.mjs +271 -0
  37. package/dist/marctl/src/client.mjs +291 -0
  38. package/dist/marctl/src/config.mjs +46 -0
  39. package/dist/marctl/src/direct-control.mjs +225 -0
  40. package/dist/marctl/src/direct-errors.mjs +48 -0
  41. package/dist/marctl/src/direct-process.mjs +374 -0
  42. package/dist/marctl/src/direct-transport.mjs +235 -0
  43. package/dist/marctl/src/direct.mjs +421 -0
  44. package/dist/marctl/src/errors.mjs +11 -0
  45. package/dist/marctl/src/i18n/en-US.mjs +285 -0
  46. package/dist/marctl/src/i18n/index.mjs +20 -0
  47. package/dist/marctl/src/i18n/zh-CN.mjs +269 -0
  48. package/dist/marctl/src/scp-channel.mjs +99 -0
  49. package/dist/marctl/src/scp-copy.mjs +46 -0
  50. package/dist/marctl/src/scp-endpoint.mjs +29 -0
  51. package/dist/marctl/src/scp-protocol.mjs +2 -0
  52. package/dist/marctl/src/scp-worker.cjs +266 -0
  53. package/dist/marctl/src/scp-workers.mjs +179 -0
  54. package/dist/marctl/src/scp.mjs +64 -0
  55. package/dist/marctl/src/session-args.mjs +233 -0
  56. package/dist/marctl/src/session-input.mjs +43 -0
  57. package/dist/marctl/src/session-prepare.mjs +87 -0
  58. package/dist/marctl/src/session-target.mjs +26 -0
  59. package/dist/marctl/src/session-wait.mjs +232 -0
  60. package/dist/marctl/src/sessions.mjs +93 -0
  61. package/dist/marctl/src/terminal-frame.mjs +48 -0
  62. package/dist/marctl/src/terminal-interaction.mjs +177 -0
  63. package/dist/marctl/src/terminal-race.mjs +117 -0
  64. package/dist/marctl/src/terminal-relay-sender.mjs +129 -0
  65. package/dist/marctl/src/terminal-relay.mjs +305 -0
  66. package/dist/marctl/src/terminal.mjs +152 -0
  67. package/dist/marctl.js +1 -1
  68. package/dist/marnodes.js +1 -1
  69. package/dist/marscp.js +1 -1
  70. package/dist/marssh.js +1 -1
  71. package/dist/ripgrep-binary.js +3 -3
  72. package/dist/runner/mar-agent/agent-operation-presentation.js +22 -10
  73. package/dist/runner/mar-agent/hosted-conversation-runtime.js +3 -2
  74. package/dist/runner/mar-agent/runtime-extensions.js +33 -0
  75. package/dist/runner/mar-agent/session-runtime.js +5 -4
  76. package/dist/service/code-navigation/file-reference-parser.js +1 -1
  77. package/dist/service/node-terminal-channel.js +1 -1
  78. package/dist/session/native-session-projection-service.js +1 -2
  79. package/dist/session/session-catalog-service.js +74 -25
  80. package/dist/workspace/workspace-code-navigation-service.js +2 -2
  81. package/package.json +11 -9
  82. package/vendor/ctags/NOTICE +0 -22
  83. package/vendor/ctags/darwin-arm64/ctags +0 -0
  84. package/vendor/ctags/darwin-x64/ctags +0 -0
  85. package/vendor/ctags/licenses/COPYING +0 -340
  86. package/vendor/ctags/licenses/COPYING.MinGW-w64-runtime.txt +0 -240
  87. package/vendor/ctags/licenses/LICENSE.janssen +0 -19
  88. package/vendor/ctags/licenses/LICENSE.libyaml +0 -19
  89. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/COPYING +0 -340
  90. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/RECEIPT.yml +0 -27
  91. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/dependencies/libiconv.yml +0 -24
  92. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/dependencies/libjansson.yml +0 -19
  93. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/dependencies/libxml2.yml +0 -20
  94. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/dependencies/libyaml.yml +0 -7
  95. package/vendor/ctags/licenses/official-snapshot/darwin-arm64/dependencies/libz.yml +0 -13
  96. package/vendor/ctags/licenses/official-snapshot/darwin-x64/COPYING +0 -340
  97. package/vendor/ctags/licenses/official-snapshot/darwin-x64/RECEIPT.yml +0 -27
  98. package/vendor/ctags/licenses/official-snapshot/darwin-x64/dependencies/libiconv.yml +0 -24
  99. package/vendor/ctags/licenses/official-snapshot/darwin-x64/dependencies/libjansson.yml +0 -19
  100. package/vendor/ctags/licenses/official-snapshot/darwin-x64/dependencies/libxml2.yml +0 -20
  101. package/vendor/ctags/licenses/official-snapshot/darwin-x64/dependencies/libyaml.yml +0 -7
  102. package/vendor/ctags/licenses/official-snapshot/darwin-x64/dependencies/libz.yml +0 -13
  103. package/vendor/ctags/licenses/official-snapshot/linux-arm64/COPYING +0 -340
  104. package/vendor/ctags/licenses/official-snapshot/linux-arm64/RECEIPT.yml +0 -27
  105. package/vendor/ctags/licenses/official-snapshot/linux-arm64/dependencies/libiconv.yml +0 -24
  106. package/vendor/ctags/licenses/official-snapshot/linux-arm64/dependencies/libjansson.yml +0 -19
  107. package/vendor/ctags/licenses/official-snapshot/linux-arm64/dependencies/libxml2.yml +0 -20
  108. package/vendor/ctags/licenses/official-snapshot/linux-arm64/dependencies/libyaml.yml +0 -7
  109. package/vendor/ctags/licenses/official-snapshot/linux-arm64/dependencies/libz.yml +0 -13
  110. package/vendor/ctags/licenses/official-snapshot/linux-x64/COPYING +0 -340
  111. package/vendor/ctags/licenses/official-snapshot/linux-x64/RECEIPT.yml +0 -27
  112. package/vendor/ctags/licenses/official-snapshot/linux-x64/dependencies/libiconv.yml +0 -24
  113. package/vendor/ctags/licenses/official-snapshot/linux-x64/dependencies/libjansson.yml +0 -19
  114. package/vendor/ctags/licenses/official-snapshot/linux-x64/dependencies/libxml2.yml +0 -20
  115. package/vendor/ctags/licenses/official-snapshot/linux-x64/dependencies/libyaml.yml +0 -7
  116. package/vendor/ctags/licenses/official-snapshot/linux-x64/dependencies/libz.yml +0 -13
  117. package/vendor/ctags/licenses/win32-x64/COPYING +0 -340
  118. package/vendor/ctags/licenses/win32-x64/COPYING.MinGW-w64-runtime.txt +0 -240
  119. package/vendor/ctags/licenses/win32-x64/Copyright.libxml2 +0 -23
  120. package/vendor/ctags/licenses/win32-x64/LICENCE.pcre2 +0 -94
  121. package/vendor/ctags/licenses/win32-x64/LICENSE.janssen +0 -19
  122. package/vendor/ctags/licenses/win32-x64/LICENSE.libyaml +0 -19
  123. package/vendor/ctags/linux-arm64/ctags +0 -0
  124. package/vendor/ctags/linux-x64/ctags +0 -0
  125. package/vendor/ctags/manifest.json +0 -42
  126. package/vendor/ctags/source/universal-ctags-ab95af198f8eaeb6d50dc96e3adf52e769d3e5f0.tar.gz +0 -0
  127. package/vendor/ctags/win32-x64/ctags.exe +0 -0
  128. package/vendor/ripgrep/LICENSE-MIT +0 -21
  129. package/vendor/ripgrep/UNLICENSE +0 -24
  130. package/vendor/ripgrep/darwin-arm64/rg +0 -0
  131. package/vendor/ripgrep/darwin-x64/rg +0 -0
  132. package/vendor/ripgrep/linux-arm64/rg +0 -0
  133. package/vendor/ripgrep/linux-x64/rg +0 -0
  134. package/vendor/ripgrep/manifest.json +0 -42
  135. package/vendor/ripgrep/win32-arm64/rg.exe +0 -0
  136. package/vendor/ripgrep/win32-x64/rg.exe +0 -0
@@ -0,0 +1,46 @@
1
+ import { MarctlError } from './errors.mjs';
2
+ import { CHUNK, WINDOW } from './scp-protocol.mjs';
3
+
4
+ export async function copyBytes(source, destination) {
5
+ const sizeBytes = await source.read(8);
6
+ const size = sizeBytes.readBigUInt64BE();
7
+ if (size > BigInt(Number.MAX_SAFE_INTEGER)) throw new MarctlError('Copy source is too large.');
8
+ const metadata = await source.read(20);
9
+ await destination.open(Number(size), metadata, async (target) => {
10
+ if ((await target.read(1))[0] !== 1)
11
+ throw new MarctlError('Copy target did not accept the file.');
12
+ let remaining = Number(size);
13
+ let acknowledged = Promise.resolve();
14
+ const pending = [];
15
+ for (;;) {
16
+ const header = await source.read(4);
17
+ const length = header.readUInt32BE();
18
+ if (length > CHUNK || length > remaining)
19
+ throw new MarctlError('Copy source sent an invalid chunk.');
20
+ await target.send(header);
21
+ if (length === 0) {
22
+ await acknowledged;
23
+ await target.send(await source.read(32));
24
+ if (remaining !== 0 || (await target.read(1))[0] !== 2)
25
+ throw new MarctlError('Copy target did not verify the file.');
26
+ break;
27
+ }
28
+ await target.send(await source.read(length));
29
+ // Keep one ordered ACK reader while sending up to a bounded window ahead.
30
+ acknowledged = acknowledged.then(async () => {
31
+ if ((await target.read(1))[0] !== 1)
32
+ throw new MarctlError('Copy target rejected the chunk.');
33
+ await source.send(Buffer.from([1]));
34
+ });
35
+ acknowledged.catch((error) => {
36
+ // ACK failures use the same copy-wide cancellation as transport failures.
37
+ source.fail(error);
38
+ });
39
+ pending.push(acknowledged);
40
+ remaining -= length;
41
+ if (pending.length >= WINDOW) await pending.shift();
42
+ }
43
+ await target.done();
44
+ });
45
+ await source.done();
46
+ }
@@ -0,0 +1,29 @@
1
+ import path from 'node:path';
2
+ import { MarctlError } from './errors.mjs';
3
+
4
+ export function parseScpEndpoint(value) {
5
+ if (typeof value !== 'string' || !value || value.includes('\0'))
6
+ throw new MarctlError('Invalid copy endpoint.');
7
+ const explicit = value.indexOf('://');
8
+ const separator = explicit >= 0 ? explicit : value.indexOf(':');
9
+ if (separator < 0 || (separator === 1 && /^[A-Za-z]:[\\/]/u.test(value))) {
10
+ // Let the filesystem resolve dot components and symlink parents.
11
+ return { path: path.isAbsolute(value) ? value : `${process.cwd()}${path.sep}${value}` };
12
+ }
13
+ const host = value.slice(0, separator);
14
+ const file = value.slice(separator + (explicit >= 0 ? 3 : 1));
15
+ if (!host || !file || (!file.startsWith('/') && !/^[A-Za-z]:[\\/]/u.test(file)))
16
+ throw new MarctlError('Invalid Node file path.');
17
+ return { host, path: file };
18
+ }
19
+
20
+ export function scpSourceBasename(value) {
21
+ const windowsPath = /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\');
22
+ if (value.endsWith('/') || (windowsPath && value.endsWith('\\')))
23
+ throw new MarctlError('Invalid source filename.');
24
+ const sourcePath = windowsPath ? path.win32 : path.posix;
25
+ const basename = sourcePath.basename(value);
26
+ if (!basename || basename === '.' || basename === '..')
27
+ throw new MarctlError('Invalid source filename.');
28
+ return basename;
29
+ }
@@ -0,0 +1,2 @@
1
+ export const CHUNK = 32 * 1024;
2
+ export const WINDOW = 8;
@@ -0,0 +1,266 @@
1
+ const { createHash, randomUUID } = require('node:crypto');
2
+ const { constants } = require('node:fs');
3
+ const { link, lstat, open, rename, unlink } = require('node:fs/promises');
4
+ const path = require('node:path');
5
+
6
+ const CHUNK = 32 * 1024;
7
+ const WINDOW = 8;
8
+ const MAX_BUFFERED_BYTES = WINDOW * (CHUNK + 4) + 64;
9
+ const [mode, encodedPath, sizeArgument, encodedMetadata, preserveArgument, encodedSourceBasename] =
10
+ process.argv.slice(1);
11
+ const target = Buffer.from(encodedPath ?? '', 'base64url').toString('utf8');
12
+ const sourceBasename = Buffer.from(encodedSourceBasename ?? '', 'base64url').toString('utf8');
13
+ const input = process.stdin[Symbol.asyncIterator]();
14
+ let pending = Buffer.alloc(0);
15
+
16
+ async function readExact(length) {
17
+ while (pending.length < length) {
18
+ const next = await input.next();
19
+ if (next.done) throw new Error('SCP_STREAM_TRUNCATED');
20
+ pending = Buffer.concat([pending, next.value]);
21
+ if (pending.length > MAX_BUFFERED_BYTES) throw new Error('SCP_INPUT_OVERFLOW');
22
+ }
23
+ const data = pending.subarray(0, length);
24
+ pending = pending.subarray(length);
25
+ return data;
26
+ }
27
+
28
+ async function send(data) {
29
+ await new Promise((resolve, reject) => {
30
+ process.stdout.write(data, (error) => (error ? reject(error) : resolve()));
31
+ });
32
+ }
33
+
34
+ function frameLength(size) {
35
+ const buffer = Buffer.alloc(4);
36
+ buffer.writeUInt32BE(size);
37
+ return buffer;
38
+ }
39
+
40
+ function fileMetadata(stat) {
41
+ const bytes = Buffer.alloc(20);
42
+ bytes.writeUInt32BE(stat.mode & 0o777, 0);
43
+ bytes.writeDoubleBE(stat.atimeMs, 4);
44
+ bytes.writeDoubleBE(stat.mtimeMs, 12);
45
+ return bytes;
46
+ }
47
+
48
+ function appendFilename(directory, filename) {
49
+ const separator =
50
+ directory.endsWith(path.sep) || (process.platform === 'win32' && directory.endsWith('/'))
51
+ ? ''
52
+ : path.sep;
53
+ return `${directory}${separator}${filename}`;
54
+ }
55
+
56
+ async function destinationPath() {
57
+ const targetPath = process.platform === 'win32' ? path.win32 : path.posix;
58
+ const directoryIntent = (
59
+ process.platform === 'win32' ? /(?:^|[\\/])\.{0,2}$/u : /(?:^|\/)\.{0,2}$/u
60
+ ).test(target);
61
+ // A trailing slash or dot must not disguise the final directory symlink.
62
+ let inspected = target;
63
+ const trailingDirectorySyntax = process.platform === 'win32' ? /[\\/]+\.?$/u : /\/+\.?$/u;
64
+ for (;;) {
65
+ const trimmed = inspected.replace(trailingDirectorySyntax, '');
66
+ if (trimmed === inspected || trimmed.length < targetPath.parse(inspected).root.length) break;
67
+ inspected = trimmed;
68
+ }
69
+ let previous;
70
+ try {
71
+ previous = await lstat(inspected);
72
+ } catch (error) {
73
+ if (error.code !== 'ENOENT') throw error;
74
+ if (directoryIntent) throw new Error('SCP_TARGET_INVALID');
75
+ return target;
76
+ }
77
+ if (previous.isDirectory() && !previous.isSymbolicLink()) {
78
+ if (
79
+ !sourceBasename ||
80
+ sourceBasename === '.' ||
81
+ sourceBasename === '..' ||
82
+ sourceBasename.includes('\0') ||
83
+ targetPath.basename(sourceBasename) !== sourceBasename ||
84
+ (process.platform === 'win32' &&
85
+ // eslint-disable-next-line no-control-regex -- Reject control characters explicitly at the input boundary.
86
+ (/[<>:"/\\|?*\x00-\x1f]/u.test(sourceBasename) ||
87
+ /[. ]$/u.test(sourceBasename) ||
88
+ /^(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)/iu.test(sourceBasename)))
89
+ )
90
+ throw new Error('SCP_SOURCE_FILENAME_INVALID');
91
+ return appendFilename(target, sourceBasename);
92
+ }
93
+ if (directoryIntent) throw new Error('SCP_TARGET_INVALID');
94
+ return target;
95
+ }
96
+
97
+ async function source() {
98
+ const before = await lstat(target);
99
+ if (!before.isFile() || before.isSymbolicLink() || !Number.isSafeInteger(before.size))
100
+ throw new Error('SCP_SOURCE_INVALID');
101
+ const handle = await open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
102
+ try {
103
+ const current = await handle.stat();
104
+ if (
105
+ (before.dev !== current.dev && !(process.platform === 'win32' && before.dev === 0)) ||
106
+ before.ino !== current.ino ||
107
+ before.size !== current.size
108
+ )
109
+ throw new Error('SCP_SOURCE_CHANGED');
110
+ const size = Buffer.alloc(8);
111
+ size.writeBigUInt64BE(BigInt(current.size));
112
+ await send(size);
113
+ await send(fileMetadata(current));
114
+ const hash = createHash('sha256');
115
+ const buffer = Buffer.alloc(CHUNK);
116
+ let offset = 0;
117
+ let acknowledged = Promise.resolve();
118
+ const pendingAcks = [];
119
+ while (offset < current.size) {
120
+ const { bytesRead } = await handle.read(
121
+ buffer,
122
+ 0,
123
+ Math.min(CHUNK, current.size - offset),
124
+ offset
125
+ );
126
+ if (bytesRead === 0) throw new Error('SCP_SOURCE_CHANGED');
127
+ hash.update(buffer.subarray(0, bytesRead));
128
+ await send(Buffer.concat([frameLength(bytesRead), buffer.subarray(0, bytesRead)]));
129
+ // Serialize ACK reads without making each file read wait for a round trip.
130
+ acknowledged = acknowledged.then(async () => {
131
+ if ((await readExact(1))[0] !== 1) throw new Error('SCP_ACK_INVALID');
132
+ });
133
+ acknowledged.catch(() => undefined);
134
+ pendingAcks.push(acknowledged);
135
+ offset += bytesRead;
136
+ if (pendingAcks.length >= WINDOW) await pendingAcks.shift();
137
+ }
138
+ await acknowledged;
139
+ const after = await handle.stat();
140
+ if (
141
+ after.size !== current.size ||
142
+ after.mtimeMs !== current.mtimeMs ||
143
+ after.ctimeMs !== current.ctimeMs ||
144
+ after.ino !== current.ino
145
+ )
146
+ throw new Error('SCP_SOURCE_CHANGED');
147
+ await send(Buffer.concat([frameLength(0), hash.digest()]));
148
+ } finally {
149
+ await handle.close();
150
+ }
151
+ }
152
+
153
+ async function destination() {
154
+ const destinationTarget = await destinationPath();
155
+ const size = Number(sizeArgument);
156
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error('SCP_SIZE_INVALID');
157
+ const metadata = Buffer.from(encodedMetadata ?? '', 'base64url');
158
+ if (metadata.length !== 20) throw new Error('SCP_METADATA_INVALID');
159
+ const sourceMode = metadata.readUInt32BE(0);
160
+ const atimeMs = metadata.readDoubleBE(4);
161
+ const mtimeMs = metadata.readDoubleBE(12);
162
+ if (sourceMode > 0o777 || !Number.isFinite(atimeMs) || !Number.isFinite(mtimeMs))
163
+ throw new Error('SCP_METADATA_INVALID');
164
+ const filename = path.basename(destinationTarget);
165
+ const temporary = appendFilename(
166
+ path.dirname(destinationTarget),
167
+ `.${filename}.marctl-${randomUUID()}.tmp`
168
+ );
169
+ const handle = await open(temporary, 'wx', 0o600);
170
+ let published = false;
171
+ try {
172
+ let previous;
173
+ try {
174
+ previous = await lstat(destinationTarget);
175
+ if (!previous.isFile() || previous.isSymbolicLink()) throw new Error('SCP_TARGET_INVALID');
176
+ const existing = await open(
177
+ destinationTarget,
178
+ constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0)
179
+ );
180
+ try {
181
+ const accessible = await existing.stat();
182
+ if (
183
+ (!(process.platform === 'win32' && previous.dev === 0) &&
184
+ previous.dev !== accessible.dev) ||
185
+ previous.ino !== accessible.ino
186
+ )
187
+ throw new Error('SCP_TARGET_CHANGED');
188
+ } finally {
189
+ await existing.close();
190
+ }
191
+ } catch (error) {
192
+ if (error.code !== 'ENOENT') throw error;
193
+ }
194
+ await send(Buffer.from([1]));
195
+ const hash = createHash('sha256');
196
+ let received = 0;
197
+ for (;;) {
198
+ const length = (await readExact(4)).readUInt32BE();
199
+ if (length === 0) break;
200
+ if (length > CHUNK || received + length > size) throw new Error('SCP_SIZE_INVALID');
201
+ const bytes = await readExact(length);
202
+ hash.update(bytes);
203
+ let written = 0;
204
+ while (written < bytes.length) {
205
+ const result = await handle.write(
206
+ bytes,
207
+ written,
208
+ bytes.length - written,
209
+ received + written
210
+ );
211
+ written += result.bytesWritten;
212
+ }
213
+ received += length;
214
+ await send(Buffer.from([1]));
215
+ }
216
+ const expectedHash = await readExact(32);
217
+ if (received !== size || !hash.digest().equals(expectedHash))
218
+ throw new Error('SCP_CHECKSUM_MISMATCH');
219
+ if (preserveArgument === '1') await handle.utimes(new Date(atimeMs), new Date(mtimeMs));
220
+ await handle.chmod(
221
+ preserveArgument === '1'
222
+ ? sourceMode
223
+ : previous === undefined
224
+ ? sourceMode & ~process.umask()
225
+ : previous.mode & 0o777
226
+ );
227
+ await handle.sync();
228
+ await handle.close();
229
+ if (previous === undefined) {
230
+ await link(temporary, destinationTarget);
231
+ } else {
232
+ const current = await lstat(destinationTarget);
233
+ if (
234
+ !current.isFile() ||
235
+ current.isSymbolicLink() ||
236
+ previous.dev !== current.dev ||
237
+ previous.ino !== current.ino ||
238
+ previous.size !== current.size ||
239
+ previous.mtimeMs !== current.mtimeMs ||
240
+ previous.ctimeMs !== current.ctimeMs
241
+ )
242
+ throw new Error('SCP_TARGET_CHANGED');
243
+ await rename(temporary, destinationTarget);
244
+ }
245
+ published = true;
246
+ await send(Buffer.from([2]));
247
+ } finally {
248
+ await handle.close().catch(() => undefined);
249
+ await unlink(temporary).catch(() => undefined);
250
+ if (!published) process.exitCode = 1;
251
+ }
252
+ }
253
+
254
+ async function main() {
255
+ if (!path.isAbsolute(target) || target.includes('\0')) throw new Error('SCP_PATH_INVALID');
256
+ if (mode === 'read') await source();
257
+ else if (mode === 'write') await destination();
258
+ else throw new Error('SCP_MODE_INVALID');
259
+ }
260
+
261
+ void main()
262
+ .catch((error) => {
263
+ process.stderr.write(`${error instanceof Error ? error.message : 'SCP_FAILED'}\n`);
264
+ process.exitCode = 1;
265
+ })
266
+ .finally(() => process.stdin.destroy());
@@ -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
+ }
@@ -0,0 +1,64 @@
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';
5
+
6
+ export async function runScp({
7
+ source,
8
+ destination,
9
+ preserve = false,
10
+ client,
11
+ WebSocketClass,
12
+ resolveNodeId,
13
+ translate,
14
+ signal
15
+ }) {
16
+ const from = parseScpEndpoint(source);
17
+ const to = parseScpEndpoint(destination);
18
+ const sourceBasename = scpSourceBasename(from.path);
19
+ if (!from.host && !to.host) throw new MarctlError('At least one copy endpoint must be a Node.');
20
+ const references = [...new Set([from.host, to.host].filter(Boolean))];
21
+ const controller = new AbortController();
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();
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
+ });
41
+ const context = {
42
+ client,
43
+ WebSocketClass,
44
+ translate,
45
+ controller,
46
+ preserve,
47
+ sourceBasename
48
+ };
49
+ await withWorker(resolved(from), 'read', undefined, undefined, context, (channel) =>
50
+ copyBytes(channel, {
51
+ open: (size, metadata, use) =>
52
+ withWorker(resolved(to), 'write', size, metadata, context, use)
53
+ })
54
+ );
55
+ controller.signal.throwIfAborted();
56
+ return 0;
57
+ } catch (error) {
58
+ controller.abort(error);
59
+ throw error;
60
+ } finally {
61
+ rejectResolution = undefined;
62
+ signal?.removeEventListener('abort', interrupt);
63
+ }
64
+ }