dsh-ssh-pty 0.0.0-stage → 0.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.
- package/LICENSE +21 -0
- package/README.md +80 -2
- package/cordis.patch.yml +20 -0
- package/icon.svg +25 -0
- package/lib/backend.js +234 -0
- package/lib/index.js +216 -0
- package/lib/ssh-config.js +107 -0
- package/lib/ssh-session.js +373 -0
- package/lib/takeover.js +509 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +46 -4
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Minimal ~/.ssh/config reader for controlled SSH terminals.
|
|
2
|
+
// Subset semantics: Host blocks, first-value-wins per keyword (except IdentityFile
|
|
3
|
+
// which accumulates across blocks), ~ expansion in paths, patterns with * / ! skipped.
|
|
4
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
export function defaultSshConfigPath() {
|
|
9
|
+
return join(homedir(), '.ssh', 'config');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function expandHome(value) {
|
|
13
|
+
if (value === '~') return homedir();
|
|
14
|
+
if (value.startsWith('~/') || value.startsWith('~\\')) return join(homedir(), value.slice(2));
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function newEntry(alias) {
|
|
19
|
+
return {
|
|
20
|
+
alias,
|
|
21
|
+
hostname: undefined,
|
|
22
|
+
port: undefined,
|
|
23
|
+
user: undefined,
|
|
24
|
+
identityFiles: [],
|
|
25
|
+
// Always an array (possibly empty): ProxyJump takes a comma-separated jump
|
|
26
|
+
// chain, and tool outputs must stay structurally stable for lossless JSON.
|
|
27
|
+
proxyJump: [],
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function parseSshConfig(text) {
|
|
32
|
+
const entries = new Map();
|
|
33
|
+
let current = [];
|
|
34
|
+
for (const raw of String(text ?? '').split(/\r?\n/)) {
|
|
35
|
+
// strip trailing comments, then split keyword from value on the first whitespace
|
|
36
|
+
const line = raw.replace(/(#|;).*$/, '').trim();
|
|
37
|
+
if (!line) continue;
|
|
38
|
+
const sp = line.search(/[\s=]/);
|
|
39
|
+
if (sp === -1) continue;
|
|
40
|
+
const keyword = line.slice(0, sp).toLowerCase();
|
|
41
|
+
const rest = line.slice(sp + 1).replace(/^[\s=]+/, '').trim();
|
|
42
|
+
if (!rest) continue;
|
|
43
|
+
if (keyword === 'host') {
|
|
44
|
+
current = [];
|
|
45
|
+
for (const pattern of rest.split(/\s+/)) {
|
|
46
|
+
if (/[*!]/.test(pattern)) continue;
|
|
47
|
+
const key = pattern.toLowerCase();
|
|
48
|
+
let entry = entries.get(key);
|
|
49
|
+
if (!entry) {
|
|
50
|
+
entry = newEntry(pattern);
|
|
51
|
+
entries.set(key, entry);
|
|
52
|
+
}
|
|
53
|
+
current.push(entry);
|
|
54
|
+
}
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (current.length === 0) continue;
|
|
58
|
+
for (const entry of current) {
|
|
59
|
+
switch (keyword) {
|
|
60
|
+
case 'hostname':
|
|
61
|
+
if (entry.hostname === undefined) entry.hostname = rest;
|
|
62
|
+
break;
|
|
63
|
+
case 'port': {
|
|
64
|
+
if (entry.port === undefined) {
|
|
65
|
+
const port = Number.parseInt(rest, 10);
|
|
66
|
+
if (Number.isInteger(port) && port > 0 && port < 65536) entry.port = port;
|
|
67
|
+
}
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
case 'user':
|
|
71
|
+
if (entry.user === undefined) entry.user = rest;
|
|
72
|
+
break;
|
|
73
|
+
case 'identityfile':
|
|
74
|
+
entry.identityFiles.push(expandHome(rest));
|
|
75
|
+
break;
|
|
76
|
+
case 'proxyjump':
|
|
77
|
+
if (entry.proxyJump.length === 0 && rest.toLowerCase() !== 'none') {
|
|
78
|
+
entry.proxyJump = rest.split(/[\s,]+/).filter(Boolean);
|
|
79
|
+
}
|
|
80
|
+
break;
|
|
81
|
+
default:
|
|
82
|
+
break;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return [...entries.values()];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function loadSshHosts(configPath = defaultSshConfigPath()) {
|
|
90
|
+
if (!existsSync(configPath)) return [];
|
|
91
|
+
let text;
|
|
92
|
+
try {
|
|
93
|
+
text = readFileSync(configPath, 'utf8');
|
|
94
|
+
} catch {
|
|
95
|
+
return [];
|
|
96
|
+
}
|
|
97
|
+
return parseSshConfig(text);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Resolves the host alias hidden in a terminal_open cwd argument (path.resolve pollution safe). */
|
|
101
|
+
export function aliasFromCwd(cwd) {
|
|
102
|
+
if (typeof cwd !== 'string' || cwd.length === 0) return undefined;
|
|
103
|
+
const norm = cwd.replace(/[\\/]+$/, '');
|
|
104
|
+
const idx = Math.max(norm.lastIndexOf('\\'), norm.lastIndexOf('/'));
|
|
105
|
+
const seg = idx === -1 ? norm : norm.slice(idx + 1);
|
|
106
|
+
return seg.length > 0 ? seg : undefined;
|
|
107
|
+
}
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
// One interactive SSH shell session: ssh2 stream -> bounded scrollback + headless xterm viewport.
|
|
2
|
+
import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require';
|
|
3
|
+
import { TerminalError } from '@deepseek-ai/dsh-terminal';
|
|
4
|
+
|
|
5
|
+
const requireHeadless = createLazyRequire('@xterm/headless', import.meta.url);
|
|
6
|
+
|
|
7
|
+
const INTC = '\x03'; // Ctrl-C
|
|
8
|
+
const SUSPC = '\x1a'; // Ctrl-Z
|
|
9
|
+
const POLL_INTERVAL_MS = 250;
|
|
10
|
+
|
|
11
|
+
/** Bounded line scrollback with newest-relative paged reads. */
|
|
12
|
+
class Scrollback {
|
|
13
|
+
constructor(maxLines, maxBytes) {
|
|
14
|
+
this.maxLines = Math.max(1, Math.floor(maxLines));
|
|
15
|
+
this.maxBytes = Math.max(1, Math.floor(maxBytes));
|
|
16
|
+
this.lines = [];
|
|
17
|
+
this.totalBytes = 0;
|
|
18
|
+
this.pending = undefined; // last partial line awaiting continuation
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
append(text) {
|
|
22
|
+
const norm = String(text).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
23
|
+
const parts = norm.split('\n');
|
|
24
|
+
for (let i = 0; i < parts.length; i++) {
|
|
25
|
+
if (i === 0) {
|
|
26
|
+
if (this.pending !== undefined) {
|
|
27
|
+
this.pending += parts[0];
|
|
28
|
+
if (parts.length > 1) {
|
|
29
|
+
this._commit(this.pending);
|
|
30
|
+
this.pending = undefined;
|
|
31
|
+
}
|
|
32
|
+
} else if (parts.length > 1) {
|
|
33
|
+
this._commit(parts[0]);
|
|
34
|
+
}
|
|
35
|
+
} else if (i < parts.length - 1) {
|
|
36
|
+
this._commit(parts[i]);
|
|
37
|
+
} else {
|
|
38
|
+
this.pending = parts[i];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
this._trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
_commit(line) {
|
|
45
|
+
this.lines.push(line);
|
|
46
|
+
this.totalBytes += Buffer.byteLength(line, 'utf8') + 1;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_trim() {
|
|
50
|
+
while (this.lines.length > this.maxLines || this.totalBytes > this.maxBytes) {
|
|
51
|
+
const removed = this.lines.shift();
|
|
52
|
+
this.totalBytes -= Buffer.byteLength(removed, 'utf8') + 1;
|
|
53
|
+
if (this.lines.length === 0) break;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
hasContent() {
|
|
58
|
+
return this.lines.length > 0 || (this.pending !== undefined && this.pending.length > 0);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
snapshotLines() {
|
|
62
|
+
const copy = [...this.lines];
|
|
63
|
+
if (this.pending !== undefined && this.pending.length > 0) copy.push(this.pending);
|
|
64
|
+
return copy;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Newest-relative paged read: offset 0 = newest line backwards. 1-based inclusive bounds. */
|
|
68
|
+
read({ offset = 0, count = 500, maxBytes } = {}) {
|
|
69
|
+
const all = this.snapshotLines();
|
|
70
|
+
const total = all.length;
|
|
71
|
+
const take = Math.max(1, Math.floor(count));
|
|
72
|
+
const off = Math.max(0, Math.floor(offset));
|
|
73
|
+
const end = Math.max(0, total - off);
|
|
74
|
+
const begin = Math.max(0, end - take);
|
|
75
|
+
let text = all.slice(begin, end).join('\n');
|
|
76
|
+
let truncated = false;
|
|
77
|
+
const cap = maxBytes ?? Number.POSITIVE_INFINITY;
|
|
78
|
+
if (Buffer.byteLength(text, 'utf8') > cap) {
|
|
79
|
+
const buf = Buffer.from(text, 'utf8');
|
|
80
|
+
let cut = buf.length - cap;
|
|
81
|
+
while (cut < buf.length && cut > 0 && (buf[cut] & 0xc0) === 0x80) cut--;
|
|
82
|
+
text = buf.subarray(Math.max(0, cut)).toString('utf8');
|
|
83
|
+
truncated = true;
|
|
84
|
+
}
|
|
85
|
+
if (begin === end) return { text: '', totalLines: total, lineBegin: end, lineEnd: end, truncated };
|
|
86
|
+
return { text, totalLines: total, lineBegin: begin + 1, lineEnd: end, truncated };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class SshSession {
|
|
91
|
+
constructor({ sessionId, alias, conn, stream, config, host, owner, onClosed }) {
|
|
92
|
+
this.sessionId = sessionId;
|
|
93
|
+
this.alias = alias;
|
|
94
|
+
this.conn = conn;
|
|
95
|
+
this.stream = stream;
|
|
96
|
+
this.config = config;
|
|
97
|
+
// Takeover-page metadata (host entry + owning agent); safe, secret-free.
|
|
98
|
+
this.host = host ?? { alias };
|
|
99
|
+
this.ownerId = owner?.id;
|
|
100
|
+
this.ownerName = owner?.name;
|
|
101
|
+
this.createdAt = Date.now();
|
|
102
|
+
this.onClosed = onClosed;
|
|
103
|
+
|
|
104
|
+
const { Terminal } = requireHeadless();
|
|
105
|
+
this.emulator = new Terminal({
|
|
106
|
+
cols: config.cols,
|
|
107
|
+
rows: config.rows,
|
|
108
|
+
scrollback: 0,
|
|
109
|
+
allowProposedApi: true,
|
|
110
|
+
});
|
|
111
|
+
this.emulator.onData((data) => {
|
|
112
|
+
if (!this.closed && this.stream.writable && data.length > 0) {
|
|
113
|
+
this.stream.write(data);
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
this.scrollback = new Scrollback(config.maxScrollbackLines, config.maxScrollbackBytes);
|
|
118
|
+
this.decoder = new TextDecoder('utf-8', { stream: true });
|
|
119
|
+
this.lastOutputAt = Date.now();
|
|
120
|
+
this.statusValue = { kind: 'running' };
|
|
121
|
+
this.active = undefined;
|
|
122
|
+
this.closed = false;
|
|
123
|
+
this.closePromise = undefined;
|
|
124
|
+
this.motd = '';
|
|
125
|
+
|
|
126
|
+
this.stream.on('data', (chunk) => this._onData(chunk));
|
|
127
|
+
this.stream.on('close', () => this._markExited(null, null));
|
|
128
|
+
this.stream.on('error', (err) => this._markExited(null, err?.message ?? 'stream error'));
|
|
129
|
+
this.stream.on('exit', (code) => this._markExited(code, null));
|
|
130
|
+
this.conn.on('error', () => this._markExited(null, 'connection error'));
|
|
131
|
+
this.conn.on('close', () => this._markExited(null, null));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
get pid() {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
status() {
|
|
139
|
+
return { ...this.statusValue };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
_onData(chunk) {
|
|
143
|
+
this.lastOutputAt = Date.now();
|
|
144
|
+
const text = this.decoder.decode(typeof chunk === 'string' ? Buffer.from(chunk) : chunk, { stream: true });
|
|
145
|
+
if (!text) return;
|
|
146
|
+
this.scrollback.append(text);
|
|
147
|
+
this.emulator.write(text);
|
|
148
|
+
const op = this.active;
|
|
149
|
+
if (op && !op.settled) op.outputAcc.push(text);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
_settleActive(waitReason) {
|
|
153
|
+
const op = this.active;
|
|
154
|
+
if (!op || op.settled) return;
|
|
155
|
+
op.settled = true;
|
|
156
|
+
clearTimeout(op.timer);
|
|
157
|
+
clearInterval(op.poll);
|
|
158
|
+
if (op.signal && op.onAbort) op.signal.removeEventListener('abort', op.onAbort);
|
|
159
|
+
this.active = undefined;
|
|
160
|
+
op.doneResolve({
|
|
161
|
+
viewport: this.renderViewport(),
|
|
162
|
+
waitReason,
|
|
163
|
+
sessionStatus: { ...this.statusValue },
|
|
164
|
+
truncated: false,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
_failActive(error) {
|
|
169
|
+
const op = this.active;
|
|
170
|
+
if (!op || op.settled) return;
|
|
171
|
+
op.settled = true;
|
|
172
|
+
clearTimeout(op.timer);
|
|
173
|
+
clearInterval(op.poll);
|
|
174
|
+
if (op.signal && op.onAbort) op.signal.removeEventListener('abort', op.onAbort);
|
|
175
|
+
this.active = undefined;
|
|
176
|
+
op.doneReject(error);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
startSend({ text, submit, signal }) {
|
|
180
|
+
if (this.statusValue.kind !== 'running') {
|
|
181
|
+
throw new TerminalError(`SSH terminal session ${this.sessionId} has exited`, 'SESSION_EXITED');
|
|
182
|
+
}
|
|
183
|
+
if (this.active) {
|
|
184
|
+
throw new TerminalError(`terminal session ${this.sessionId} already has an active send`, 'SEND_ACTIVE');
|
|
185
|
+
}
|
|
186
|
+
const op = {
|
|
187
|
+
settled: false,
|
|
188
|
+
outputAcc: [],
|
|
189
|
+
doneResolve: null,
|
|
190
|
+
doneReject: null,
|
|
191
|
+
timer: null,
|
|
192
|
+
poll: null,
|
|
193
|
+
signal,
|
|
194
|
+
onAbort: null,
|
|
195
|
+
};
|
|
196
|
+
op.done = new Promise((resolve, reject) => {
|
|
197
|
+
op.doneResolve = resolve;
|
|
198
|
+
op.doneReject = reject;
|
|
199
|
+
});
|
|
200
|
+
this.active = op;
|
|
201
|
+
|
|
202
|
+
op.timer = setTimeout(() => this._settleActive('timeout'), this.config.sendTimeoutMs);
|
|
203
|
+
op.poll = setInterval(() => {
|
|
204
|
+
if (this.statusValue.kind !== 'running') {
|
|
205
|
+
this._settleActive('session_exit');
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (Date.now() - this.lastOutputAt >= this.config.idleSilenceMs) {
|
|
209
|
+
this._settleActive('inferred_idle');
|
|
210
|
+
}
|
|
211
|
+
}, POLL_INTERVAL_MS);
|
|
212
|
+
|
|
213
|
+
op.onAbort = () => {
|
|
214
|
+
try {
|
|
215
|
+
if (!this.closed && this.stream.writable) this.stream.write(INTC);
|
|
216
|
+
} catch {
|
|
217
|
+
// stream already dead; the exit path settles the operation
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
signal?.addEventListener('abort', op.onAbort, { once: true });
|
|
221
|
+
|
|
222
|
+
const payload = String(text ?? '') + (submit === false ? '' : '\r');
|
|
223
|
+
this.stream.write(payload);
|
|
224
|
+
this.lastOutputAt = Date.now();
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
done: op.done,
|
|
228
|
+
readOutput: () => {
|
|
229
|
+
const delta = op.outputAcc.join('');
|
|
230
|
+
op.outputAcc = [];
|
|
231
|
+
return { delta, truncated: false };
|
|
232
|
+
},
|
|
233
|
+
cancel: () => {
|
|
234
|
+
if (!op.settled) {
|
|
235
|
+
op.onAbort();
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
return false;
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
read(request = {}) {
|
|
244
|
+
return this.scrollback.read({ ...request, maxBytes: this.config.maxReadBytes });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async signal(sig) {
|
|
248
|
+
if (this.statusValue.kind !== 'running') {
|
|
249
|
+
throw new TerminalError(`terminal session ${this.sessionId} has exited`, 'SESSION_EXITED');
|
|
250
|
+
}
|
|
251
|
+
if (sig === 'SIGINT') {
|
|
252
|
+
this.stream.write(INTC);
|
|
253
|
+
return { delivered: true, targetPgid: 0 };
|
|
254
|
+
}
|
|
255
|
+
if (sig === 'SIGTSTP') {
|
|
256
|
+
this.stream.write(SUSPC);
|
|
257
|
+
return { delivered: true, targetPgid: 0 };
|
|
258
|
+
}
|
|
259
|
+
throw new TerminalError(
|
|
260
|
+
`signal ${sig} cannot be delivered over an SSH shell channel; use SIGINT (Ctrl-C) or terminal_close`,
|
|
261
|
+
'UNSUPPORTED_SIGNAL',
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
renderViewport() {
|
|
266
|
+
const buffer = this.emulator.buffer.active;
|
|
267
|
+
const lines = [];
|
|
268
|
+
for (let y = 0; y < this.emulator.rows; y++) {
|
|
269
|
+
lines.push(buffer.getLine(y)?.translateToString(true) ?? '');
|
|
270
|
+
}
|
|
271
|
+
while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
|
|
272
|
+
return lines.join('\n');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Raw PTY write for the human takeover page; bypasses agent send/readiness logic. */
|
|
276
|
+
write(data) {
|
|
277
|
+
if (this.closed || this.statusValue.kind !== 'running') return false;
|
|
278
|
+
if (typeof data !== 'string' || data.length === 0) return false;
|
|
279
|
+
try {
|
|
280
|
+
this.stream.write(data);
|
|
281
|
+
return true;
|
|
282
|
+
} catch {
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** PTY + emulator resize (clamped to the same limits as the plugin config). */
|
|
288
|
+
resize(cols, rows) {
|
|
289
|
+
if (this.statusValue.kind !== 'running') return false;
|
|
290
|
+
const nextCols = Math.min(500, Math.max(20, Math.floor(Number(cols) || 0)));
|
|
291
|
+
const nextRows = Math.min(200, Math.max(10, Math.floor(Number(rows) || 0)));
|
|
292
|
+
if (nextCols === this.emulator.cols && nextRows === this.emulator.rows) return true;
|
|
293
|
+
try {
|
|
294
|
+
this.emulator.resize(nextCols, nextRows);
|
|
295
|
+
} catch {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
try {
|
|
299
|
+
this.stream.setWindow(nextRows, nextCols, 0, 0);
|
|
300
|
+
} catch {
|
|
301
|
+
// stream already closed; the exit path settles everything
|
|
302
|
+
}
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
cursor() {
|
|
307
|
+
const buffer = this.emulator.buffer.active;
|
|
308
|
+
return { x: buffer.cursorX, y: buffer.cursorY };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Waits for the first output burst (banner/prompt) to land and go quiet; returns the first screen. */
|
|
312
|
+
async warmup(signal) {
|
|
313
|
+
const deadline = Date.now() + this.config.warmupTimeoutMs;
|
|
314
|
+
while (Date.now() < deadline) {
|
|
315
|
+
if (this.statusValue.kind !== 'running') break;
|
|
316
|
+
if (signal?.aborted) break;
|
|
317
|
+
if (this.scrollback.hasContent() && Date.now() - this.lastOutputAt >= 400) break;
|
|
318
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
319
|
+
}
|
|
320
|
+
this.motd = this.renderViewport();
|
|
321
|
+
return this.motd;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
_markExited(exitCode, error) {
|
|
325
|
+
if (this.statusValue.kind !== 'running') return;
|
|
326
|
+
this.statusValue = {
|
|
327
|
+
kind: 'exited',
|
|
328
|
+
exitCode: typeof exitCode === 'number' ? exitCode : null,
|
|
329
|
+
signal: null,
|
|
330
|
+
};
|
|
331
|
+
this.exitError = typeof error === 'string' && error !== '' ? error : undefined;
|
|
332
|
+
this._settleActive('session_exit');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async close(reason) {
|
|
336
|
+
if (this.closePromise) return this.closePromise;
|
|
337
|
+
this.closePromise = (async () => {
|
|
338
|
+
this.closed = true;
|
|
339
|
+
this._markExited(null, null);
|
|
340
|
+
const op = this.active;
|
|
341
|
+
if (op && !op.settled) {
|
|
342
|
+
this._failActive(new Error(`terminal session ${this.sessionId} closed: ${reason ?? 'closed'}`));
|
|
343
|
+
}
|
|
344
|
+
try {
|
|
345
|
+
this.stream.removeAllListeners?.('data');
|
|
346
|
+
this.stream.removeAllListeners?.('close');
|
|
347
|
+
this.stream.removeAllListeners?.('error');
|
|
348
|
+
this.stream.removeAllListeners?.('exit');
|
|
349
|
+
} catch {
|
|
350
|
+
// already detached
|
|
351
|
+
}
|
|
352
|
+
try {
|
|
353
|
+
this.conn.removeAllListeners?.('error');
|
|
354
|
+
this.conn.removeAllListeners?.('close');
|
|
355
|
+
} catch {
|
|
356
|
+
// already detached
|
|
357
|
+
}
|
|
358
|
+
try {
|
|
359
|
+
this.stream.close();
|
|
360
|
+
} catch {
|
|
361
|
+
// stream already closed
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
this.conn.end();
|
|
365
|
+
} catch {
|
|
366
|
+
// connection already gone
|
|
367
|
+
}
|
|
368
|
+
this.onClosed?.(this.sessionId);
|
|
369
|
+
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
370
|
+
})();
|
|
371
|
+
return this.closePromise;
|
|
372
|
+
}
|
|
373
|
+
}
|