@pyrokine/mcp-ssh 3.0.0 → 3.2.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.
@@ -0,0 +1,553 @@
1
+ import { spawn } from 'child_process';
2
+ import { createHash, randomBytes } from 'crypto';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import { PassThrough, Transform } from 'stream';
6
+ import { escapeShellArg, expandTilde } from './tools/utils.js';
7
+ import { validateConfigFile } from './security.js';
8
+ const CONFIG_OUTPUT_LIMIT = 512 * 1024;
9
+ const CONTROL_OUTPUT_LIMIT = 16 * 1024;
10
+ export class OpenSshError extends Error {
11
+ details;
12
+ constructor(message, details) {
13
+ super(message);
14
+ this.details = details;
15
+ this.name = 'OpenSshError';
16
+ }
17
+ }
18
+ function invalidConfig(message) {
19
+ throw new OpenSshError(message, { code: 'invalid_openssh_config', backend: 'openssh', retryable: false });
20
+ }
21
+ async function captureSsh(args, timeout, maxBytes, signal, track) {
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn('ssh', args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, signal });
24
+ track?.(child);
25
+ const stdout = [];
26
+ const stderr = [];
27
+ let bytes = 0;
28
+ let failure;
29
+ const timer = setTimeout(() => {
30
+ failure = new OpenSshError(`OpenSSH request timed out after ${timeout}ms`, {
31
+ code: 'openssh_timeout',
32
+ backend: 'openssh',
33
+ timeout,
34
+ operationStatus: 'unknown',
35
+ retryable: false,
36
+ });
37
+ child.kill('SIGKILL');
38
+ }, timeout);
39
+ const collect = (chunks) => (chunk) => {
40
+ bytes += chunk.length;
41
+ if (bytes > maxBytes) {
42
+ failure ??= new OpenSshError('OpenSSH response exceeded its output limit', {
43
+ code: 'openssh_output_limit',
44
+ backend: 'openssh',
45
+ maxBytes,
46
+ retryable: false,
47
+ });
48
+ child.kill('SIGKILL');
49
+ }
50
+ else {
51
+ chunks.push(chunk);
52
+ }
53
+ };
54
+ child.stdout.on('data', collect(stdout));
55
+ child.stderr.on('data', collect(stderr));
56
+ child.once('error', (error) => {
57
+ failure ??= error;
58
+ });
59
+ child.once('close', (status) => {
60
+ clearTimeout(timer);
61
+ if (failure) {
62
+ reject(failure);
63
+ }
64
+ else {
65
+ resolve({
66
+ stdout: Buffer.concat(stdout).toString('utf8'),
67
+ stderr: Buffer.concat(stderr).toString('utf8'),
68
+ status,
69
+ });
70
+ }
71
+ });
72
+ });
73
+ }
74
+ export async function resolveOpenSshConfig(input) {
75
+ if (process.platform === 'win32') {
76
+ throw new OpenSshError('The OpenSSH master backend requires a local POSIX platform', {
77
+ code: 'unsupported_backend',
78
+ backend: 'openssh',
79
+ capability: 'local_platform',
80
+ retryable: false,
81
+ });
82
+ }
83
+ const destination = input.configHost ?? input.host;
84
+ if (!destination || destination.startsWith('-') || /[\0\r\n]/.test(destination)) {
85
+ invalidConfig('An OpenSSH host or configHost is required');
86
+ }
87
+ const args = ['-G', '-T', '-o', 'BatchMode=yes', '-o', 'PermitLocalCommand=no'];
88
+ if (input.configPath) {
89
+ const configPath = path.resolve(expandTilde(input.configPath));
90
+ validateConfigFile(configPath);
91
+ args.push('-F', configPath);
92
+ }
93
+ if (input.configHost && input.host) {
94
+ args.push('-o', `HostName=${input.host}`);
95
+ }
96
+ if (input.username) {
97
+ args.push('-l', input.username);
98
+ }
99
+ if (input.port !== undefined) {
100
+ args.push('-p', String(input.port));
101
+ }
102
+ if (input.controlPath) {
103
+ args.push('-S', path.resolve(expandTilde(input.controlPath)));
104
+ }
105
+ args.push('--', destination);
106
+ const result = await captureSsh(args, input.readyTimeout ?? 30_000, CONFIG_OUTPUT_LIMIT);
107
+ if (result.status !== 0) {
108
+ invalidConfig(`OpenSSH configuration could not be resolved: ${result.stderr.trim()}`);
109
+ }
110
+ const config = new Map();
111
+ for (const line of result.stdout.split('\n')) {
112
+ const separator = line.indexOf(' ');
113
+ if (separator > 0 && !config.has(line.slice(0, separator))) {
114
+ config.set(line.slice(0, separator), line.slice(separator + 1));
115
+ }
116
+ }
117
+ const host = config.get('hostname') ?? '';
118
+ const username = config.get('user') ?? '';
119
+ const port = Number(config.get('port'));
120
+ const controlPath = config.get('controlpath');
121
+ if (!host || host.startsWith('-') || /[\s\0]/.test(host) || !username || /[\s:@\0]/.test(username)) {
122
+ invalidConfig('OpenSSH returned an invalid host or user');
123
+ }
124
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
125
+ invalidConfig('OpenSSH returned an invalid port');
126
+ }
127
+ if (!controlPath || controlPath === 'none' || /[\0\r\n]/.test(controlPath)) {
128
+ invalidConfig('OpenSSH requires an existing ControlPath; configure it or pass controlPath');
129
+ }
130
+ return { host, username, port, controlPath: path.resolve(expandTilde(controlPath)) };
131
+ }
132
+ class OpenSshChannel extends PassThrough {
133
+ stderr = new PassThrough();
134
+ ready;
135
+ child;
136
+ resolveReady;
137
+ rejectReady;
138
+ constructor(args, command, track) {
139
+ super({ emitClose: false });
140
+ this.ready = new Promise((resolve, reject) => {
141
+ this.resolveReady = resolve;
142
+ this.rejectReady = reject;
143
+ });
144
+ // 消费者可能在等待通道就绪前收到进程错误
145
+ void this.ready.catch(() => undefined);
146
+ const token = randomBytes(32).toString('hex');
147
+ const prefix = Buffer.from(`\x1eMCPSSH:${token}:`);
148
+ const script = `printf ${escapeShellArg(`\x1eMCPSSH:${token}:START\x1f`)} >&2; ` +
149
+ `sh -c ${escapeShellArg(command)}; status=$?; ` +
150
+ `printf ${escapeShellArg(`\x1eMCPSSH:${token}:END:%s\x1f`)} "$status" >&2; exit "$status"`;
151
+ this.child = spawn('ssh', [...args, script], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
152
+ track(this.child);
153
+ let pending = Buffer.alloc(0);
154
+ let remoteExitCode;
155
+ let started = false;
156
+ const resolveReady = this.resolveReady;
157
+ const markers = new Transform({
158
+ transform(chunk, _encoding, callback) {
159
+ pending = Buffer.concat([pending, chunk]);
160
+ while (pending.length > 0) {
161
+ const index = pending.indexOf(prefix);
162
+ if (index < 0) {
163
+ let retained = Math.min(pending.length, prefix.length - 1);
164
+ while (retained > 0 &&
165
+ !pending.subarray(pending.length - retained).equals(prefix.subarray(0, retained))) {
166
+ --retained;
167
+ }
168
+ const count = pending.length - retained;
169
+ this.push(pending.subarray(0, count));
170
+ pending = pending.subarray(count);
171
+ break;
172
+ }
173
+ if (index > 0) {
174
+ this.push(pending.subarray(0, index));
175
+ pending = pending.subarray(index);
176
+ }
177
+ const end = pending.indexOf(0x1f, prefix.length);
178
+ if (end < 0 && pending.length <= prefix.length + 16) {
179
+ break;
180
+ }
181
+ if (end < 0 || end > prefix.length + 16) {
182
+ this.push(pending.subarray(0, 1));
183
+ pending = pending.subarray(1);
184
+ continue;
185
+ }
186
+ const marker = pending.subarray(prefix.length, end).toString('ascii');
187
+ if (marker === 'START' && !started) {
188
+ started = true;
189
+ resolveReady();
190
+ }
191
+ else if (/^END:(?:0|[1-9]\d{0,2})$/.test(marker) && Number(marker.slice(4)) <= 255) {
192
+ remoteExitCode = Number(marker.slice(4));
193
+ }
194
+ else {
195
+ this.push(pending.subarray(0, end + 1));
196
+ }
197
+ pending = pending.subarray(end + 1);
198
+ }
199
+ callback();
200
+ },
201
+ flush(callback) {
202
+ this.push(pending);
203
+ pending = Buffer.alloc(0);
204
+ callback();
205
+ },
206
+ });
207
+ this.child.stdout.pipe(this, { end: false });
208
+ this.child.stderr.pipe(markers).pipe(this.stderr);
209
+ this.child.once('error', (error) => {
210
+ this.rejectReady(error);
211
+ if (!this.destroyed) {
212
+ this.emit('error', error);
213
+ }
214
+ });
215
+ this.child.once('close', (code, signal) => {
216
+ if (remoteExitCode === undefined) {
217
+ const error = new OpenSshError('OpenSSH channel ended without a remote exit status; remote state is unknown', {
218
+ code: 'openssh_transport_error',
219
+ backend: 'openssh',
220
+ operationStatus: 'unknown',
221
+ retryable: false,
222
+ exitCode: code,
223
+ signal,
224
+ });
225
+ this.rejectReady(error);
226
+ if (!this.destroyed) {
227
+ this.emit('error', error);
228
+ }
229
+ }
230
+ this.end();
231
+ this.emit('close', remoteExitCode ?? null, signal);
232
+ });
233
+ }
234
+ close() {
235
+ this.destroy();
236
+ }
237
+ _destroy(error, callback) {
238
+ this.rejectReady(error ?? new Error('OpenSSH channel was closed'));
239
+ this.child.kill('SIGKILL');
240
+ this.stderr.destroy();
241
+ callback(error);
242
+ }
243
+ }
244
+ export class OpenSshConnection {
245
+ config;
246
+ info;
247
+ processes = new Map();
248
+ socketIdentity;
249
+ closed = false;
250
+ constructor(config, socket, pid) {
251
+ this.config = config;
252
+ this.socketIdentity = `${socket.dev}:${socket.ino}`;
253
+ this.info = { backend: 'openssh', masterReused: true, identityStatus: 'master_trusted', masterPid: pid };
254
+ }
255
+ static async connect(config, signal) {
256
+ if (process.platform === 'win32' ||
257
+ config.remotePlatform === 'windows' ||
258
+ config.commandShell === 'cmd' ||
259
+ config.commandShell === 'powershell') {
260
+ throw new OpenSshError('The OpenSSH master backend supports local and remote POSIX platforms', {
261
+ code: 'unsupported_backend',
262
+ backend: 'openssh',
263
+ capability: 'platform',
264
+ retryable: false,
265
+ });
266
+ }
267
+ if (!config.controlPath) {
268
+ invalidConfig('OpenSSH requires a resolved controlPath');
269
+ }
270
+ const socket = this.socket(config.controlPath);
271
+ const args = this.arguments(config);
272
+ const timeout = config.readyTimeout ?? 30_000;
273
+ const checked = await captureSsh([...args.slice(0, -1), '-O', 'check', config.host], timeout, CONTROL_OUTPUT_LIMIT, signal);
274
+ const pid = Number(/Master running \(pid=(?<pid>\d+)\)/.exec(checked.stderr)?.[1]);
275
+ if (checked.status !== 0 || !Number.isSafeInteger(pid) || pid <= 0) {
276
+ throw new OpenSshError(`OpenSSH master is unavailable: ${checked.stderr.trim()}`, {
277
+ code: 'master_unavailable',
278
+ backend: 'openssh',
279
+ retryable: false,
280
+ });
281
+ }
282
+ const connection = new OpenSshConnection(config, socket, pid);
283
+ const abort = () => connection.close();
284
+ signal?.addEventListener('abort', abort, { once: true });
285
+ try {
286
+ if (signal?.aborted) {
287
+ throw signal.reason;
288
+ }
289
+ const marker = randomBytes(32).toString('hex');
290
+ const command = `printf ${escapeShellArg(`${marker}\\n`)}; id -u; id -un; printf '%s\\n' "$SSH_CONNECTION"`;
291
+ const observed = await captureSsh([...args, command], timeout, CONTROL_OUTPUT_LIMIT, signal, connection.trackProcess);
292
+ const start = observed.stdout.lastIndexOf(`${marker}\n`);
293
+ const lines = observed.stdout.slice(start + marker.length + 1).split('\n');
294
+ if (observed.status !== 0 || start < 0 || !/^\d+$/.test(lines[0]) || !lines[1]) {
295
+ throw new OpenSshError('The existing OpenSSH master did not provide its login identity', {
296
+ code: 'master_identity_unavailable',
297
+ backend: 'openssh',
298
+ retryable: false,
299
+ });
300
+ }
301
+ if (lines[1] !== config.username) {
302
+ throw new OpenSshError('The existing master login does not match the requested user', {
303
+ code: 'master_identity_mismatch',
304
+ backend: 'openssh',
305
+ requestedUser: config.username,
306
+ observedUser: lines[1],
307
+ retryable: false,
308
+ });
309
+ }
310
+ connection.info.observedLogin = {
311
+ uid: Number(lines[0]),
312
+ username: lines[1],
313
+ sshConnection: lines[2] || undefined,
314
+ };
315
+ connection.assertCurrent();
316
+ return connection;
317
+ }
318
+ catch (error) {
319
+ connection.close();
320
+ throw error;
321
+ }
322
+ finally {
323
+ signal?.removeEventListener('abort', abort);
324
+ }
325
+ }
326
+ static socket(controlPath) {
327
+ let socket;
328
+ try {
329
+ socket = fs.statSync(controlPath);
330
+ }
331
+ catch {
332
+ throw new OpenSshError('The existing OpenSSH control socket is unavailable', {
333
+ code: 'master_unavailable',
334
+ backend: 'openssh',
335
+ retryable: false,
336
+ });
337
+ }
338
+ if (!socket.isSocket() || socket.uid !== process.getuid?.()) {
339
+ throw new OpenSshError('ControlPath must refer to a socket owned by the current user', {
340
+ code: 'invalid_control_socket',
341
+ backend: 'openssh',
342
+ retryable: false,
343
+ });
344
+ }
345
+ return socket;
346
+ }
347
+ static arguments(config) {
348
+ return [
349
+ '-F',
350
+ '/dev/null',
351
+ '-S',
352
+ config.controlPath,
353
+ '-T',
354
+ '-o',
355
+ 'ControlMaster=no',
356
+ '-o',
357
+ 'BatchMode=yes',
358
+ '-o',
359
+ 'ProxyCommand=/bin/false',
360
+ '-o',
361
+ 'ProxyUseFdpass=no',
362
+ '-o',
363
+ 'PermitLocalCommand=no',
364
+ '-o',
365
+ 'ClearAllForwardings=yes',
366
+ '-p',
367
+ String(config.port),
368
+ '-l',
369
+ config.username,
370
+ config.host,
371
+ ];
372
+ }
373
+ arguments() {
374
+ this.assertCurrent();
375
+ return OpenSshConnection.arguments(this.config);
376
+ }
377
+ assertCurrent() {
378
+ const socket = OpenSshConnection.socket(this.config.controlPath);
379
+ if (this.closed || `${socket.dev}:${socket.ino}` !== this.socketIdentity) {
380
+ throw new OpenSshError('The OpenSSH master socket changed; reconnect the alias to bind it again', {
381
+ code: 'master_changed',
382
+ backend: 'openssh',
383
+ retryable: false,
384
+ });
385
+ }
386
+ }
387
+ isAlive() {
388
+ try {
389
+ this.assertCurrent();
390
+ process.kill(this.info.masterPid, 0);
391
+ return true;
392
+ }
393
+ catch {
394
+ return false;
395
+ }
396
+ }
397
+ trackProcess = (child, processGroup = false) => {
398
+ this.processes.set(child, processGroup);
399
+ child.once('close', () => this.processes.delete(child));
400
+ if (this.closed) {
401
+ this.close();
402
+ }
403
+ };
404
+ open(command) {
405
+ return new OpenSshChannel(this.arguments(), command, this.trackProcess);
406
+ }
407
+ consume(command, consume, timeout) {
408
+ const stream = this.open(command);
409
+ return new Promise((resolve, reject) => {
410
+ let settled = false;
411
+ let stderr = Buffer.alloc(0);
412
+ const finish = (error) => {
413
+ if (settled) {
414
+ return;
415
+ }
416
+ settled = true;
417
+ clearTimeout(timer);
418
+ if (error) {
419
+ stream.destroy();
420
+ reject(error);
421
+ }
422
+ else {
423
+ resolve();
424
+ }
425
+ };
426
+ const timer = setTimeout(() => finish(new OpenSshError(`OpenSSH command timed out after ${timeout}ms`, {
427
+ code: 'openssh_timeout',
428
+ backend: 'openssh',
429
+ operationStatus: 'unknown',
430
+ timeout,
431
+ retryable: false,
432
+ })), timeout);
433
+ stream.on('data', (chunk) => {
434
+ if (settled) {
435
+ return;
436
+ }
437
+ try {
438
+ consume(chunk);
439
+ }
440
+ catch (error) {
441
+ finish(error instanceof Error ? error : new Error(String(error)));
442
+ }
443
+ });
444
+ stream.stderr.on('data', (chunk) => {
445
+ stderr = Buffer.concat([stderr, chunk.subarray(0, Math.max(0, 4096 - stderr.length))]);
446
+ });
447
+ stream.on('error', finish);
448
+ stream.on('close', (code) => finish(code === 0
449
+ ? undefined
450
+ : new OpenSshError(`OpenSSH remote command failed: ${stderr.toString('utf8').trim() || `exit ${code}`}`, {
451
+ code: 'remote_command',
452
+ backend: 'openssh',
453
+ exitCode: code,
454
+ stderr: stderr.toString('utf8'),
455
+ retryable: false,
456
+ })));
457
+ });
458
+ }
459
+ async capture(command, timeout, maxBytes) {
460
+ const chunks = [];
461
+ let size = 0;
462
+ await this.consume(command, (chunk) => {
463
+ size += chunk.length;
464
+ if (size > maxBytes) {
465
+ throw new OpenSshError('OpenSSH command exceeded its output budget', {
466
+ code: 'openssh_output_limit',
467
+ backend: 'openssh',
468
+ maxBytes,
469
+ retryable: false,
470
+ });
471
+ }
472
+ chunks.push(chunk);
473
+ }, timeout);
474
+ return Buffer.concat(chunks);
475
+ }
476
+ async stat(remotePath, timeout, follow = true) {
477
+ const format = '%f\\0%s\\0%u\\0%g\\0%Y\\0%X\\0%d:%i:%s:%y:%z\\0';
478
+ const bytes = await this.capture(`LC_ALL=C stat ${follow ? '-L ' : ''}--printf=${escapeShellArg(format)} -- ${escapeShellArg(remotePath)}`, timeout, 4096);
479
+ const fields = bytes.toString('utf8').split('\0');
480
+ const values = [Number.parseInt(fields[0], 16), ...fields.slice(1, 6).map(Number)];
481
+ if (fields.length !== 8 || !values.every(Number.isSafeInteger) || values[1] < 0) {
482
+ throw new OpenSshError('OpenSSH stat returned invalid metadata', {
483
+ code: 'invalid_remote_metadata',
484
+ backend: 'openssh',
485
+ retryable: false,
486
+ });
487
+ }
488
+ return {
489
+ mode: values[0],
490
+ size: values[1],
491
+ uid: values[2],
492
+ gid: values[3],
493
+ mtime: values[4],
494
+ atime: values[5],
495
+ stamp: fields[6],
496
+ };
497
+ }
498
+ async hashFile(remotePath, algorithm, timeout, maxBytes, expectedSize) {
499
+ const deadline = Date.now() + timeout;
500
+ const remaining = () => {
501
+ const value = deadline - Date.now();
502
+ if (value <= 0) {
503
+ throw new OpenSshError('OpenSSH file verification exhausted its timeout', {
504
+ code: 'openssh_timeout',
505
+ backend: 'openssh',
506
+ operationStatus: 'unknown',
507
+ retryable: false,
508
+ });
509
+ }
510
+ return value;
511
+ };
512
+ const before = await this.stat(remotePath, remaining());
513
+ if ((before.mode & 0o170000) !== 0o100000) {
514
+ throw new Error('File hashing requires a regular remote file');
515
+ }
516
+ if ((maxBytes !== undefined && before.size > maxBytes) ||
517
+ (expectedSize !== undefined && before.size !== expectedSize)) {
518
+ throw new Error('Remote file size changed or exceeds the verification byte budget');
519
+ }
520
+ const hash = createHash(algorithm);
521
+ let size = 0;
522
+ await this.consume(`head -c ${before.size + 1} -- ${escapeShellArg(remotePath)}`, (chunk) => {
523
+ size += chunk.length;
524
+ if (size > before.size) {
525
+ throw new Error('Remote file grew during verification');
526
+ }
527
+ hash.update(chunk);
528
+ }, remaining());
529
+ const after = await this.stat(remotePath, remaining());
530
+ if (size !== before.size || before.stamp !== after.stamp) {
531
+ throw new Error('Remote file changed during verification');
532
+ }
533
+ return hash.digest('hex');
534
+ }
535
+ close() {
536
+ this.closed = true;
537
+ for (const [child, processGroup] of this.processes) {
538
+ if (processGroup && child.pid) {
539
+ try {
540
+ process.kill(-child.pid, 'SIGKILL');
541
+ }
542
+ catch (error) {
543
+ if (error.code !== 'ESRCH') {
544
+ console.error('OpenSSH process cleanup failed:', error);
545
+ }
546
+ }
547
+ }
548
+ else {
549
+ child.kill('SIGKILL');
550
+ }
551
+ }
552
+ }
553
+ }
@@ -1,5 +1,4 @@
1
- import type { ClientChannel } from 'ssh2';
2
- import type { OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions } from './types.js';
1
+ import type { CommandChannel, OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions } from './types.js';
3
2
  export declare const DEFAULT_OPERATION_MAX_OUTPUT_BYTES: number;
4
3
  export declare const HARD_OPERATION_MAX_OUTPUT_BYTES: number;
5
4
  export declare const DEFAULT_OPERATION_READ_BYTES: number;
@@ -13,7 +12,7 @@ export declare class OperationStartError extends Error {
13
12
  constructor(message: string, details: Record<string, unknown>);
14
13
  }
15
14
  export interface OperationDependencies {
16
- openStream(alias: string, command: string, marker: string, options: OperationStartOptions, adopt: (stream: ClientChannel) => void): Promise<void>;
15
+ openStream(alias: string, command: string, marker: string, options: OperationStartOptions, adopt: (stream: CommandChannel) => void): Promise<void>;
17
16
  cancelRemote(alias: string, pid: number, marker: string, processGroup: boolean, options: OperationStartOptions, processCreatedAt?: string): Promise<{
18
17
  success: boolean;
19
18
  error?: string;
@@ -154,11 +154,23 @@ export class OperationManager {
154
154
  ensureUtf8Boundary(record.stderr, stderrOffset, 'stderrOffset');
155
155
  const stdoutRequestedEnd = Math.min(record.stdout.length, stdoutOffset + maxReadBytes);
156
156
  const stdoutEnd = utf8SafeEnd(record.stdout, stdoutOffset, stdoutRequestedEnd, 'stdout');
157
+ if (record.finishedAt !== null &&
158
+ !record.stdoutTruncated &&
159
+ stdoutRequestedEnd === record.stdout.length &&
160
+ stdoutEnd < stdoutRequestedEnd) {
161
+ throw new Error('Operation output contains an incomplete UTF-8 sequence in stdout');
162
+ }
157
163
  const stdout = record.stdout.subarray(stdoutOffset, stdoutEnd);
158
164
  const nextStdoutOffset = record.stdoutTruncated && stdoutRequestedEnd === record.stdout.length ? stdoutRequestedEnd : stdoutEnd;
159
165
  const remaining = maxReadBytes - stdout.length;
160
166
  const stderrRequestedEnd = Math.min(record.stderr.length, stderrOffset + remaining);
161
- const stderrEnd = utf8SafeEnd(record.stderr, stderrOffset, stderrRequestedEnd, 'stderr');
167
+ const stderrEnd = utf8SafeEnd(record.stderr, stderrOffset, stderrRequestedEnd, 'stderr', stderrRequestedEnd < record.stderr.length, nextStdoutOffset > stdoutOffset);
168
+ if (record.finishedAt !== null &&
169
+ !record.stderrTruncated &&
170
+ stderrRequestedEnd === record.stderr.length &&
171
+ stderrEnd < stderrRequestedEnd) {
172
+ throw new Error('Operation output contains an incomplete UTF-8 sequence in stderr');
173
+ }
162
174
  const stderr = record.stderr.subarray(stderrOffset, stderrEnd);
163
175
  const nextStderrOffset = record.stderrTruncated && stderrRequestedEnd === record.stderr.length ? stderrRequestedEnd : stderrEnd;
164
176
  return {
@@ -272,7 +284,7 @@ export class OperationManager {
272
284
  this.finishStreamError(record, error);
273
285
  });
274
286
  stream.on('close', (code, signal) => {
275
- const close = { type: 'close', code, signal: signal ?? null };
287
+ const close = { type: 'close', code: code ?? null, signal: signal || null };
276
288
  if (record.cancelInFlight) {
277
289
  record.pendingTermination ??= close;
278
290
  return;
@@ -297,7 +309,14 @@ export class OperationManager {
297
309
  return;
298
310
  }
299
311
  this.flushMarkerBuffer(record);
300
- record.status = 'failed';
312
+ const details = 'details' in error ? error.details : undefined;
313
+ record.status =
314
+ details &&
315
+ typeof details === 'object' &&
316
+ 'operationStatus' in details &&
317
+ details.operationStatus === 'unknown'
318
+ ? 'unknown'
319
+ : 'failed';
301
320
  record.error = error.message;
302
321
  this.finish(record);
303
322
  }
@@ -311,6 +330,11 @@ export class OperationManager {
311
330
  if (record.cancelRequested) {
312
331
  record.status = 'cancelled';
313
332
  }
333
+ else if (code === null && signal === null) {
334
+ record.status = 'unknown';
335
+ record.error =
336
+ 'SSH channel closed without an exit status or signal; inspect the remote operation before repeating it';
337
+ }
314
338
  else if (!record.markerVerified) {
315
339
  record.status = 'failed';
316
340
  record.error ??= 'Remote operation exited before its marker was verified';
@@ -376,7 +400,9 @@ export class OperationManager {
376
400
  this.failMarker(record, 'Remote operation marker did not match the local operation');
377
401
  return;
378
402
  }
379
- const metadata = line.slice(expectedPrefix.length).match(/^([1-9]\d*):(0|1)(?::([1-9]\d*))?$/);
403
+ const metadata = line
404
+ .slice(expectedPrefix.length)
405
+ .match(/^(?<pid>[1-9]\d*):(?<processGroup>[01])(?::(?<createdAt>[1-9]\d*))?$/);
380
406
  const pid = metadata ? Number(metadata[1]) : Number.NaN;
381
407
  if (!metadata || !Number.isSafeInteger(pid)) {
382
408
  this.appendStderr(record, lineBytes);
@@ -415,7 +441,9 @@ export class OperationManager {
415
441
  const storedBytes = record.stdout.length + record.stderr.length;
416
442
  const available = Math.max(0, record.maxOutputBytes - storedBytes);
417
443
  const stored = data.subarray(0, available);
418
- record[stream] = Buffer.concat([record[stream], stored]);
444
+ if (stored.length > 0) {
445
+ record[stream] = Buffer.concat([record[stream], stored]);
446
+ }
419
447
  if (stored.length < data.length) {
420
448
  if (stream === 'stdout') {
421
449
  record.stdoutTruncated = true;
@@ -24,13 +24,14 @@ export declare class PtyManager {
24
24
  read(ptyId: string, options?: {
25
25
  mode?: 'screen' | 'raw';
26
26
  clear?: boolean;
27
- }): PtyReadResult;
27
+ }): Promise<PtyReadResult>;
28
28
  resize(ptyId: string, rows: number, cols: number): boolean;
29
29
  close(ptyId: string): PtyCloseResult;
30
30
  /** 关闭指定 alias 的所有 PTY 会话 */
31
31
  closeByAlias(alias: string): void;
32
32
  list(): PtySessionInfo[];
33
33
  private appendOutput;
34
+ private disposeParser;
34
35
  private appendRaw;
35
36
  private endDecoder;
36
37
  private normalizeBufferSize;