dsh-remote-go 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +87 -7
  2. package/client.js +8763 -0
  3. package/cordis.patch.yml +3 -0
  4. package/index.js +4 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +77 -3
  8. package/src/admission.js +43 -0
  9. package/src/api.js +536 -0
  10. package/src/atomic-json.js +225 -0
  11. package/src/bootstrap.js +113 -0
  12. package/src/connect-log.js +176 -0
  13. package/src/connect-pipeline.js +1900 -0
  14. package/src/connect-progress.js +155 -0
  15. package/src/constants.js +93 -0
  16. package/src/diagnostics.js +160 -0
  17. package/src/download-jobs.js +234 -0
  18. package/src/errors.js +412 -0
  19. package/src/host-lifecycle.js +604 -0
  20. package/src/host-registry.js +217 -0
  21. package/src/host-runtime.js +127 -0
  22. package/src/host-view.js +75 -0
  23. package/src/index.js +206 -0
  24. package/src/key-files.js +54 -0
  25. package/src/known-hosts.js +133 -0
  26. package/src/layout.js +53 -0
  27. package/src/local-download.js +381 -0
  28. package/src/local-ssh.js +27 -0
  29. package/src/local-version.js +88 -0
  30. package/src/node-runtime.js +521 -0
  31. package/src/probe.js +101 -0
  32. package/src/prompts.js +229 -0
  33. package/src/redact.js +68 -0
  34. package/src/remote-files.js +71 -0
  35. package/src/remote-path.js +137 -0
  36. package/src/remote-proc.js +343 -0
  37. package/src/remote-proxy.js +815 -0
  38. package/src/remote-web.js +751 -0
  39. package/src/request-trust.js +89 -0
  40. package/src/secrets.js +109 -0
  41. package/src/service.js +459 -0
  42. package/src/settings.js +163 -0
  43. package/src/ssh-config.js +271 -0
  44. package/src/ssh.js +731 -0
  45. package/src/store.js +193 -0
  46. package/src/tools.js +386 -0
  47. package/src/tunnel.js +132 -0
  48. package/src/util.js +153 -0
  49. package/src/version.js +103 -0
  50. package/src/webapp.js +43 -0
  51. package/vendor/THIRD_PARTY_NOTICES.md +36 -0
  52. package/vendor/ssh2.bundle.cjs +25 -0
