@pyrokine/mcp-ssh 2.3.2 → 2.4.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.
- package/README.md +141 -27
- package/README_zh.md +76 -27
- package/dist/command-risk.d.ts +7 -0
- package/dist/command-risk.js +106 -0
- package/dist/directory-verification.d.ts +43 -0
- package/dist/directory-verification.js +485 -0
- package/dist/file-ops.d.ts +77 -14
- package/dist/file-ops.js +839 -205
- package/dist/forward-manager.d.ts +22 -3
- package/dist/forward-manager.js +501 -85
- package/dist/index.js +2 -1
- package/dist/operation-manager.d.ts +64 -0
- package/dist/operation-manager.js +545 -0
- package/dist/pty-manager.d.ts +1 -0
- package/dist/pty-manager.js +11 -7
- package/dist/session-manager.d.ts +47 -11
- package/dist/session-manager.js +564 -114
- package/dist/tools/connection.js +58 -17
- package/dist/tools/exec.js +7 -66
- package/dist/tools/file.d.ts +1 -0
- package/dist/tools/file.js +575 -119
- package/dist/tools/forward.js +18 -8
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +1 -0
- package/dist/tools/operation.d.ts +2 -0
- package/dist/tools/operation.js +134 -0
- package/dist/tools/utils.d.ts +2 -2
- package/dist/transfer-outcome.d.ts +12 -0
- package/dist/transfer-outcome.js +72 -0
- package/dist/types.d.ts +95 -6
- package/package.json +10 -8
package/dist/index.js
CHANGED
|
@@ -17,12 +17,13 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
17
17
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
18
18
|
import { readFileSync } from 'node:fs';
|
|
19
19
|
import { sessionManager } from './session-manager.js';
|
|
20
|
-
import { registerConnectionTools, registerExecTools, registerFileTools, registerForwardTools, registerPtyTools, } from './tools/index.js';
|
|
20
|
+
import { registerConnectionTools, registerExecTools, registerFileTools, registerForwardTools, registerOperationTools, registerPtyTools, } from './tools/index.js';
|
|
21
21
|
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
|
|
22
22
|
const server = new McpServer({ name: 'mcp-ssh', version: pkg.version }, { capabilities: { tools: {} } });
|
|
23
23
|
registerConnectionTools(server);
|
|
24
24
|
registerExecTools(server);
|
|
25
25
|
registerFileTools(server);
|
|
26
|
+
registerOperationTools(server);
|
|
26
27
|
registerPtyTools(server);
|
|
27
28
|
registerForwardTools(server);
|
|
28
29
|
async function cleanup() {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ClientChannel } from 'ssh2';
|
|
2
|
+
import type { OperationCancelResult, OperationInfo, OperationReadResult, OperationStartOptions } from './types.js';
|
|
3
|
+
export declare const DEFAULT_OPERATION_MAX_OUTPUT_BYTES: number;
|
|
4
|
+
export declare const HARD_OPERATION_MAX_OUTPUT_BYTES: number;
|
|
5
|
+
export declare const DEFAULT_OPERATION_READ_BYTES: number;
|
|
6
|
+
export declare const HARD_OPERATION_READ_BYTES: number;
|
|
7
|
+
export declare const DEFAULT_OPERATION_RETENTION_MS: number;
|
|
8
|
+
export declare const MAX_OPERATION_RETENTION_MS: number;
|
|
9
|
+
export declare const DEFAULT_OPERATION_START_TIMEOUT_MS = 30000;
|
|
10
|
+
export declare const MAX_OPERATION_START_TIMEOUT_MS = 600000;
|
|
11
|
+
export declare class OperationStartError extends Error {
|
|
12
|
+
readonly details: Record<string, unknown>;
|
|
13
|
+
constructor(message: string, details: Record<string, unknown>);
|
|
14
|
+
}
|
|
15
|
+
export interface OperationDependencies {
|
|
16
|
+
openStream(alias: string, command: string, marker: string, options: OperationStartOptions, adopt: (stream: ClientChannel) => void): Promise<void>;
|
|
17
|
+
cancelRemote(alias: string, pid: number, marker: string, processGroup: boolean, options: OperationStartOptions): Promise<{
|
|
18
|
+
success: boolean;
|
|
19
|
+
error?: string;
|
|
20
|
+
}>;
|
|
21
|
+
}
|
|
22
|
+
export declare class OperationManager {
|
|
23
|
+
private readonly dependencies;
|
|
24
|
+
private readonly now;
|
|
25
|
+
private readonly operations;
|
|
26
|
+
private readonly pendingStarts;
|
|
27
|
+
private readonly sweeper;
|
|
28
|
+
constructor(dependencies: OperationDependencies, now?: () => number);
|
|
29
|
+
start(alias: string, command: string, options?: OperationStartOptions): Promise<OperationInfo>;
|
|
30
|
+
status(operationId: string): OperationInfo;
|
|
31
|
+
read(operationId: string, options?: {
|
|
32
|
+
stdoutOffset?: number;
|
|
33
|
+
stderrOffset?: number;
|
|
34
|
+
maxBytes?: number;
|
|
35
|
+
}): OperationReadResult;
|
|
36
|
+
cancel(operationId: string): Promise<OperationCancelResult>;
|
|
37
|
+
list(alias?: string): OperationInfo[];
|
|
38
|
+
markAliasDisconnected(alias: string): void;
|
|
39
|
+
sweepExpired(): void;
|
|
40
|
+
close(): void;
|
|
41
|
+
private attachStream;
|
|
42
|
+
private finishPendingTermination;
|
|
43
|
+
private finishStreamError;
|
|
44
|
+
private finishStreamClose;
|
|
45
|
+
private consumeMarker;
|
|
46
|
+
private failMarker;
|
|
47
|
+
private flushMarkerBuffer;
|
|
48
|
+
private appendStderr;
|
|
49
|
+
private appendOutput;
|
|
50
|
+
private finish;
|
|
51
|
+
private info;
|
|
52
|
+
private clearPendingStart;
|
|
53
|
+
private requireOperation;
|
|
54
|
+
private normalizeMaxOutputBytes;
|
|
55
|
+
private normalizeReadBytes;
|
|
56
|
+
private normalizeRetentionMs;
|
|
57
|
+
private normalizeStartTimeoutMs;
|
|
58
|
+
private normalizeOffset;
|
|
59
|
+
private ensureUtf8Boundary;
|
|
60
|
+
private utf8SafeEnd;
|
|
61
|
+
private trimIncompleteUtf8Sequence;
|
|
62
|
+
private utf8SequenceLength;
|
|
63
|
+
private isUtf8ContinuationByte;
|
|
64
|
+
}
|
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
export const DEFAULT_OPERATION_MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
3
|
+
export const HARD_OPERATION_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
|
4
|
+
export const DEFAULT_OPERATION_READ_BYTES = 64 * 1024;
|
|
5
|
+
export const HARD_OPERATION_READ_BYTES = 1024 * 1024;
|
|
6
|
+
export const DEFAULT_OPERATION_RETENTION_MS = 60 * 60_000;
|
|
7
|
+
export const MAX_OPERATION_RETENTION_MS = 24 * 60 * 60_000;
|
|
8
|
+
export const DEFAULT_OPERATION_START_TIMEOUT_MS = 30_000;
|
|
9
|
+
export const MAX_OPERATION_START_TIMEOUT_MS = 600_000;
|
|
10
|
+
export class OperationStartError extends Error {
|
|
11
|
+
details;
|
|
12
|
+
constructor(message, details) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.details = details;
|
|
15
|
+
this.name = 'OperationStartError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const MARKER_PREFIX = '__MCP_SSH_OPERATION__';
|
|
19
|
+
const MARKER_LINE_LIMIT = 512;
|
|
20
|
+
export class OperationManager {
|
|
21
|
+
dependencies;
|
|
22
|
+
now;
|
|
23
|
+
operations = new Map();
|
|
24
|
+
pendingStarts = new Map();
|
|
25
|
+
sweeper;
|
|
26
|
+
constructor(dependencies, now = Date.now) {
|
|
27
|
+
this.dependencies = dependencies;
|
|
28
|
+
this.now = now;
|
|
29
|
+
this.sweeper = setInterval(() => this.sweepExpired(), 60_000);
|
|
30
|
+
this.sweeper.unref?.();
|
|
31
|
+
}
|
|
32
|
+
async start(alias, command, options = {}) {
|
|
33
|
+
const pendingOperationId = this.pendingStarts.get(alias);
|
|
34
|
+
if (pendingOperationId) {
|
|
35
|
+
throw new OperationStartError(`Alias '${alias}' already has an operation start awaiting SSH channel setup`, {
|
|
36
|
+
alias,
|
|
37
|
+
operationId: pendingOperationId,
|
|
38
|
+
retryable: true,
|
|
39
|
+
suggestion: '等待当前 operation start 完成,或断开该 alias 以释放未完成的 SSH channel request',
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const operationId = `op_${randomUUID()}`;
|
|
43
|
+
const marker = randomBytes(32).toString('hex');
|
|
44
|
+
const maxOutputBytes = this.normalizeMaxOutputBytes(options.maxOutputBytes);
|
|
45
|
+
const retentionMs = this.normalizeRetentionMs(options.retentionMs);
|
|
46
|
+
const startTimeoutMs = this.normalizeStartTimeoutMs(options.startTimeoutMs);
|
|
47
|
+
const record = {
|
|
48
|
+
operationId,
|
|
49
|
+
alias,
|
|
50
|
+
command,
|
|
51
|
+
marker,
|
|
52
|
+
status: 'starting',
|
|
53
|
+
pid: null,
|
|
54
|
+
processGroup: false,
|
|
55
|
+
markerVerified: false,
|
|
56
|
+
cancelRequested: false,
|
|
57
|
+
cancelInFlight: false,
|
|
58
|
+
pendingTermination: null,
|
|
59
|
+
startedAt: this.now(),
|
|
60
|
+
finishedAt: null,
|
|
61
|
+
expiresAt: null,
|
|
62
|
+
retentionMs,
|
|
63
|
+
exitCode: null,
|
|
64
|
+
signal: null,
|
|
65
|
+
stdout: Buffer.alloc(0),
|
|
66
|
+
stderr: Buffer.alloc(0),
|
|
67
|
+
stdoutBytes: 0,
|
|
68
|
+
stderrBytes: 0,
|
|
69
|
+
stdoutTruncated: false,
|
|
70
|
+
stderrTruncated: false,
|
|
71
|
+
maxOutputBytes,
|
|
72
|
+
markerBuffer: Buffer.alloc(0),
|
|
73
|
+
options: { ...options, maxOutputBytes, retentionMs, startTimeoutMs },
|
|
74
|
+
};
|
|
75
|
+
this.operations.set(operationId, record);
|
|
76
|
+
this.pendingStarts.set(alias, operationId);
|
|
77
|
+
const opening = this.dependencies.openStream(alias, command, marker, record.options, (stream) => {
|
|
78
|
+
if (record.stream) {
|
|
79
|
+
stream.destroy();
|
|
80
|
+
throw new Error('Operation stream was adopted more than once');
|
|
81
|
+
}
|
|
82
|
+
if (record.finishedAt !== null) {
|
|
83
|
+
stream.destroy();
|
|
84
|
+
throw new Error('Operation stream arrived after operation start finished');
|
|
85
|
+
}
|
|
86
|
+
record.stream = stream;
|
|
87
|
+
this.attachStream(record, stream);
|
|
88
|
+
});
|
|
89
|
+
void opening.then(() => this.clearPendingStart(alias, operationId), () => this.clearPendingStart(alias, operationId));
|
|
90
|
+
let timer;
|
|
91
|
+
try {
|
|
92
|
+
await Promise.race([
|
|
93
|
+
opening,
|
|
94
|
+
new Promise((_resolve, reject) => {
|
|
95
|
+
timer = setTimeout(() => {
|
|
96
|
+
reject(new OperationStartError(`Operation start timed out after ${startTimeoutMs}ms`, {
|
|
97
|
+
alias,
|
|
98
|
+
operationId,
|
|
99
|
+
startTimeoutMs,
|
|
100
|
+
status: 'unknown',
|
|
101
|
+
retryable: false,
|
|
102
|
+
suggestion: 'SSH channel request 状态无法确认;使用 ssh_operation_status 查询记录,必要时 ssh_disconnect 释放底层 pending channel',
|
|
103
|
+
}));
|
|
104
|
+
}, startTimeoutMs);
|
|
105
|
+
}),
|
|
106
|
+
]);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (record.finishedAt === null) {
|
|
110
|
+
record.status = error instanceof OperationStartError ? 'unknown' : 'failed';
|
|
111
|
+
record.error = error instanceof Error ? error.message : String(error);
|
|
112
|
+
this.finish(record);
|
|
113
|
+
}
|
|
114
|
+
record.stream?.destroy();
|
|
115
|
+
if (error instanceof OperationStartError) {
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
throw new OperationStartError(record.error ?? 'Operation start failed', {
|
|
119
|
+
alias,
|
|
120
|
+
operationId,
|
|
121
|
+
status: record.status,
|
|
122
|
+
retryable: false,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
if (timer) {
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (!record.stream) {
|
|
131
|
+
record.status = 'failed';
|
|
132
|
+
record.error = 'Operation stream was not adopted';
|
|
133
|
+
this.finish(record);
|
|
134
|
+
throw new OperationStartError(record.error, {
|
|
135
|
+
alias,
|
|
136
|
+
operationId,
|
|
137
|
+
status: record.status,
|
|
138
|
+
retryable: false,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return this.info(record);
|
|
142
|
+
}
|
|
143
|
+
status(operationId) {
|
|
144
|
+
return this.info(this.requireOperation(operationId));
|
|
145
|
+
}
|
|
146
|
+
read(operationId, options = {}) {
|
|
147
|
+
const record = this.requireOperation(operationId);
|
|
148
|
+
const maxReadBytes = this.normalizeReadBytes(options.maxBytes);
|
|
149
|
+
const stdoutOffset = this.normalizeOffset(options.stdoutOffset, record.stdout.length, 'stdoutOffset');
|
|
150
|
+
const stderrOffset = this.normalizeOffset(options.stderrOffset, record.stderr.length, 'stderrOffset');
|
|
151
|
+
this.ensureUtf8Boundary(record.stdout, stdoutOffset, 'stdoutOffset');
|
|
152
|
+
this.ensureUtf8Boundary(record.stderr, stderrOffset, 'stderrOffset');
|
|
153
|
+
const stdoutEnd = this.utf8SafeEnd(record.stdout, stdoutOffset, Math.min(record.stdout.length, stdoutOffset + maxReadBytes), 'stdout');
|
|
154
|
+
const stdout = record.stdout.subarray(stdoutOffset, stdoutEnd);
|
|
155
|
+
const remaining = maxReadBytes - stdout.length;
|
|
156
|
+
const stderrEnd = this.utf8SafeEnd(record.stderr, stderrOffset, Math.min(record.stderr.length, stderrOffset + remaining), 'stderr');
|
|
157
|
+
const stderr = record.stderr.subarray(stderrOffset, stderrEnd);
|
|
158
|
+
return {
|
|
159
|
+
...this.info(record),
|
|
160
|
+
stdout: stdout.toString('utf8'),
|
|
161
|
+
stderr: stderr.toString('utf8'),
|
|
162
|
+
stdoutOffset,
|
|
163
|
+
stderrOffset,
|
|
164
|
+
nextStdoutOffset: stdoutEnd,
|
|
165
|
+
nextStderrOffset: stderrEnd,
|
|
166
|
+
readBytes: stdout.length + stderr.length,
|
|
167
|
+
maxReadBytes,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
async cancel(operationId) {
|
|
171
|
+
const record = this.requireOperation(operationId);
|
|
172
|
+
if (record.status !== 'starting' && record.status !== 'running') {
|
|
173
|
+
return {
|
|
174
|
+
...this.info(record),
|
|
175
|
+
success: false,
|
|
176
|
+
cancelRequested: record.cancelRequested,
|
|
177
|
+
retryable: false,
|
|
178
|
+
verificationError: `Operation is ${record.status}`,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
if (!record.markerVerified || record.pid === null) {
|
|
182
|
+
return {
|
|
183
|
+
...this.info(record),
|
|
184
|
+
success: false,
|
|
185
|
+
cancelRequested: false,
|
|
186
|
+
retryable: true,
|
|
187
|
+
verificationError: 'Remote operation marker has not been verified',
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if (record.cancelInFlight) {
|
|
191
|
+
return {
|
|
192
|
+
...this.info(record),
|
|
193
|
+
success: false,
|
|
194
|
+
cancelRequested: record.cancelRequested,
|
|
195
|
+
retryable: true,
|
|
196
|
+
verificationError: 'Remote cancellation is already in progress',
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
record.cancelInFlight = true;
|
|
200
|
+
let result;
|
|
201
|
+
try {
|
|
202
|
+
result = await this.dependencies.cancelRemote(record.alias, record.pid, record.marker, record.processGroup, record.options);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
record.cancelInFlight = false;
|
|
206
|
+
this.finishPendingTermination(record);
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
record.cancelInFlight = false;
|
|
210
|
+
if (result.success) {
|
|
211
|
+
record.cancelRequested = true;
|
|
212
|
+
}
|
|
213
|
+
this.finishPendingTermination(record);
|
|
214
|
+
return {
|
|
215
|
+
...this.info(record),
|
|
216
|
+
success: result.success,
|
|
217
|
+
cancelRequested: record.cancelRequested,
|
|
218
|
+
retryable: !result.success,
|
|
219
|
+
...(result.error ? { verificationError: result.error } : {}),
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
list(alias) {
|
|
223
|
+
this.sweepExpired();
|
|
224
|
+
return Array.from(this.operations.values())
|
|
225
|
+
.filter((record) => alias === undefined || record.alias === alias)
|
|
226
|
+
.map((record) => this.info(record));
|
|
227
|
+
}
|
|
228
|
+
markAliasDisconnected(alias) {
|
|
229
|
+
this.pendingStarts.delete(alias);
|
|
230
|
+
for (const record of this.operations.values()) {
|
|
231
|
+
if (record.alias === alias && (record.status === 'starting' || record.status === 'running')) {
|
|
232
|
+
record.status = 'unknown';
|
|
233
|
+
record.error = 'SSH session disconnected before remote process state could be confirmed';
|
|
234
|
+
this.finish(record);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
sweepExpired() {
|
|
239
|
+
const now = this.now();
|
|
240
|
+
for (const [operationId, record] of this.operations) {
|
|
241
|
+
if (record.expiresAt !== null && record.expiresAt <= now) {
|
|
242
|
+
this.operations.delete(operationId);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
close() {
|
|
247
|
+
clearInterval(this.sweeper);
|
|
248
|
+
}
|
|
249
|
+
attachStream(record, stream) {
|
|
250
|
+
stream.on('data', (data) => {
|
|
251
|
+
record.stdoutBytes += data.length;
|
|
252
|
+
this.appendOutput(record, 'stdout', data);
|
|
253
|
+
});
|
|
254
|
+
stream.stderr.on('data', (data) => {
|
|
255
|
+
this.consumeMarker(record, data);
|
|
256
|
+
});
|
|
257
|
+
stream.on('error', (error) => {
|
|
258
|
+
if (record.cancelInFlight) {
|
|
259
|
+
record.pendingTermination ??= { type: 'error', error };
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
this.finishStreamError(record, error);
|
|
263
|
+
});
|
|
264
|
+
stream.on('close', (code, signal) => {
|
|
265
|
+
const close = { type: 'close', code, signal: signal ?? null };
|
|
266
|
+
if (record.cancelInFlight) {
|
|
267
|
+
record.pendingTermination ??= close;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
this.finishStreamClose(record, close.code, close.signal);
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
finishPendingTermination(record) {
|
|
274
|
+
const pending = record.pendingTermination;
|
|
275
|
+
record.pendingTermination = null;
|
|
276
|
+
if (!pending) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (pending.type === 'error') {
|
|
280
|
+
this.finishStreamError(record, pending.error);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
this.finishStreamClose(record, pending.code, pending.signal);
|
|
284
|
+
}
|
|
285
|
+
finishStreamError(record, error) {
|
|
286
|
+
if (record.status === 'unknown' || record.finishedAt !== null) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
this.flushMarkerBuffer(record);
|
|
290
|
+
record.status = 'failed';
|
|
291
|
+
record.error = error.message;
|
|
292
|
+
this.finish(record);
|
|
293
|
+
}
|
|
294
|
+
finishStreamClose(record, code, signal) {
|
|
295
|
+
if (record.status === 'unknown' || record.finishedAt !== null) {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
record.exitCode = code;
|
|
299
|
+
record.signal = signal;
|
|
300
|
+
this.flushMarkerBuffer(record);
|
|
301
|
+
if (record.cancelRequested) {
|
|
302
|
+
record.status = 'cancelled';
|
|
303
|
+
}
|
|
304
|
+
else if (!record.markerVerified) {
|
|
305
|
+
record.status = 'failed';
|
|
306
|
+
record.error ??= 'Remote operation exited before its marker was verified';
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
record.status = code === 0 ? 'completed' : 'failed';
|
|
310
|
+
}
|
|
311
|
+
this.finish(record);
|
|
312
|
+
}
|
|
313
|
+
consumeMarker(record, data) {
|
|
314
|
+
if (record.markerVerified || record.status !== 'starting') {
|
|
315
|
+
this.appendStderr(record, data);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const markerPrefix = Buffer.from(MARKER_PREFIX);
|
|
319
|
+
record.markerBuffer = Buffer.concat([record.markerBuffer, data]);
|
|
320
|
+
while (!record.markerVerified) {
|
|
321
|
+
const markerIndex = record.markerBuffer.indexOf(markerPrefix);
|
|
322
|
+
if (markerIndex > 0) {
|
|
323
|
+
this.appendStderr(record, record.markerBuffer.subarray(0, markerIndex));
|
|
324
|
+
record.markerBuffer = record.markerBuffer.subarray(markerIndex);
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (markerIndex < 0) {
|
|
328
|
+
const newline = record.markerBuffer.indexOf(0x0a);
|
|
329
|
+
if (newline >= 0) {
|
|
330
|
+
this.appendStderr(record, record.markerBuffer.subarray(0, newline + 1));
|
|
331
|
+
record.markerBuffer = record.markerBuffer.subarray(newline + 1);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
const retainedBytes = Math.min(record.markerBuffer.length, markerPrefix.length - 1);
|
|
335
|
+
const streamedBytes = record.markerBuffer.length - retainedBytes;
|
|
336
|
+
if (streamedBytes > 0) {
|
|
337
|
+
this.appendStderr(record, record.markerBuffer.subarray(0, streamedBytes));
|
|
338
|
+
record.markerBuffer = record.markerBuffer.subarray(streamedBytes);
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const newline = record.markerBuffer.indexOf(0x0a);
|
|
343
|
+
if (newline < 0) {
|
|
344
|
+
if (record.markerBuffer.length > MARKER_LINE_LIMIT) {
|
|
345
|
+
this.appendStderr(record, record.markerBuffer);
|
|
346
|
+
record.markerBuffer = Buffer.alloc(0);
|
|
347
|
+
this.failMarker(record, 'Remote operation marker exceeded the allowed length');
|
|
348
|
+
}
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
const lineBytes = record.markerBuffer.subarray(0, newline + 1);
|
|
352
|
+
const line = record.markerBuffer.subarray(0, newline).toString('utf8').trim();
|
|
353
|
+
record.markerBuffer = record.markerBuffer.subarray(newline + 1);
|
|
354
|
+
if (newline > MARKER_LINE_LIMIT) {
|
|
355
|
+
this.appendStderr(record, lineBytes);
|
|
356
|
+
this.appendStderr(record, record.markerBuffer);
|
|
357
|
+
record.markerBuffer = Buffer.alloc(0);
|
|
358
|
+
this.failMarker(record, 'Remote operation marker exceeded the allowed length');
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const expectedPrefix = `${MARKER_PREFIX}:${record.marker}:`;
|
|
362
|
+
if (!line.startsWith(expectedPrefix)) {
|
|
363
|
+
this.appendStderr(record, lineBytes);
|
|
364
|
+
this.appendStderr(record, record.markerBuffer);
|
|
365
|
+
record.markerBuffer = Buffer.alloc(0);
|
|
366
|
+
this.failMarker(record, 'Remote operation marker did not match the local operation');
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const metadata = line.slice(expectedPrefix.length).match(/^([1-9]\d*):(0|1)$/);
|
|
370
|
+
const pid = metadata ? Number(metadata[1]) : Number.NaN;
|
|
371
|
+
if (!metadata || !Number.isSafeInteger(pid)) {
|
|
372
|
+
this.appendStderr(record, lineBytes);
|
|
373
|
+
this.appendStderr(record, record.markerBuffer);
|
|
374
|
+
record.markerBuffer = Buffer.alloc(0);
|
|
375
|
+
this.failMarker(record, 'Remote operation marker contained invalid process metadata');
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
record.pid = pid;
|
|
379
|
+
record.processGroup = metadata[2] === '1';
|
|
380
|
+
record.markerVerified = true;
|
|
381
|
+
record.status = 'running';
|
|
382
|
+
this.appendStderr(record, record.markerBuffer);
|
|
383
|
+
record.markerBuffer = Buffer.alloc(0);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
failMarker(record, error) {
|
|
387
|
+
record.status = 'failed';
|
|
388
|
+
record.error = error;
|
|
389
|
+
this.finish(record);
|
|
390
|
+
record.stream?.destroy();
|
|
391
|
+
}
|
|
392
|
+
flushMarkerBuffer(record) {
|
|
393
|
+
if (record.markerBuffer.length === 0) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
this.appendStderr(record, record.markerBuffer);
|
|
397
|
+
record.markerBuffer = Buffer.alloc(0);
|
|
398
|
+
}
|
|
399
|
+
appendStderr(record, data) {
|
|
400
|
+
record.stderrBytes += data.length;
|
|
401
|
+
this.appendOutput(record, 'stderr', data);
|
|
402
|
+
}
|
|
403
|
+
appendOutput(record, stream, data) {
|
|
404
|
+
const storedBytes = record.stdout.length + record.stderr.length;
|
|
405
|
+
const available = Math.max(0, record.maxOutputBytes - storedBytes);
|
|
406
|
+
const stored = data.subarray(0, available);
|
|
407
|
+
record[stream] = Buffer.concat([record[stream], stored]);
|
|
408
|
+
if (stored.length < data.length) {
|
|
409
|
+
if (stream === 'stdout') {
|
|
410
|
+
record.stdoutTruncated = true;
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
record.stderrTruncated = true;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
finish(record) {
|
|
418
|
+
if (record.finishedAt !== null) {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
record.finishedAt = this.now();
|
|
422
|
+
record.expiresAt = record.finishedAt + record.retentionMs;
|
|
423
|
+
}
|
|
424
|
+
info(record) {
|
|
425
|
+
return {
|
|
426
|
+
operationId: record.operationId,
|
|
427
|
+
alias: record.alias,
|
|
428
|
+
status: record.status,
|
|
429
|
+
pid: record.pid,
|
|
430
|
+
processGroup: record.processGroup,
|
|
431
|
+
markerVerified: record.markerVerified,
|
|
432
|
+
cancelRequested: record.cancelRequested,
|
|
433
|
+
startedAt: record.startedAt,
|
|
434
|
+
finishedAt: record.finishedAt,
|
|
435
|
+
expiresAt: record.expiresAt,
|
|
436
|
+
retentionMs: record.retentionMs,
|
|
437
|
+
exitCode: record.exitCode,
|
|
438
|
+
signal: record.signal,
|
|
439
|
+
stdoutBytes: record.stdoutBytes,
|
|
440
|
+
stderrBytes: record.stderrBytes,
|
|
441
|
+
stdoutStoredBytes: record.stdout.length,
|
|
442
|
+
stderrStoredBytes: record.stderr.length,
|
|
443
|
+
stdoutTruncated: record.stdoutTruncated,
|
|
444
|
+
stderrTruncated: record.stderrTruncated,
|
|
445
|
+
maxOutputBytes: record.maxOutputBytes,
|
|
446
|
+
...(record.error ? { error: record.error } : {}),
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
clearPendingStart(alias, operationId) {
|
|
450
|
+
if (this.pendingStarts.get(alias) === operationId) {
|
|
451
|
+
this.pendingStarts.delete(alias);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
requireOperation(operationId) {
|
|
455
|
+
this.sweepExpired();
|
|
456
|
+
const record = this.operations.get(operationId);
|
|
457
|
+
if (!record) {
|
|
458
|
+
throw new Error(`Operation '${operationId}' not found or expired`);
|
|
459
|
+
}
|
|
460
|
+
return record;
|
|
461
|
+
}
|
|
462
|
+
normalizeMaxOutputBytes(value) {
|
|
463
|
+
const normalized = value ?? DEFAULT_OPERATION_MAX_OUTPUT_BYTES;
|
|
464
|
+
if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > HARD_OPERATION_MAX_OUTPUT_BYTES) {
|
|
465
|
+
throw new Error(`maxOutputBytes must be between 1 and ${HARD_OPERATION_MAX_OUTPUT_BYTES}`);
|
|
466
|
+
}
|
|
467
|
+
return normalized;
|
|
468
|
+
}
|
|
469
|
+
normalizeReadBytes(value) {
|
|
470
|
+
const normalized = value ?? DEFAULT_OPERATION_READ_BYTES;
|
|
471
|
+
if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > HARD_OPERATION_READ_BYTES) {
|
|
472
|
+
throw new Error(`maxBytes must be between 1 and ${HARD_OPERATION_READ_BYTES}`);
|
|
473
|
+
}
|
|
474
|
+
return normalized;
|
|
475
|
+
}
|
|
476
|
+
normalizeRetentionMs(value) {
|
|
477
|
+
const normalized = value ?? DEFAULT_OPERATION_RETENTION_MS;
|
|
478
|
+
if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > MAX_OPERATION_RETENTION_MS) {
|
|
479
|
+
throw new Error(`retentionMs must be between 1 and ${MAX_OPERATION_RETENTION_MS}`);
|
|
480
|
+
}
|
|
481
|
+
return normalized;
|
|
482
|
+
}
|
|
483
|
+
normalizeStartTimeoutMs(value) {
|
|
484
|
+
const normalized = value ?? DEFAULT_OPERATION_START_TIMEOUT_MS;
|
|
485
|
+
if (!Number.isSafeInteger(normalized) || normalized <= 0 || normalized > MAX_OPERATION_START_TIMEOUT_MS) {
|
|
486
|
+
throw new Error(`startTimeoutMs must be between 1 and ${MAX_OPERATION_START_TIMEOUT_MS}`);
|
|
487
|
+
}
|
|
488
|
+
return normalized;
|
|
489
|
+
}
|
|
490
|
+
normalizeOffset(value, length, field) {
|
|
491
|
+
const normalized = value ?? 0;
|
|
492
|
+
if (!Number.isSafeInteger(normalized) || normalized < 0 || normalized > length) {
|
|
493
|
+
throw new Error(`${field} must be between 0 and ${length}`);
|
|
494
|
+
}
|
|
495
|
+
return normalized;
|
|
496
|
+
}
|
|
497
|
+
ensureUtf8Boundary(buffer, offset, field) {
|
|
498
|
+
if (offset < buffer.length && this.isUtf8ContinuationByte(buffer[offset])) {
|
|
499
|
+
throw new Error(`${field} must point to a UTF-8 character boundary`);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
utf8SafeEnd(buffer, start, requestedEnd, stream) {
|
|
503
|
+
const limitedByMaxBytes = requestedEnd < buffer.length;
|
|
504
|
+
let end = requestedEnd;
|
|
505
|
+
if (limitedByMaxBytes) {
|
|
506
|
+
while (end > start && this.isUtf8ContinuationByte(buffer[end])) {
|
|
507
|
+
--end;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
end = this.trimIncompleteUtf8Sequence(buffer, start, end);
|
|
511
|
+
if (end === start && requestedEnd > start && limitedByMaxBytes) {
|
|
512
|
+
throw new Error(`maxBytes is too small to read the next UTF-8 character from ${stream}`);
|
|
513
|
+
}
|
|
514
|
+
return end;
|
|
515
|
+
}
|
|
516
|
+
trimIncompleteUtf8Sequence(buffer, start, end) {
|
|
517
|
+
if (end <= start) {
|
|
518
|
+
return end;
|
|
519
|
+
}
|
|
520
|
+
let sequenceStart = end - 1;
|
|
521
|
+
while (sequenceStart > start && this.isUtf8ContinuationByte(buffer[sequenceStart])) {
|
|
522
|
+
--sequenceStart;
|
|
523
|
+
}
|
|
524
|
+
const expectedLength = this.utf8SequenceLength(buffer[sequenceStart]);
|
|
525
|
+
return sequenceStart + expectedLength > end ? sequenceStart : end;
|
|
526
|
+
}
|
|
527
|
+
utf8SequenceLength(value) {
|
|
528
|
+
if ((value & 0x80) === 0) {
|
|
529
|
+
return 1;
|
|
530
|
+
}
|
|
531
|
+
if ((value & 0xe0) === 0xc0) {
|
|
532
|
+
return 2;
|
|
533
|
+
}
|
|
534
|
+
if ((value & 0xf0) === 0xe0) {
|
|
535
|
+
return 3;
|
|
536
|
+
}
|
|
537
|
+
if ((value & 0xf8) === 0xf0) {
|
|
538
|
+
return 4;
|
|
539
|
+
}
|
|
540
|
+
return 1;
|
|
541
|
+
}
|
|
542
|
+
isUtf8ContinuationByte(value) {
|
|
543
|
+
return (value & 0xc0) === 0x80;
|
|
544
|
+
}
|
|
545
|
+
}
|
package/dist/pty-manager.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ export declare class PtyManager {
|
|
|
16
16
|
private idCounter;
|
|
17
17
|
private readonly defaultBufferSize;
|
|
18
18
|
private readonly idleTimeoutMs;
|
|
19
|
+
private readonly closedRetentionMs;
|
|
19
20
|
private idleSweeper;
|
|
20
21
|
constructor();
|
|
21
22
|
start(deps: PtyDependencies, alias: string, command: string, options?: PtyOptions): Promise<string>;
|
package/dist/pty-manager.js
CHANGED
|
@@ -12,6 +12,7 @@ export class PtyManager {
|
|
|
12
12
|
defaultBufferSize = 1024 * 1024; // 1MB
|
|
13
13
|
// 默认 idle timeout 1 小时,超时未读的 pty 自动回收
|
|
14
14
|
idleTimeoutMs = Number(process.env.SSH_MCP_PTY_IDLE_TIMEOUT_MS) || 3600_000;
|
|
15
|
+
closedRetentionMs = Number(process.env.SSH_MCP_PTY_CLOSED_RETENTION_MS) || 300_000;
|
|
15
16
|
idleSweeper = null;
|
|
16
17
|
constructor() {
|
|
17
18
|
this.startIdleSweeper();
|
|
@@ -40,6 +41,7 @@ export class PtyManager {
|
|
|
40
41
|
unreadRawBytes: 0,
|
|
41
42
|
maxBufferSize,
|
|
42
43
|
active: true,
|
|
44
|
+
closedAt: null,
|
|
43
45
|
};
|
|
44
46
|
// 监听输出数据
|
|
45
47
|
stream.on('data', (data) => {
|
|
@@ -59,17 +61,15 @@ export class PtyManager {
|
|
|
59
61
|
}
|
|
60
62
|
});
|
|
61
63
|
stream.on('close', () => {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
try {
|
|
65
|
-
terminal.dispose();
|
|
66
|
-
}
|
|
67
|
-
catch (e) {
|
|
68
|
-
console.warn(`PTY ${ptyId} terminal dispose failed:`, e.message);
|
|
64
|
+
if (!this.sessions.has(ptyId)) {
|
|
65
|
+
return;
|
|
69
66
|
}
|
|
67
|
+
ptySession.active = false;
|
|
68
|
+
ptySession.closedAt = Date.now();
|
|
70
69
|
});
|
|
71
70
|
stream.on('error', (err) => {
|
|
72
71
|
ptySession.active = false;
|
|
72
|
+
ptySession.closedAt = Date.now();
|
|
73
73
|
terminal.write(`\n[PTY Error: ${err.message}]`);
|
|
74
74
|
});
|
|
75
75
|
this.sessions.set(ptyId, ptySession);
|
|
@@ -197,6 +197,10 @@ export class PtyManager {
|
|
|
197
197
|
const now = Date.now();
|
|
198
198
|
for (const [id, session] of this.sessions) {
|
|
199
199
|
if (!session.active) {
|
|
200
|
+
const closedAt = session.closedAt ?? session.lastOutputAt ?? session.createdAt;
|
|
201
|
+
if (now - Math.max(closedAt, session.lastReadAt) > this.closedRetentionMs) {
|
|
202
|
+
this.close(id);
|
|
203
|
+
}
|
|
200
204
|
continue;
|
|
201
205
|
}
|
|
202
206
|
if (now - session.lastReadAt > this.idleTimeoutMs) {
|