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