@@ -0,0 +1,604 @@
1
+ /**
2
+ * Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path; the reconnect timer gets a callback, so this never imports the pipeline.
3
+ */
4
+ import {
5
+ DEFAULT_IDLE_MINUTES,
6
+ REMOTE_EPISODE_COOLDOWN_MS,
7
+ REMOTE_HEARTBEAT_DEFAULT_SEC,
8
+ REMOTE_HEARTBEAT_MAX_SEC,
9
+ REMOTE_HEARTBEAT_MIN_SEC,
10
+ REMOTE_TUNNEL_REPAIR_SETTLE_MS,
11
+ REMOTE_UNREACHABLE_FAILURES,
12
+ } from './constants.js'
13
+ import { errors, toErrorView } from './errors.js'
14
+ import { emptyRemote } from './host-runtime.js'
15
+ import { layoutForRuntime } from './layout.js'
16
+ import { cancelConflict, cancelHostKeyPrompt } from './prompts.js'
17
+ import { isUiUp } from './remote-proc.js'
18
+ import { commandMatchesProfile } from './remote-web.js'
19
+ import { isPid, messageOf, randomDelay } from './util.js'
20
+
21
+ export function cancelReconnect(runtime) {
22
+ if (runtime.reconnectTimer) {
23
+ clearTimeout(runtime.reconnectTimer)
24
+ runtime.reconnectTimer = null
25
+ }
26
+ }
27
+
28
+ export function cancelIdleStop(runtime) {
29
+ if (runtime.idleTimer) {
30
+ clearTimeout(runtime.idleTimer)
31
+ runtime.idleTimer = null
32
+ }
33
+ }
34
+
35
+ /**
36
+ * One-shot link actions (a local restart, a remote re-attach, a tunnel rebuild) share a
37
+ * token so a disconnect, a dropped transport or a newer action can invalidate an older one:
38
+ * an action must never write state on top of whatever replaced it.
39
+ * @param {object} runtime - host runtime.
40
+ * @param {string} kind - `restart`, `reattach`, `repair` or `stop`.
41
+ * @returns {number} the token that owns the action.
42
+ */
43
+ export function beginLinkWork(runtime, kind) {
44
+ runtime.linkToken = (Number(runtime.linkToken) || 0) + 1
45
+ runtime.linkBusy = kind
46
+ return runtime.linkToken
47
+ }
48
+
49
+ export function isLinkWorkCurrent(runtime, token) {
50
+ return runtime.linkToken === token
51
+ }
52
+
53
+ export function endLinkWork(runtime, token) {
54
+ if (!isLinkWorkCurrent(runtime, token)) return
55
+ runtime.linkBusy = null
56
+ }
57
+
58
+ /** Invalidate whatever one-shot action was running; safe when there is none. */
59
+ export function cancelLinkWork(runtime) {
60
+ runtime.linkToken = (Number(runtime.linkToken) || 0) + 1
61
+ runtime.linkBusy = null
62
+ }
63
+
64
+ /** Milliseconds between liveness probes, from settings (default 30s, disabled allowed). */
65
+ export function remoteHeartbeatIntervalSec(ctx) {
66
+ const raw = ctx.settings()?.remoteHeartbeat
67
+ const seconds = Number(raw?.intervalSec)
68
+ if (!Number.isFinite(seconds)) return REMOTE_HEARTBEAT_DEFAULT_SEC
69
+ return Math.min(REMOTE_HEARTBEAT_MAX_SEC, Math.max(REMOTE_HEARTBEAT_MIN_SEC, Math.round(seconds)))
70
+ }
71
+
72
+ function cancelRemoteCheck(runtime) {
73
+ if (runtime.remoteCheckTimer) {
74
+ clearTimeout(runtime.remoteCheckTimer)
75
+ runtime.remoteCheckTimer = null
76
+ }
77
+ }
78
+
79
+ /** Stop probing: called on connect, disconnect, re-attach and shutdown. */
80
+ export function stopRemoteHeartbeat(runtime) {
81
+ if (runtime.heartbeatTimer) {
82
+ clearInterval(runtime.heartbeatTimer)
83
+ runtime.heartbeatTimer = null
84
+ }
85
+ cancelRemoteCheck(runtime)
86
+ runtime.remoteFailures = 0
87
+ runtime.remoteEpisode = false
88
+ runtime.episodeSource = null
89
+ // A new attach starts a new episode budget; the cooldown only exists to damp one connection.
90
+ runtime.episodeCooldownUntil = 0
91
+ }
92
+
93
+ /** Start the light liveness probe for a host that just became connected. */
94
+ export function startRemoteHeartbeat(ctx, runtime) {
95
+ stopRemoteHeartbeat(runtime)
96
+ const enabled = ctx.settings()?.remoteHeartbeat?.enabled !== false
97
+ if (!enabled) {
98
+ ctx.progress.log(runtime, 'debug', 'remote heartbeat: disabled by settings')
99
+ return
100
+ }
101
+ const intervalSec = remoteHeartbeatIntervalSec(ctx)
102
+ runtime.heartbeatTimer = setInterval(() => {
103
+ void remoteHeartbeatTick(ctx, runtime)
104
+ }, intervalSec * 1000)
105
+ runtime.heartbeatTimer.unref?.()
106
+ ctx.progress.log(runtime, 'debug', `remote heartbeat: probing every ${intervalSec}s`)
107
+ }
108
+
109
+ /** A host is watchable only while it is really up and no one-shot action owns the link. */
110
+ function watchable(ctx, runtime) {
111
+ return (
112
+ ctx.state.disposed !== true &&
113
+ runtime.desired === 'connected' &&
114
+ runtime.status === 'connected' &&
115
+ runtime.linkBusy === null &&
116
+ runtime.ssh?.connected === true &&
117
+ runtime.tunnel !== null
118
+ )
119
+ }
120
+
121
+ /**
122
+ * Open a liveness episode at most once. Transient reports (a proxy/tunnel failure) are
123
+ * coalesced: after a confirmed-healthy episode the same kind of report is ignored for a
124
+ * cooldown window, so a flapping tunnel cannot emit suspected/recovered on every request.
125
+ * Returns whether a new episode was opened.
126
+ */
127
+ function beginRemoteEpisode(ctx, runtime, source) {
128
+ if (runtime.remoteEpisode === true) return false
129
+ const transient = source === 'proxy' || source === 'tunnel'
130
+ if (transient && Date.now() < (Number(runtime.episodeCooldownUntil) || 0)) {
131
+ ctx.progress.log(runtime, 'debug', `remote-unreachable reported again (${source}); episode cooldown, ignoring`)
132
+ return false
133
+ }
134
+ runtime.remoteEpisode = true
135
+ runtime.episodeSource = source
136
+ ctx.progress.log(runtime, 'debug', `remote-unreachable suspected (${source}); confirming with probes`)
137
+ ctx.onRemoteUnreachable?.(runtime, { phase: 'suspected', source })
138
+ return true
139
+ }
140
+
141
+ /**
142
+ * Reset the failure streak; report the recovery once when an episode was open. A transient
143
+ * episode also rebuilds the local listener: the remote answering the probe while the page
144
+ * got a 502 usually means the tunnel, not the remote, is what broke.
145
+ */
146
+ async function clearRemoteEpisode(ctx, runtime, source) {
147
+ const wasOpen = runtime.remoteEpisode === true
148
+ const transient = runtime.episodeSource === 'proxy' || runtime.episodeSource === 'tunnel'
149
+ runtime.remoteEpisode = false
150
+ runtime.remoteFailures = 0
151
+ if (!wasOpen) return
152
+ runtime.episodeSource = null
153
+ if (transient) {
154
+ runtime.episodeCooldownUntil = Date.now() + REMOTE_EPISODE_COOLDOWN_MS
155
+ // The SSH probe only proves the remote side answers. Ask the local listener first: if it
156
+ // still serves, a single failed upstream connection is not a broken tunnel and rebuilding
157
+ // would drop live WebSockets for nothing.
158
+ let healthy = false
159
+ try {
160
+ healthy = (await ctx.deps.tunnelProbe?.(runtime.tunnel?.localPort ?? null)) === true
161
+ } catch {
162
+ // swallow-ok: a probe error means "not healthy"; the rebuild path reports its own failure
163
+ }
164
+ if (healthy) {
165
+ ctx.progress.log(runtime, 'debug', 'the local tunnel still answers; keeping the listener')
166
+ } else {
167
+ try {
168
+ const repaired = await ctx.repairTunnel?.(runtime)
169
+ if (repaired && repaired.ok !== true) {
170
+ ctx.progress.log(runtime, 'debug', `tunnel rebuild skipped (${repaired.reason ?? 'unknown'})`)
171
+ }
172
+ } catch (error) {
173
+ // swallow-ok: a failed repair is reported by the helper; the episode still recovers
174
+ ctx.progress.log(runtime, 'warn', 'tunnel rebuild failed:', messageOf(error))
175
+ }
176
+ }
177
+ }
178
+ ctx.progress.log(runtime, 'info', `remote heartbeat: the remote UI answers again (${source})`)
179
+ if (!watchable(ctx, runtime)) return
180
+ ctx.onRemoteUnreachable?.(runtime, { phase: 'recovered', source })
181
+ }
182
+
183
+ function scheduleRemoteCheck(ctx, runtime, source, delayMs) {
184
+ if (runtime.remoteCheckTimer) return
185
+ runtime.remoteCheckTimer = setTimeout(() => {
186
+ runtime.remoteCheckTimer = null
187
+ void checkRemoteNow(ctx, runtime, source)
188
+ }, delayMs)
189
+ runtime.remoteCheckTimer.unref?.()
190
+ }
191
+
192
+ /**
193
+ * Probe the connected host once and feed the consecutive-failure counter. One
194
+ * failed request is not a restart: the counter has to reach
195
+ * {@link REMOTE_UNREACHABLE_FAILURES} before a re-attach is requested.
196
+ */
197
+ async function checkRemoteNow(ctx, runtime, source) {
198
+ if (!watchable(ctx, runtime) || typeof ctx.deps.remoteStatus !== 'function') return
199
+ const ssh = runtime.ssh
200
+ const port = runtime.remote.port
201
+ let status = null
202
+ try {
203
+ status = await ctx.deps.remoteStatus(ssh, port)
204
+ } catch {
205
+ // swallow-ok: an unreachable probe is a failed probe, handled by the same counter
206
+ status = null
207
+ }
208
+ // The transport may have gone away while the probe was in flight; the close handler owns that.
209
+ if (!watchable(ctx, runtime) || runtime.ssh !== ssh) return
210
+ if (isUiUp(status)) {
211
+ await clearRemoteEpisode(ctx, runtime, source)
212
+ return
213
+ }
214
+ runtime.remoteFailures = (Number(runtime.remoteFailures) || 0) + 1
215
+ ctx.progress.log(
216
+ runtime,
217
+ 'debug',
218
+ `remote heartbeat: probe failed (HTTP ${status ?? 'none'}), ${runtime.remoteFailures}/${REMOTE_UNREACHABLE_FAILURES} (${source})`,
219
+ )
220
+ beginRemoteEpisode(ctx, runtime, source)
221
+ if (runtime.remoteFailures < REMOTE_UNREACHABLE_FAILURES) {
222
+ scheduleRemoteCheck(ctx, runtime, source, ctx.timers.remoteRecheckMs)
223
+ return
224
+ }
225
+ ctx.progress.log(
226
+ runtime,
227
+ 'warn',
228
+ `remote-unreachable: ${runtime.remoteFailures} consecutive probes failed (${source}); re-attaching`,
229
+ )
230
+ ctx.onRemoteUnreachable?.(runtime, {
231
+ phase: 'confirmed',
232
+ source,
233
+ failures: runtime.remoteFailures,
234
+ })
235
+ cancelRemoteCheck(runtime)
236
+ ctx.requestReattach?.(runtime, { reason: `probe-failed-${runtime.remoteFailures}`, source })
237
+ }
238
+
239
+ /** One scheduled heartbeat tick. */
240
+ export async function remoteHeartbeatTick(ctx, runtime) {
241
+ if (!watchable(ctx, runtime)) return
242
+ if (runtime.remoteCheckTimer) return
243
+ await checkRemoteNow(ctx, runtime, 'heartbeat')
244
+ }
245
+
246
+ /**
247
+ * A proxy or tunnel failure was observed: report the episode once and confirm it
248
+ * with probes instead of treating one failed request as a remote restart.
249
+ */
250
+ export function noteRemoteUnreachable(ctx, runtime, source) {
251
+ if (!watchable(ctx, runtime)) return
252
+ if (!beginRemoteEpisode(ctx, runtime, source)) return
253
+ scheduleRemoteCheck(ctx, runtime, source, ctx.timers.remoteConfirmDelayMs)
254
+ }
255
+
256
+ /**
257
+ * Arm the next reconnect attempt, or give up once the configured budget is spent.
258
+ */
259
+ export function scheduleReconnect(ctx, runtime, onDue) {
260
+ cancelReconnect(runtime)
261
+ // A retry only makes sense while the user still wants the link: a disconnect, a host
262
+ // removal or a shutdown that raced the timer must not resurrect the connection.
263
+ if (ctx.state.disposed === true || runtime.desired !== 'connected') {
264
+ ctx.progress.set(runtime, { status: 'disconnected' })
265
+ return
266
+ }
267
+ const settings = ctx.settings()
268
+ if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled) {
269
+ ctx.progress.set(runtime, { status: 'disconnected' })
270
+ return
271
+ }
272
+ const maxAttempts = settings.autoReconnect.maxAttempts
273
+ if (runtime.reconnectAttempts >= maxAttempts) {
274
+ runtime.status = 'error'
275
+ runtime.error = toErrorView(
276
+ errors.network({
277
+ zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
278
+ en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
279
+ }),
280
+ )
281
+ runtime.progress = null
282
+ ctx.emitState()
283
+ return
284
+ }
285
+ runtime.reconnectAttempts += 1
286
+ const delay = randomDelay(
287
+ settings.autoReconnect.baseDelayMs,
288
+ settings.autoReconnect.baseDelayMs * 2 ** Math.min(runtime.reconnectAttempts, 4),
289
+ )
290
+ runtime.progress = { code: 'reconnecting', params: { attempt: runtime.reconnectAttempts, max: maxAttempts } }
291
+ ctx.progress.log(
292
+ runtime,
293
+ 'warn',
294
+ `link lost; retrying in ${Math.round(delay / 100) / 10}s (attempt ${runtime.reconnectAttempts}/${maxAttempts})`,
295
+ )
296
+ ctx.emitState()
297
+ runtime.reconnectTimer = setTimeout(() => {
298
+ runtime.reconnectTimer = null
299
+ onDue()
300
+ }, delay)
301
+ // A pending retry must never keep the host process alive on its own.
302
+ runtime.reconnectTimer.unref?.()
303
+ }
304
+
305
+ function scheduleIdleStop(ctx, runtime) {
306
+ cancelIdleStop(runtime)
307
+ const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES)
308
+ runtime.idleTimer = setTimeout(() => {
309
+ runtime.idleTimer = null
310
+ void stopRemoteForIdle(ctx, runtime)
311
+ }, minutes * 60_000)
312
+ runtime.idleTimer.unref?.()
313
+ }
314
+
315
+ /**
316
+ * Best-effort stop of the remote web for the idle policy, then drop the transport.
317
+ *
318
+ * The teardown that armed this timer clears `facts` and `remote`, so the stop has to use the
319
+ * home and pid remembered before that clearing: the old fallback built a layout with a
320
+ * literal `~`, whose `kill -0` is a no-op that still reported success (H1).
321
+ *
322
+ * The timer is a *policy for an idle host*, never authority over a live link: the user may
323
+ * have connected again (the timer would otherwise kill the link just brought up), and a pid
324
+ * that answers `/proc` is not proof it is still the process this connection started
325
+ * (review: idle-timer zombie / pid reuse). Shutdown is the one caller that deliberately
326
+ * overrides the "still wanted" guard, because it is stopping the whole host process.
327
+ *
328
+ * @param {object} ctx - service context.
329
+ * @param {object} runtime - host runtime that went idle.
330
+ * @param {{ shutdown?: boolean }} [options]
331
+ * @returns {Promise<{ ok: boolean, reason?: string }>} the stop verdict (best effort).
332
+ */
333
+ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
334
+ // A live link wins over the idle policy, whichever timer fired it. This is what keeps a
335
+ // manual reconnect from being torn down by the timer armed before it.
336
+ const linkLive = runtime.desired === 'connected' || runtime.status === 'connected' || runtime.tunnel !== null
337
+ if (linkLive && options.shutdown !== true) {
338
+ ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again')
339
+ return { ok: false, reason: 'still-wanted' }
340
+ }
341
+ // The transport this call owns: the identity proof below awaits, and the user may connect
342
+ // in that window. Only this session may be released afterwards, never the new one.
343
+ const capturedSsh = runtime.ssh
344
+ const stillWanted = () =>
345
+ runtime.ssh !== capturedSsh ||
346
+ runtime.desired === 'connected' ||
347
+ runtime.status === 'connected' ||
348
+ runtime.tunnel !== null
349
+ try {
350
+ if (capturedSsh?.connected !== true) return { ok: false, reason: 'no-transport' }
351
+ const home = runtime.facts?.home ?? runtime.remoteHome ?? null
352
+ if (typeof home !== 'string' || home.trim() === '') {
353
+ ctx.progress.log(runtime, 'warn', 'idle stop skipped: the remote home directory is unknown')
354
+ return { ok: false, reason: 'no-home' }
355
+ }
356
+ const layout = layoutForRuntime(runtime)
357
+ const pid = Number(runtime.remote.pid ?? runtime.remotePid ?? 0)
358
+ // Without a pid there is nothing this policy may signal: `stopRemoteWeb` would fall back
359
+ // to the run registry and could stop an instance this connection did not launch.
360
+ if (!isPid(pid)) return { ok: false, reason: 'pid-unknown' }
361
+ // Same `/proc` identity proof the explicit stop uses: a reused pid, another DSH home or
362
+ // another profile is not this connection's process and must not be signalled.
363
+ const proof = await proveIdleStopTarget(ctx, runtime, pid, layout)
364
+ if (proof.ok !== true) {
365
+ ctx.progress.log(runtime, 'warn', `idle stop skipped: ${proof.reason}`)
366
+ return { ok: false, reason: proof.reason }
367
+ }
368
+ // The user may have connected while the identity was read: the link wins again.
369
+ if (options.shutdown !== true && stillWanted()) {
370
+ ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again')
371
+ return { ok: false, reason: 'still-wanted' }
372
+ }
373
+ const stopped = await ctx.deps.stopWeb(capturedSsh, layout, { pid })
374
+ if (stopped?.ok !== true) {
375
+ ctx.progress.log(
376
+ runtime,
377
+ 'warn',
378
+ `idle stop did not confirm (${stopped?.reason ?? 'unknown'}); the remote may still be running`,
379
+ )
380
+ return { ok: false, reason: stopped?.reason ?? 'not-confirmed' }
381
+ }
382
+ runtime.remotePid = null
383
+ return { ok: true }
384
+ } catch (error) {
385
+ // swallow-ok: the idle stop is best effort; its failure is only a warning and the timer
386
+ // is already gone, so the host stays idle either way
387
+ ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error))
388
+ return { ok: false, reason: 'error' }
389
+ } finally {
390
+ // Release only the transport this call captured: when a new connection owns the link by
391
+ // now, its session is not ours to dispose.
392
+ if (runtime.ssh === capturedSsh) await disposeSsh(runtime)
393
+ }
394
+ }
395
+
396
+ /** The `/proc` identity proof for the process the idle policy is about to stop. */
397
+ async function proveIdleStopTarget(ctx, runtime, pid, layout) {
398
+ const bound = Number(runtime.bound?.pid) === pid ? runtime.bound : null
399
+ const launched = runtime.launched instanceof Map ? runtime.launched.get(pid) : null
400
+ const proof = bound ?? launched
401
+ if (!proof) return { ok: false, reason: 'not-owned' }
402
+ let identity = null
403
+ try {
404
+ identity = await ctx.deps.processIdentity(runtime.ssh, pid)
405
+ } catch {
406
+ // swallow-ok: an unreadable identity means "cannot prove it is ours", so no signal
407
+ return { ok: false, reason: 'identity-unreadable' }
408
+ }
409
+ if (identity?.ok !== true) {
410
+ return {
411
+ ok: false,
412
+ reason: identity?.reason === 'missing' ? 'identity-missing' : `identity-${identity?.reason ?? 'unknown'}`,
413
+ }
414
+ }
415
+ if (typeof proof.startTime === 'string' && proof.startTime !== '' && identity.startTime !== proof.startTime) {
416
+ return { ok: false, reason: 'pid-reused' }
417
+ }
418
+ if (identity.dshHome !== '' && identity.dshHome !== layout.dshHome) {
419
+ return { ok: false, reason: 'dsh-home-mismatch' }
420
+ }
421
+ const profile = runtime.remote.profile ?? runtime.remoteProfile ?? null
422
+ if (typeof profile === 'string' && profile !== '' && !commandMatchesProfile(identity.command, profile)) {
423
+ return { ok: false, reason: 'profile-mismatch' }
424
+ }
425
+ return { ok: true }
426
+ }
427
+
428
+ export async function closeTunnel(runtime) {
429
+ const tunnel = runtime.tunnel
430
+ runtime.tunnel = null
431
+ // `localPort` is a view of the live listener: a closed tunnel must not leave a stale port
432
+ // behind (the proxy and diagnostics read this field).
433
+ runtime.remote.localPort = null
434
+ if (tunnel) {
435
+ try {
436
+ await tunnel.close()
437
+ } catch {}
438
+ }
439
+ }
440
+
441
+ export async function disposeSsh(runtime) {
442
+ const ssh = runtime.ssh
443
+ runtime.ssh = null
444
+ const jump = runtime.jumpSsh
445
+ runtime.jumpSsh = null
446
+ if (ssh) {
447
+ try {
448
+ await ssh.dispose()
449
+ } catch {}
450
+ }
451
+ if (jump) {
452
+ try {
453
+ await jump.dispose()
454
+ } catch {}
455
+ }
456
+ }
457
+
458
+ /**
459
+ * The single teardown path. `stopRemote` also stops the remote web (keep-alive
460
+ * `stop`), `keepSshForIdle` leaves the transport up for a fast resume, and
461
+ * `keepRemote` preserves the remote facts so the card still describes what is
462
+ * running on the other side.
463
+ */
464
+ /**
465
+ * Wait for an in-flight tunnel rebuild (if any) after the caller cancelled link work.
466
+ * The rebuild closes its own replacement in `finally` when its token is gone, so awaiting
467
+ * here is what makes disconnect / removeHost / shutdown leak-free. Bounded: a stuck rebuild
468
+ * must not delay teardown forever; its token is already cancelled, so it cannot publish.
469
+ * @param {object} ctx - service context.
470
+ * @param {object} runtime - host runtime.
471
+ */
472
+ async function settleTunnelRepair(ctx, runtime) {
473
+ const repair = runtime.tunnelRepair
474
+ if (!repair) return
475
+ const timeoutMs = Number(ctx.timers?.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS)
476
+ let timer = null
477
+ const timeout = new Promise((resolve) => {
478
+ timer = setTimeout(() => resolve('timeout'), Math.max(0, timeoutMs))
479
+ timer.unref?.()
480
+ })
481
+ try {
482
+ const outcome = await Promise.race([repair, timeout])
483
+ if (outcome === 'timeout') {
484
+ ctx.progress.log(runtime, 'warn', 'tunnel rebuild did not finish in time; abandoning it')
485
+ // The rebuild was cancelled via cancelLinkWork; its own finally will close any listener
486
+ // it creates. Clear the slot so teardown never waits on it again.
487
+ runtime.tunnelRepair = null
488
+ }
489
+ } catch {
490
+ // swallow-ok: the rebuild reports its own failure; teardown must still proceed
491
+ } finally {
492
+ if (timer !== null) clearTimeout(timer)
493
+ }
494
+ }
495
+
496
+ export async function teardownRuntime(ctx, runtime, options = {}) {
497
+ cancelConflict(runtime)
498
+ // A prompt parked on the transport that is about to go away can never be answered: settle
499
+ // it now instead of letting the connect promise wait for its 120s timeout (M1).
500
+ cancelHostKeyPrompt(runtime)
501
+ cancelLinkWork(runtime)
502
+ stopRemoteHeartbeat(runtime)
503
+ runtime.closing = true
504
+ cancelIdleStop(runtime)
505
+ // A tunnel rebuild owns a listener it may be creating right now. Cancel it (above), then
506
+ // wait for it to clean up: otherwise the listener would be assigned after this teardown.
507
+ await settleTunnelRepair(ctx, runtime)
508
+ // Remember where the remote lives before the facts below are cleared: the idle policy and
509
+ // a later stop still need the real home, never a literal `~` (H1).
510
+ if (typeof runtime.facts?.home === 'string' && runtime.facts.home.trim() !== '') {
511
+ runtime.remoteHome = runtime.facts.home
512
+ }
513
+ if (typeof runtime.remote.profile === 'string' && runtime.remote.profile !== '') {
514
+ runtime.remoteProfile = runtime.remote.profile
515
+ }
516
+ const boundPid = Number(runtime.remote.pid ?? 0)
517
+ if (isPid(boundPid)) runtime.remotePid = boundPid
518
+ let remoteStopped = false
519
+ if (options.stopRemote && runtime.ssh?.connected) {
520
+ try {
521
+ const result = await ctx.deps.stopWeb(runtime.ssh, layoutForRuntime(runtime), {
522
+ pid: runtime.remote.pid ?? undefined,
523
+ })
524
+ // Only a confirmed stop means the pid is gone; a refusal keeps the memory so a later
525
+ // stop can try again instead of reporting a process that never stopped.
526
+ remoteStopped = result?.ok === true
527
+ } catch (error) {
528
+ ctx.progress.log(runtime, 'warn', 'stop remote failed:', messageOf(error))
529
+ }
530
+ }
531
+ if (remoteStopped) runtime.remotePid = null
532
+ await closeTunnel(runtime)
533
+ if (!options.keepSshForIdle) await disposeSsh(runtime)
534
+ if (!options.keepRemote) {
535
+ runtime.remote = { ...emptyRemote(), version: runtime.remote.version }
536
+ runtime.token = null
537
+ runtime.facts = null
538
+ runtime.exchange = null
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Tear one host down and leave it idle: the keep-alive policy decides whether the
544
+ * remote web is stopped and whether the transport survives for a fast resume.
545
+ * `stopped` says the caller already stopped the remote web itself (the explicit
546
+ * "stop remote DSH" action): the policy must then neither arm an idle stop nor send
547
+ * a second stop signal. That second signal would be based on a pid captured several
548
+ * SSH round-trips earlier - a pid the action just proved is the right one (or that
549
+ * it is already gone), so re-signalling it is at best redundant and at worst kills
550
+ * an unrelated process after a pid reuse.
551
+ */
552
+ export async function disconnectHost(ctx, runtime, options = {}) {
553
+ ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`)
554
+ runtime.desired = 'idle'
555
+ cancelReconnect(runtime)
556
+ cancelLinkWork(runtime)
557
+ stopRemoteHeartbeat(runtime)
558
+ const policy = runtime.entry.keepAlive
559
+ const alreadyStopped = options.stopped === true
560
+ const stopRemote = alreadyStopped !== true && (options.stopRemote === true || policy === 'stop')
561
+ await teardownRuntime(ctx, runtime, {
562
+ stopRemote,
563
+ keepSshForIdle: policy === 'idle' && !stopRemote && !alreadyStopped,
564
+ })
565
+ runtime.status = 'disconnected'
566
+ runtime.phase = null
567
+ runtime.progress = null
568
+ runtime.remote.uiReady = false
569
+ runtime.remote.localPort = null
570
+ runtime.token = null
571
+ ctx.progress.set(runtime, {})
572
+ if (policy === 'idle' && !stopRemote && !alreadyStopped) scheduleIdleStop(ctx, runtime)
573
+ return { ok: true }
574
+ }
575
+
576
+ /**
577
+ * Stop every host's timers and release its transport. The `stop` keep-alive
578
+ * policy also stops the remote web so nothing is left running unowned.
579
+ */
580
+ export async function shutdownAll(ctx) {
581
+ for (const runtime of ctx.state.runtimes.values()) {
582
+ // Mark the link dead before the first await: a dependent action must not start (or
583
+ // retry) while shutdown is still walking the list (L).
584
+ runtime.closing = true
585
+ runtime.desired = 'idle'
586
+ cancelReconnect(runtime)
587
+ cancelIdleStop(runtime)
588
+ cancelLinkWork(runtime)
589
+ cancelHostKeyPrompt(runtime)
590
+ cancelConflict(runtime)
591
+ stopRemoteHeartbeat(runtime)
592
+ await settleTunnelRepair(ctx, runtime)
593
+ try {
594
+ if (runtime.entry.keepAlive === 'stop') {
595
+ await stopRemoteForIdle(ctx, runtime, { shutdown: true })
596
+ } else {
597
+ await closeTunnel(runtime)
598
+ await disposeSsh(runtime)
599
+ }
600
+ } catch {
601
+ /* best effort on shutdown */
602
+ }
603
+ }
604
+ }