@linxin666/dsh-ssh 0.4.20 → 0.4.21

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.
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { existsSync, lstatSync, mkdirSync, readdirSync, statSync } from 'node:fs'
8
- import { dirname, join, relative, resolve as resolvePath } from 'node:path'
8
+ import { dirname, join, posix, relative, resolve as resolvePath } from 'node:path'
9
9
  import { Client, type SFTPWrapper } from 'ssh2'
10
10
  import type { RemoteDirEntry, TransferProgress } from '../protocol.ts'
11
11
  import { withClient, type PoolEngine } from './connection-pool.ts'
@@ -47,21 +47,24 @@ export async function upload(
47
47
  if (!existsSync(local)) throw new Error('local path not found: \'' + localPath + '\'')
48
48
  return withClient(engine, alias, (client) => withSftp(client, async (sftp) => {
49
49
  const stat = statSync(local)
50
+ const ensuredDirs = new Set<string>()
50
51
  let files: string[]
51
52
  if (stat.isDirectory()) {
52
53
  if (!recursive) throw new Error('\'' + localPath + '\' is a directory — enable recursive upload')
53
54
  files = walkLocalDir(local)
54
- await ensureRemoteDir(sftp, remotePath)
55
+ await ensureRemoteDir(sftp, remotePath, ensuredDirs)
55
56
  } else {
56
57
  files = ['']
57
- await ensureRemoteDir(sftp, dirname(remotePath))
58
+ await ensureRemoteDir(sftp, posix.dirname(remotePath), ensuredDirs)
58
59
  }
59
60
  let bytes = 0
61
+ const baseRemote = remotePath.replace(/\/$/, '')
60
62
  for (const rel of files) {
61
63
  const src = rel === '' ? local : join(local, rel)
62
64
  // Remote paths always use forward slashes; normalize any OS separators.
63
65
  const remoteRel = rel.split(/[\\/]/).join('/')
64
- const dst = rel === '' ? remotePath : remotePath.replace(/\/$/, '') + '/' + remoteRel
66
+ const dst = rel === '' ? remotePath : baseRemote + '/' + remoteRel
67
+ if (rel !== '') await ensureRemoteDir(sftp, posix.dirname(dst), ensuredDirs)
65
68
  await fastPut(sftp, src, dst, engine.opts.sftpConcurrency, onProgress)
66
69
  bytes += statSync(src).size
67
70
  }
@@ -143,38 +146,66 @@ function sftpChannel(client: Client): Promise<SFTPWrapper> {
143
146
  })
144
147
  }
145
148
 
146
- /** Create a remote directory chain (stat-then-mkdir per segment). */
147
- function ensureRemoteDir(sftp: SFTPWrapper, remote: string): Promise<void> {
149
+ function normalizeRemoteDir(remote: string): string {
150
+ const cleaned = remote.replace(/\/+$/, '')
151
+ return cleaned === '' ? '/' : cleaned
152
+ }
153
+
154
+ function recordEnsuredPrefixes(segments: string[], upToIndex: number, ensuredDirs?: Set<string>): void {
155
+ if (ensuredDirs === undefined) return
156
+ for (let index = 0; index <= upToIndex; index += 1) {
157
+ ensuredDirs.add('/' + segments.slice(0, index + 1).join('/'))
158
+ }
159
+ }
160
+
161
+ function statRemote(sftp: SFTPWrapper, path: string): Promise<boolean> {
162
+ return new Promise((resolve) => {
163
+ sftp.stat(path, (error) => { resolve(error === undefined) })
164
+ })
165
+ }
166
+
167
+ function mkdirRemote(sftp: SFTPWrapper, path: string): Promise<void> {
148
168
  return new Promise((resolve, reject) => {
149
- const segments = remote.replace(/^\/+/, '').split('/').filter(segment => segment !== '')
150
- const walk = (index: number): void => {
151
- if (index >= segments.length) {
152
- resolve()
153
- return
154
- }
155
- const current = '/' + segments.slice(0, index + 1).join('/')
156
- sftp.stat(current, (statError) => {
157
- if (statError === undefined) {
158
- walk(index + 1)
159
- return
160
- }
161
- // Statting a missing path fails; mkdir it (idempotent because the
162
- // stat check runs first — some sftp servers throw on EEXIST).
163
- sftp.mkdir(current, (mkdirError) => {
164
- if (mkdirError !== undefined) {
165
- reject(mkdirError)
166
- return
167
- }
168
- walk(index + 1)
169
- })
170
- })
171
- }
172
- walk(0)
169
+ sftp.mkdir(path, (error) => {
170
+ if (error !== undefined) reject(error)
171
+ else resolve()
172
+ })
173
173
  })
174
174
  }
175
175
 
176
+ /** Create a remote directory chain (with a 1-RTT stat fast path and prefix cache). */
177
+ export async function ensureRemoteDir(sftp: SFTPWrapper, remote: string, ensuredDirs?: Set<string>): Promise<void> {
178
+ const normalized = normalizeRemoteDir(remote)
179
+ if (normalized === '/' || ensuredDirs?.has(normalized) === true) return
180
+ const segments = normalized.slice(1).split('/').filter(segment => segment !== '')
181
+ if (segments.length === 0) return
182
+
183
+ // Fast path: a single stat on a multi-segment path avoids N sequential RTTs
184
+ // when the target directory already exists.
185
+ if (segments.length > 1 && await statRemote(sftp, normalized)) {
186
+ recordEnsuredPrefixes(segments, segments.length - 1, ensuredDirs)
187
+ return
188
+ }
189
+
190
+ for (let index = 0; index < segments.length; index += 1) {
191
+ const current = '/' + segments.slice(0, index + 1).join('/')
192
+ if (ensuredDirs?.has(current) === true) continue
193
+ const isLastAfterMissedFastPath = segments.length > 1 && index === segments.length - 1
194
+ if (!isLastAfterMissedFastPath && await statRemote(sftp, current)) {
195
+ ensuredDirs?.add(current)
196
+ continue
197
+ }
198
+ try {
199
+ await mkdirRemote(sftp, current)
200
+ } catch (error) {
201
+ if (!(await statRemote(sftp, current))) throw error
202
+ }
203
+ ensuredDirs?.add(current)
204
+ }
205
+ }
206
+
176
207
  /** One fastPut/fastGet transfer with throttled progress (the two directions share everything but the verb). */
177
- function fastTransfer(sftp: SFTPWrapper, kind: 'put' | 'get', src: string, dst: string, concurrency: number, onProgress?: (progress: TransferProgress) => void): Promise<void> {
208
+ export function fastTransfer(sftp: SFTPWrapper, kind: 'put' | 'get', src: string, dst: string, concurrency: number, onProgress?: (progress: TransferProgress) => void): Promise<void> {
178
209
  return new Promise((resolve, reject) => {
179
210
  // Progress frames name the destination on upload, the source on download;
180
211
  // the final size comes from the local side of the transfer.
@@ -183,6 +214,7 @@ function fastTransfer(sftp: SFTPWrapper, kind: 'put' | 'get', src: string, dst:
183
214
  let last = 0
184
215
  let lastEmit = 0
185
216
  const started = Date.now()
217
+ let prevEmit = started
186
218
  if (kind === 'put') {
187
219
  onProgress?.({ phase: 'transferring', file, transferred: 0, total: statSync(src).size, percent: 0 })
188
220
  }
@@ -192,23 +224,25 @@ function fastTransfer(sftp: SFTPWrapper, kind: 'put' | 'get', src: string, dst:
192
224
  // needs ~10 frames per second.
193
225
  if (now - lastEmit < 100 && transferred < total) return
194
226
  lastEmit = now
195
- const elapsed = (now - started) / 1000
227
+ const windowSec = (now - prevEmit) / 1000
196
228
  onProgress?.({
197
229
  phase: 'transferring',
198
230
  file,
199
231
  transferred,
200
232
  total,
201
233
  percent: total > 0 ? Math.round((transferred / total) * 1000) / 10 : 0,
202
- speedBps: elapsed > 0 ? Math.round((transferred - last) / elapsed) : undefined,
234
+ speedBps: windowSec > 0 ? Math.round((transferred - last) / windowSec) : undefined,
203
235
  })
236
+ prevEmit = now
204
237
  last = transferred
205
238
  }
206
239
  const done = (error: unknown): void => {
207
- if (error !== undefined) {
240
+ if (error !== undefined && error !== null) {
208
241
  onProgress?.({ phase: 'error', file, transferred: 0, total: 0, percent: 0, error: String(error) })
209
242
  reject(error)
210
243
  } else {
211
- onProgress?.({ phase: 'done', file, transferred: finalSize(), total: finalSize(), percent: 100 })
244
+ const size = finalSize()
245
+ onProgress?.({ phase: 'done', file, transferred: size, total: size, percent: 100 })
212
246
  resolve()
213
247
  }
214
248
  }
@@ -9,6 +9,7 @@
9
9
  * for a short grace window so a reattaching view still sees the final screen.
10
10
  */
11
11
  import { randomBytes } from 'node:crypto'
12
+ import { StringDecoder } from 'node:string_decoder'
12
13
  import { WebSocket } from 'ws'
13
14
  import type { KeyboardInteractiveHandler } from './connection-pool.ts'
14
15
  import type { ShellSession } from './pty.ts'
@@ -29,15 +30,27 @@ const DEFAULT_IDLE_MS = 10 * 60 * 1000
29
30
  /** An exited session is kept this long for a reattaching view. */
30
31
  const DEFAULT_EXIT_GRACE_MS = 60 * 1000
31
32
 
33
+ /** Clamp a terminal column/row dimension to an integer >= `min`. */
34
+ function clampDimension(value: unknown, min: number, fallback: number): number {
35
+ if (typeof value !== 'number' || !Number.isFinite(value)) return fallback
36
+ return Math.max(min, Math.trunc(value))
37
+ }
38
+
32
39
  /** One live terminal session and the sockets currently watching it. */
33
40
  interface HostedTerminal {
34
41
  id: string
35
42
  alias: string
36
43
  shell?: ShellSession
37
44
  sockets: Set<WebSocket>
38
- /** Bounded scrollback replayed to an attaching socket. */
45
+ decoder: StringDecoder
46
+ /** Bounded scrollback ring replayed to an attaching socket. */
39
47
  buffer: string[]
48
+ bufferChunkBytes: number[]
49
+ bufferHead: number
40
50
  bufferBytes: number
51
+ paused: boolean
52
+ /** Cached drain callback reused across backed-up sends without per-frame allocation. */
53
+ onDrain?: () => void
41
54
  exited: boolean
42
55
  exit?: { code: number | null; error?: string }
43
56
  /** Pending keyboard-interactive challenge, whoever attached when it arrived. */
@@ -83,10 +96,17 @@ export class TerminalSessionRegistry {
83
96
  id: randomBytes(9).toString('hex'),
84
97
  alias,
85
98
  sockets: new Set(),
99
+ decoder: new StringDecoder('utf8'),
86
100
  buffer: [],
101
+ bufferChunkBytes: [],
102
+ bufferHead: 0,
87
103
  bufferBytes: 0,
104
+ paused: false,
88
105
  exited: false,
89
106
  }
107
+ session.onDrain = () => {
108
+ if (session.paused) this.applyBackpressure(session)
109
+ }
90
110
  this.sessions.set(session.id, session)
91
111
  this.bind(ws, session)
92
112
  try {
@@ -97,12 +117,15 @@ export class TerminalSessionRegistry {
97
117
  return
98
118
  }
99
119
  session.shell = shell
100
- shell.onData = data => { this.pushOutput(session, data.toString('utf8')) }
120
+ shell.onData = data => {
121
+ const text = session.decoder.write(data)
122
+ if (text !== '') this.pushOutput(session, text)
123
+ }
101
124
  shell.onExit = (code, error) => { this.finish(session, code, error) }
102
125
  this.send(session, { type: 'ready', alias, sessionId: session.id })
103
126
  } catch (error) {
104
- this.sessions.delete(session.id)
105
127
  this.send(session, { type: 'exit', code: null, error: error instanceof Error ? error.message : String(error) })
128
+ this.end(session)
106
129
  }
107
130
  }
108
131
 
@@ -115,22 +138,24 @@ export class TerminalSessionRegistry {
115
138
  if (session === undefined) return false
116
139
  this.bind(ws, session)
117
140
  this.clearReap(session)
118
- for (const chunk of session.buffer) this.sendTo(session, ws, { type: 'output', data: chunk })
119
- this.sendTo(session, ws, { type: 'ready', alias: session.alias, sessionId: session.id })
141
+ for (let index = session.bufferHead; index < session.buffer.length; index += 1) {
142
+ this.sendPayload(session, ws, JSON.stringify({ type: 'output', data: session.buffer[index]! }))
143
+ }
144
+ this.sendPayload(session, ws, JSON.stringify({ type: 'ready', alias: session.alias, sessionId: session.id }))
120
145
  if (session.exited) {
121
- this.sendTo(session, ws, { type: 'exit', code: session.exit?.code ?? null, error: session.exit?.error })
146
+ this.sendPayload(session, ws, JSON.stringify({ type: 'exit', code: session.exit?.code ?? null, error: session.exit?.error }))
122
147
  // Re-arm the grace window: this socket now holds the exited session open.
123
148
  this.scheduleReap(session, this.exitGraceMs)
124
149
  } else {
125
- session.shell?.resize(Math.max(2, size.cols), Math.max(1, size.rows))
126
- session.shell?.resume()
150
+ session.shell?.resize(clampDimension(size.cols, 2, 80), clampDimension(size.rows, 1, 24))
151
+ this.applyBackpressure(session)
127
152
  }
128
153
  return true
129
154
  }
130
155
 
131
156
  /** End every session (host teardown, plugin dispose). */
132
157
  dispose(): void {
133
- for (const session of [...this.sessions.values()]) this.end(session, false)
158
+ for (const session of [...this.sessions.values()]) this.end(session)
134
159
  this.sessions.clear()
135
160
  }
136
161
 
@@ -143,22 +168,26 @@ export class TerminalSessionRegistry {
143
168
  private bind(ws: WebSocket, session: HostedTerminal): void {
144
169
  session.sockets.add(ws)
145
170
  ws.on('message', (data) => {
146
- let frame: { type?: string; data?: string; cols?: number; rows?: number; responses?: string[] }
171
+ let frame: { type?: unknown; data?: unknown; cols?: unknown; rows?: unknown; responses?: unknown }
147
172
  try {
148
173
  frame = JSON.parse(String(data)) as typeof frame
149
174
  } catch {
150
175
  return
151
176
  }
177
+ if (typeof frame !== 'object' || frame === null) return
152
178
  if (frame.type === 'input') {
153
- session.shell?.send(frame.data ?? '')
179
+ if (typeof frame.data === 'string') session.shell?.send(frame.data)
154
180
  } else if (frame.type === 'resize') {
155
- session.shell?.resize(Math.max(2, frame.cols ?? 80), Math.max(1, frame.rows ?? 24))
181
+ session.shell?.resize(clampDimension(frame.cols, 2, 80), clampDimension(frame.rows, 1, 24))
156
182
  } else if (frame.type === 'auth_response') {
157
183
  const finish = session.pendingAuthFinish
158
184
  session.pendingAuthFinish = undefined
159
- try { finish?.(frame.responses ?? []) } catch { /* the connect already failed */ }
185
+ const responses = Array.isArray(frame.responses)
186
+ ? frame.responses.filter((item): item is string => typeof item === 'string')
187
+ : []
188
+ try { finish?.(responses) } catch { /* the connect already failed */ }
160
189
  } else if (frame.type === 'close') {
161
- this.end(session, true)
190
+ this.end(session)
162
191
  } else if (frame.type === 'detach') {
163
192
  this.detach(ws)
164
193
  }
@@ -177,19 +206,23 @@ export class TerminalSessionRegistry {
177
206
  // screen is dropped).
178
207
  this.scheduleReap(session, session.exited ? this.exitGraceMs : this.idleMs)
179
208
  }
209
+ if (session.paused) this.applyBackpressure(session)
180
210
  return
181
211
  }
182
212
  }
183
213
 
184
- /** End the session a socket is attached to (explicit close from the view). */
185
- private end(session: HostedTerminal, notify: boolean): void {
214
+ /** End the session and close every socket still attached to it. */
215
+ private end(session: HostedTerminal): void {
186
216
  this.clearReap(session)
187
- if (this.sessions.delete(session.id) && notify) {
188
- if (session.pendingAuthFinish !== undefined) {
189
- const finish = session.pendingAuthFinish
190
- session.pendingAuthFinish = undefined
191
- try { finish([]) } catch { /* the connect already failed */ }
192
- }
217
+ this.sessions.delete(session.id)
218
+ if (session.pendingAuthFinish !== undefined) {
219
+ const finish = session.pendingAuthFinish
220
+ session.pendingAuthFinish = undefined
221
+ try { finish([]) } catch { /* the connect already failed */ }
222
+ }
223
+ for (const ws of [...session.sockets]) {
224
+ session.sockets.delete(ws)
225
+ try { ws.close(1000) } catch { /* already closed */ }
193
226
  }
194
227
  try { session.shell?.close() } catch { /* channel gone */ }
195
228
  }
@@ -197,6 +230,8 @@ export class TerminalSessionRegistry {
197
230
  /** Mark a session exited and keep it briefly so a reattaching view sees it. */
198
231
  private finish(session: HostedTerminal, code: number | null, error?: string): void {
199
232
  if (session.exited) return
233
+ const tail = session.decoder.end()
234
+ if (tail !== '') this.pushOutput(session, tail)
200
235
  session.exited = true
201
236
  session.exit = { code, error }
202
237
  this.send(session, { type: 'exit', code, error })
@@ -210,40 +245,80 @@ export class TerminalSessionRegistry {
210
245
  this.scheduleReap(session, this.exitGraceMs)
211
246
  }
212
247
 
213
- /** Append output to the replay buffer, trimmed to the byte cap. */
248
+ /** Keep at most `maxBytes` from the tail of `data` on a valid UTF-8 boundary. */
249
+ private trimTailToUtf8Bytes(data: string, maxBytes: number): { text: string; bytes: number } {
250
+ if (maxBytes <= 0) return { text: '', bytes: 0 }
251
+ const buf = Buffer.from(data, 'utf8')
252
+ if (buf.byteLength <= maxBytes) return { text: data, bytes: buf.byteLength }
253
+ let start = buf.byteLength - maxBytes
254
+ while (start < buf.byteLength && (buf[start]! & 0xc0) === 0x80) start += 1
255
+ const tail = buf.subarray(start)
256
+ return { text: tail.toString('utf8'), bytes: tail.byteLength }
257
+ }
258
+
259
+ /** Append output to the O(1) replay ring, trimmed to the byte cap. */
214
260
  private pushOutput(session: HostedTerminal, data: string): void {
215
- session.buffer.push(data)
216
- session.bufferBytes += Buffer.byteLength(data)
217
- while (session.bufferBytes > this.maxBufferBytes && session.buffer.length > 1) {
218
- const dropped = session.buffer.shift()
219
- session.bufferBytes -= Buffer.byteLength(dropped ?? '')
261
+ const chunkBytes = Buffer.byteLength(data, 'utf8')
262
+ if (chunkBytes > this.maxBufferBytes) {
263
+ const trimmed = this.trimTailToUtf8Bytes(data, this.maxBufferBytes)
264
+ session.buffer = trimmed.text === '' ? [] : [trimmed.text]
265
+ session.bufferChunkBytes = trimmed.text === '' ? [] : [trimmed.bytes]
266
+ session.bufferHead = 0
267
+ session.bufferBytes = trimmed.bytes
268
+ } else {
269
+ session.buffer.push(data)
270
+ session.bufferChunkBytes.push(chunkBytes)
271
+ session.bufferBytes += chunkBytes
272
+ while (session.bufferBytes > this.maxBufferBytes && session.buffer.length - session.bufferHead > 1) {
273
+ session.bufferBytes -= session.bufferChunkBytes[session.bufferHead]!
274
+ session.bufferHead += 1
275
+ }
276
+ if (session.bufferHead >= 64 && session.bufferHead * 2 >= session.buffer.length) {
277
+ session.buffer = session.buffer.slice(session.bufferHead)
278
+ session.bufferChunkBytes = session.bufferChunkBytes.slice(session.bufferHead)
279
+ session.bufferHead = 0
280
+ }
220
281
  }
221
282
  this.send(session, { type: 'output', data })
222
283
  }
223
284
 
224
285
  /** Broadcast one frame to every attached socket, honoring backpressure. */
225
286
  private send(session: HostedTerminal, frame: TerminalServerFrame): void {
226
- for (const ws of session.sockets) this.sendTo(session, ws, frame)
287
+ const payload = JSON.stringify(frame)
288
+ for (const ws of session.sockets) this.sendPayload(session, ws, payload)
227
289
  this.applyBackpressure(session)
228
290
  }
229
291
 
230
- private sendTo(session: HostedTerminal, ws: WebSocket, frame: TerminalServerFrame): void {
292
+ private sendPayload(session: HostedTerminal, ws: WebSocket, payload: string): void {
231
293
  if (ws.readyState !== WebSocket.OPEN) return
232
- try { ws.send(JSON.stringify(frame)) } catch { /* socket raced away */ }
294
+ try {
295
+ // Attach the drain callback only when buffered output is near/above the
296
+ // low-water mark so uncontested frames incur zero callback overhead.
297
+ if ((session.paused || ws.bufferedAmount + payload.length > BACKPRESSURE_LOW_WATER) && session.onDrain !== undefined) {
298
+ ws.send(payload, session.onDrain)
299
+ } else {
300
+ ws.send(payload)
301
+ }
302
+ } catch { /* socket raced away */ }
233
303
  }
234
304
 
235
305
  /** Pause while any attached socket is backed up; resume once all drained. */
236
306
  private applyBackpressure(session: HostedTerminal): void {
237
307
  const shell = session.shell
238
- if (shell === undefined) return
308
+ if (shell === undefined || session.exited) return
239
309
  let high = false
240
310
  let low = true
241
311
  for (const ws of session.sockets) {
242
312
  if (ws.bufferedAmount > BACKPRESSURE_HIGH_WATER) high = true
243
313
  if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) low = false
244
314
  }
245
- if (high) shell.pause()
246
- else if (low) shell.resume()
315
+ if (high && !session.paused) {
316
+ session.paused = true
317
+ shell.pause()
318
+ } else if (low && session.paused) {
319
+ session.paused = false
320
+ shell.resume()
321
+ }
247
322
  }
248
323
 
249
324
  /** Answer a keyboard-interactive challenge through whoever is attached. */
@@ -264,7 +339,7 @@ export class TerminalSessionRegistry {
264
339
  const timer = setTimeout(() => {
265
340
  session.reapTimer = undefined
266
341
  if (session.sockets.size > 0) return
267
- this.end(session, false)
342
+ this.end(session)
268
343
  }, delayMs)
269
344
  // Never hold the host process open for an idle terminal.
270
345
  ;(timer as { unref?: () => void }).unref?.()
@@ -98,6 +98,11 @@ export async function startTunnel(
98
98
  destroyQuietly(socket)
99
99
  return
100
100
  }
101
+ if (socket.destroyed) {
102
+ try { stream.close() } catch { /* gone */ }
103
+ destroyQuietly(stream)
104
+ return
105
+ }
101
106
  // Both ends of the pipe can die independently; destroy the pair so an
102
107
  // unhandled 'error' event can never crash the host process.
103
108
  const destroy = (): void => {
@@ -118,6 +123,8 @@ export async function startTunnel(
118
123
  abortTunnel(engine, id)
119
124
  }
120
125
  })
126
+ // Guard the pooled connection from sweepPool or sibling teardown while binding.
127
+ record.inFlight += 1
121
128
  try {
122
129
  await new Promise<void>((resolve, reject) => {
123
130
  server.once('error', reject)
@@ -127,11 +134,14 @@ export async function startTunnel(
127
134
  })
128
135
  })
129
136
  } catch (error) {
137
+ record.inFlight -= 1
130
138
  // Roll back: never leave an unpinned orphan connection behind.
131
139
  if (!record.pinned && record.inFlight === 0) disposeRecord(engine, alias, record)
132
140
  throw error
133
141
  }
134
142
  record.pinned = true
143
+ record.inFlight -= 1
144
+ server.on('error', () => { abortTunnel(engine, id) })
135
145
  const address = server.address()
136
146
  info.localPort = typeof address === 'object' && address !== null ? address.port : 0
137
147
  info.state = 'forwarding'
@@ -175,8 +185,16 @@ export function stopTunnel(engine: TunnelEngine, id: string): boolean {
175
185
  // replaced (e.g. after a broken-connection recycle) is ended directly.
176
186
  const shared = [...engine.tunnels.values()].some(candidate => candidate.record === tunnel.record)
177
187
  if (!shared) {
178
- if (engine.pool.get(tunnel.alias) === tunnel.record) disposeRecord(engine, tunnel.alias, tunnel.record)
179
- else endRecordChain(tunnel.record)
188
+ if (engine.pool.get(tunnel.alias) === tunnel.record) {
189
+ if (!tunnel.record.broken && tunnel.record.inFlight > 0) {
190
+ tunnel.record.pinned = false
191
+ tunnel.record.idleAt = Date.now()
192
+ } else {
193
+ disposeRecord(engine, tunnel.alias, tunnel.record)
194
+ }
195
+ } else {
196
+ endRecordChain(tunnel.record)
197
+ }
180
198
  }
181
199
  return true
182
200
  }
package/src/engine.ts CHANGED
@@ -12,6 +12,8 @@ import {
12
12
  DEFAULTS,
13
13
  execCommand,
14
14
  disposeRecord,
15
+ invalidateAlias,
16
+ markPoolDisposed,
15
17
  sweepPool,
16
18
  type EngineOptions,
17
19
  type KeyboardInteractiveHandler,
@@ -151,6 +153,7 @@ export class SshEngine {
151
153
  * connection — the next operation re-connects from the current config.
152
154
  */
153
155
  dropAlias(alias: string): void {
156
+ invalidateAlias(this, alias)
154
157
  stopAllTunnels(this, alias)
155
158
  disposeRecord(this, alias)
156
159
  }
@@ -172,6 +175,7 @@ export class SshEngine {
172
175
 
173
176
  /** Close every pooled connection and tunnel. */
174
177
  dispose(): void {
178
+ markPoolDisposed(this)
175
179
  if (this.sweepTimer !== undefined) clearInterval(this.sweepTimer)
176
180
  for (const id of [...this.tunnels.keys()]) stopTunnel(this, id)
177
181
  for (const alias of [...this.pool.keys()]) disposeRecord(this, alias)
package/src/index.ts CHANGED
@@ -238,37 +238,41 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
238
238
  let disposeService: (() => void) | undefined
239
239
 
240
240
  // Register (or drop) every surface to match the resolved config. Each group
241
- // is kept under one disposer: re-registering first tears the old one down
242
- // so duplicate-name registrations never throw.
241
+ // stays mounted while its own condition holds, so unrelated volatile edits
242
+ // (such as terminalFontFamily or connectTimeoutMs) never tear down routes
243
+ // and kill live terminal sessions.
243
244
  const sync = (): void => {
244
245
  // A settings edit reaches this instance without a remount; apply the
245
246
  // connection ceiling before re-deriving the surfaces so connections opened
246
247
  // by the request that follows use the new value.
247
248
  engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS))
248
249
  const value = resolve()
249
- if (disposeSection !== undefined) {
250
+ const wantSection = value.enabled && value.announceToAgent
251
+ if (!wantSection && disposeSection !== undefined) {
250
252
  disposeSection()
251
253
  disposeSection = undefined
252
254
  }
253
- if (disposeRoutes !== undefined) {
254
- disposeRoutes()
255
- disposeRoutes = undefined
255
+ if (!value.enabled) {
256
+ if (disposeRoutes !== undefined) {
257
+ disposeRoutes()
258
+ disposeRoutes = undefined
259
+ }
260
+ if (disposeTools !== undefined) {
261
+ disposeTools()
262
+ disposeTools = undefined
263
+ }
264
+ // The service follows the master switch only: a settings edit that keeps
265
+ // the plugin on leaves the provision — and every dependent's inject scope —
266
+ // alone, so an unrelated field does not reboot consumers.
267
+ if (disposeService !== undefined) {
268
+ // Unproviding releases every dependent fiber that injected the service;
269
+ // each of those scopes unloads with it.
270
+ disposeService()
271
+ disposeService = undefined
272
+ }
273
+ return
256
274
  }
257
- if (disposeTools !== undefined) {
258
- disposeTools()
259
- disposeTools = undefined
260
- }
261
- // The service follows the master switch only: a settings edit that keeps
262
- // the plugin on leaves the provision — and every dependent's inject scope —
263
- // alone, so an unrelated field does not reboot consumers.
264
- if (disposeService !== undefined && !value.enabled) {
265
- // Unproviding releases every dependent fiber that injected the service;
266
- // each of those scopes unloads with it.
267
- disposeService()
268
- disposeService = undefined
269
- }
270
- if (!value.enabled) return
271
- if (value.announceToAgent) {
275
+ if (wantSection && disposeSection === undefined) {
272
276
  disposeSection = ctx.systemPrompt.section({
273
277
  name: 'plugin:dsh-ssh',
274
278
  order: SECTION_ORDER,
@@ -279,27 +283,31 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
279
283
  text: visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE),
280
284
  })
281
285
  }
282
- disposeRoutes = ctx.effect(
283
- () => {
284
- const disposers = routes.map(route => ctx.webServer.register(route))
285
- const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
286
- return () => {
287
- for (const dispose of disposers) dispose()
288
- upgradeDisposer()
289
- // Dropping the routes also ends the terminal sessions they served:
290
- // a live shell must not outlive the surface that can reach it.
291
- terminalSessions.dispose()
292
- }
293
- },
294
- 'dsh-ssh: routes',
295
- )
296
- disposeTools = ctx.effect(
297
- () => {
298
- const disposers = tools.map(tool => ctx.tools.register(tool))
299
- return () => { for (const dispose of disposers) dispose() }
300
- },
301
- 'dsh-ssh: tools',
302
- )
286
+ if (disposeRoutes === undefined) {
287
+ disposeRoutes = ctx.effect(
288
+ () => {
289
+ const disposers = routes.map(route => ctx.webServer.register(route))
290
+ const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
291
+ return () => {
292
+ for (const dispose of disposers) dispose()
293
+ upgradeDisposer()
294
+ // Dropping the routes also ends the terminal sessions they served:
295
+ // a live shell must not outlive the surface that can reach it.
296
+ terminalSessions.dispose()
297
+ }
298
+ },
299
+ 'dsh-ssh: routes',
300
+ )
301
+ }
302
+ if (disposeTools === undefined) {
303
+ disposeTools = ctx.effect(
304
+ () => {
305
+ const disposers = tools.map(tool => ctx.tools.register(tool))
306
+ return () => { for (const dispose of disposers) dispose() }
307
+ },
308
+ 'dsh-ssh: tools',
309
+ )
310
+ }
303
311
  if (disposeService === undefined && typeof (ctx as { provide?: unknown }).provide === 'function') {
304
312
  disposeService = ctx.provide(DSH_SSH_SERVICE, createService(engine))
305
313
  }