dsh-remote-go 0.2.0 → 0.3.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 (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/{src → dist/src}/constants.js +30 -56
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -0,0 +1,504 @@
1
+ /**
2
+ * Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path; the
3
+ * reconnect timer gets a callback, so this never imports the pipeline. The liveness watchdog that
4
+ * used to live here moved to `watchdog.ts` (P2 step 9); only the timer primitives it disarms stay,
5
+ * because this module owns the runtime's timer block.
6
+ */
7
+ import { DEFAULT_IDLE_MINUTES, REMOTE_TUNNEL_REPAIR_SETTLE_MS } from './constants.js';
8
+ import { OWNERSHIP_OPTIONS, proveOwnership } from './connect/ownership.js';
9
+ import { errors, toErrorView } from './errors.js';
10
+ import { emptyRemote } from './host-runtime.js';
11
+ import { layoutForRuntime } from './layout.js';
12
+ import { cancelConflict, cancelHostKeyPrompt } from './prompts.js';
13
+ import { dispatch, scopeFactsFor } from './runtime/dispatch.js';
14
+ import { isPid, messageOf, randomDelay } from './util.js';
15
+ export function cancelReconnect(runtime) {
16
+ if (runtime.reconnectTimer) {
17
+ clearTimeout(runtime.reconnectTimer);
18
+ runtime.reconnectTimer = null;
19
+ }
20
+ }
21
+ export function cancelIdleStop(runtime) {
22
+ if (runtime.idleTimer) {
23
+ clearTimeout(runtime.idleTimer);
24
+ runtime.idleTimer = null;
25
+ }
26
+ }
27
+ /**
28
+ * One-shot link actions (a local restart, a remote re-attach, a tunnel rebuild) share a
29
+ * token so a disconnect, a dropped transport or a newer action can invalidate an older one:
30
+ * an action must never write state on top of whatever replaced it.
31
+ * @param runtime - host runtime.
32
+ * @param kind - `restart`, `reattach`, `repair` or `stop`.
33
+ * @returns the token that owns the action.
34
+ */
35
+ export function beginLinkWork(runtime, kind) {
36
+ runtime.linkToken = (Number(runtime.linkToken) || 0) + 1;
37
+ runtime.linkBusy = kind;
38
+ return runtime.linkToken;
39
+ }
40
+ export function isLinkWorkCurrent(runtime, token) {
41
+ return runtime.linkToken === token;
42
+ }
43
+ export function endLinkWork(runtime, token) {
44
+ if (!isLinkWorkCurrent(runtime, token))
45
+ return;
46
+ runtime.linkBusy = null;
47
+ }
48
+ /** Invalidate whatever one-shot action was running; safe when there is none. */
49
+ export function cancelLinkWork(runtime) {
50
+ runtime.linkToken = (Number(runtime.linkToken) || 0) + 1;
51
+ runtime.linkBusy = null;
52
+ }
53
+ export function cancelRemoteCheck(runtime) {
54
+ if (runtime.remoteCheckTimer) {
55
+ clearTimeout(runtime.remoteCheckTimer);
56
+ runtime.remoteCheckTimer = null;
57
+ }
58
+ }
59
+ /** Stop probing: called on connect, disconnect, re-attach and shutdown. */
60
+ export function stopRemoteHeartbeat(runtime) {
61
+ if (runtime.heartbeatTimer) {
62
+ clearInterval(runtime.heartbeatTimer);
63
+ runtime.heartbeatTimer = null;
64
+ }
65
+ cancelRemoteCheck(runtime);
66
+ runtime.remoteFailures = 0;
67
+ runtime.remoteEpisode = false;
68
+ runtime.episodeSource = null;
69
+ // A new attach starts a new episode budget; the cooldown only exists to damp one connection.
70
+ runtime.episodeCooldownUntil = 0;
71
+ }
72
+ /**
73
+ * Arm the next reconnect attempt, or give up once the configured budget is spent.
74
+ *
75
+ * The timer is created through `reconnect.scheduled`; that event is the **only** `arm(reconnect)`
76
+ * the executor turns into a timeout (the design's P2b hand-off: the connect-failure paths also ask
77
+ * for a retry, and honouring those would run a second loop). The rule decides whether the attempt
78
+ * is still wanted, the policy/budget/randomized delay stay here.
79
+ */
80
+ export function scheduleReconnect(ctx, runtime, onDue) {
81
+ cancelReconnect(runtime);
82
+ // A retry only makes sense while the user still wants the link: a disconnect, a host
83
+ // removal or a shutdown that raced the timer must not resurrect the connection.
84
+ if (ctx.state.disposed === true || runtime.desired !== 'connected') {
85
+ void dispatch(effectsOf(ctx), runtime, { type: 'reconnect.skipped' }, scopeFactsFor(ctx, runtime, { type: 'reconnect.skipped' }), {
86
+ caller: 'timer',
87
+ });
88
+ return;
89
+ }
90
+ const settings = ctx.settings();
91
+ if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled) {
92
+ void dispatch(effectsOf(ctx), runtime, { type: 'reconnect.skipped' }, scopeFactsFor(ctx, runtime, { type: 'reconnect.skipped' }), {
93
+ caller: 'timer',
94
+ });
95
+ return;
96
+ }
97
+ const maxAttempts = settings.autoReconnect.maxAttempts;
98
+ if (runtime.reconnectAttempts >= maxAttempts) {
99
+ const event = {
100
+ type: 'reconnect.gaveup',
101
+ maxAttempts,
102
+ view: toErrorView(errors.network({
103
+ zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
104
+ en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
105
+ })),
106
+ };
107
+ void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' });
108
+ return;
109
+ }
110
+ const attempt = runtime.reconnectAttempts + 1;
111
+ const delay = randomDelay(settings.autoReconnect.baseDelayMs, settings.autoReconnect.baseDelayMs * 2 ** Math.min(attempt, 4));
112
+ ctx.progress.log(runtime, 'warn', `link lost; retrying in ${Math.round(delay / 100) / 10}s (attempt ${attempt}/${maxAttempts})`);
113
+ void dispatch(effectsOf(ctx), runtime, { type: 'reconnect.scheduled', attempt, max: maxAttempts, delayMs: delay }, scopeFactsFor(ctx, runtime, { type: 'reconnect.scheduled', attempt, max: maxAttempts, delayMs: delay }), {
114
+ caller: 'timer',
115
+ armReconnect: (ms) => {
116
+ runtime.reconnectTimer = setTimeout(() => {
117
+ runtime.reconnectTimer = null;
118
+ onDue();
119
+ }, ms);
120
+ // A pending retry must never keep the host process alive on its own.
121
+ runtime.reconnectTimer.unref?.();
122
+ },
123
+ });
124
+ }
125
+ /**
126
+ * The idle policy's timer. It is a *guard* first and a stop second: `idle.elapsed` is the FSM's
127
+ * statement that the host is no longer wanted (`stillWanted`), and a refusal — the user connected
128
+ * again while the timer was armed — is logged at debug by the event itself, never as a warning.
129
+ */
130
+ export function scheduleIdleStop(ctx, runtime) {
131
+ cancelIdleStop(runtime);
132
+ const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES);
133
+ runtime.idleTimer = setTimeout(() => {
134
+ runtime.idleTimer = null;
135
+ const event = { type: 'idle.elapsed' };
136
+ void dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'timer' }).then(async (result) => {
137
+ // The rule allows the stop only while the host is idle; `stopRemoteForIdle` re-checks the
138
+ // same condition and remains the single implementation of the policy itself.
139
+ if (result.ok)
140
+ await stopRemoteForIdle(ctx, runtime);
141
+ });
142
+ }, minutes * 60_000);
143
+ runtime.idleTimer.unref?.();
144
+ }
145
+ /**
146
+ * Best-effort stop of the remote web for the idle policy, then drop the transport.
147
+ *
148
+ * The teardown that armed this timer clears `facts` and `remote`, so the stop has to use the
149
+ * home and pid remembered before that clearing: the old fallback built a layout with a
150
+ * literal `~`, whose `kill -0` is a no-op that still reported success (H1).
151
+ *
152
+ * The timer is a *policy for an idle host*, never authority over a live link: the user may
153
+ * have connected again (the timer would otherwise kill the link just brought up), and a pid
154
+ * that answers `/proc` is not proof it is still the process this connection started
155
+ * (review: idle-timer zombie / pid reuse). Shutdown is the one caller that deliberately
156
+ * overrides the "still wanted" guard, because it is stopping the whole host process.
157
+ *
158
+ * @param ctx - service context.
159
+ * @param runtime - host runtime that went idle.
160
+ * @returns the stop verdict (best effort).
161
+ */
162
+ export async function stopRemoteForIdle(ctx, runtime, options = {}) {
163
+ // A live link wins over the idle policy, whichever timer fired it. This is what keeps a
164
+ // manual reconnect from being torn down by the timer armed before it.
165
+ const linkLive = runtime.desired === 'connected' || runtime.status === 'connected' || runtime.tunnel !== null;
166
+ if (linkLive && options.shutdown !== true) {
167
+ ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
168
+ return { ok: false, reason: 'still-wanted' };
169
+ }
170
+ // The transport this call owns: the identity proof below awaits, and the user may connect
171
+ // in that window. Only this session may be released afterwards, never the new one.
172
+ const capturedSsh = runtime.ssh;
173
+ const stillWanted = () => runtime.ssh !== capturedSsh ||
174
+ runtime.desired === 'connected' ||
175
+ runtime.status === 'connected' ||
176
+ runtime.tunnel !== null;
177
+ try {
178
+ if (capturedSsh?.connected !== true)
179
+ return { ok: false, reason: 'no-transport' };
180
+ const home = runtime.facts?.home ?? runtime.remoteHome ?? null;
181
+ if (typeof home !== 'string' || home.trim() === '') {
182
+ ctx.progress.log(runtime, 'warn', 'idle stop skipped: the remote home directory is unknown');
183
+ return { ok: false, reason: 'no-home' };
184
+ }
185
+ const layout = layoutForRuntime(runtime);
186
+ const pid = Number(runtime.remote.pid ?? runtime.remotePid ?? 0);
187
+ // Without a pid there is nothing this policy may signal: `stopRemoteWeb` would fall back
188
+ // to the run registry and could stop an instance this connection did not launch.
189
+ if (!isPid(pid))
190
+ return { ok: false, reason: 'pid-unknown' };
191
+ // Same `/proc` identity proof the explicit stop uses (`OWNERSHIP_OPTIONS.idle`): a reused
192
+ // pid, another DSH home or another profile is not this connection's process and must not be
193
+ // signalled — and unlike the stop, nobody pointed at it, only the timer fired.
194
+ const proof = await proveOwnership(ctx, runtime, {
195
+ ...OWNERSHIP_OPTIONS.idle,
196
+ pid,
197
+ layout,
198
+ profile: runtime.remote.profile ?? runtime.remoteProfile ?? '',
199
+ });
200
+ if (proof.ok !== true) {
201
+ ctx.progress.log(runtime, 'warn', `idle stop skipped: ${proof.reason}`);
202
+ return { ok: false, reason: proof.reason };
203
+ }
204
+ // The user may have connected while the identity was read: the link wins again.
205
+ if (options.shutdown !== true && stillWanted()) {
206
+ ctx.progress.log(runtime, 'debug', 'idle stop skipped: the host is connected again');
207
+ return { ok: false, reason: 'still-wanted' };
208
+ }
209
+ const stopped = await ctx.deps.stopWeb(capturedSsh, layout, { pid });
210
+ if (stopped?.ok !== true) {
211
+ ctx.progress.log(runtime, 'warn', `idle stop did not confirm (${stopped?.reason ?? 'unknown'}); the remote may still be running`);
212
+ return { ok: false, reason: stopped?.reason ?? 'not-confirmed' };
213
+ }
214
+ runtime.remotePid = null;
215
+ return { ok: true };
216
+ }
217
+ catch (error) {
218
+ // swallow-ok: the idle stop is best effort; its failure is only a warning and the timer
219
+ // is already gone, so the host stays idle either way
220
+ ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error));
221
+ return { ok: false, reason: 'error' };
222
+ }
223
+ finally {
224
+ // Release only the transport this call captured: when a new connection owns the link by
225
+ // now, its session is not ours to dispose.
226
+ if (runtime.ssh === capturedSsh)
227
+ await disposeSsh(runtime);
228
+ }
229
+ }
230
+ export async function closeTunnel(runtime) {
231
+ const tunnel = runtime.tunnel;
232
+ runtime.tunnel = null;
233
+ // `localPort` is a view of the live listener: a closed tunnel must not leave a stale port
234
+ // behind (the proxy and diagnostics read this field).
235
+ runtime.remote.localPort = null;
236
+ if (tunnel) {
237
+ try {
238
+ await tunnel.close();
239
+ }
240
+ catch {
241
+ // swallow-ok: teardown continues; a dead tunnel needs no second error
242
+ }
243
+ }
244
+ }
245
+ export async function disposeSsh(runtime) {
246
+ const ssh = runtime.ssh;
247
+ runtime.ssh = null;
248
+ const jump = runtime.jumpSsh;
249
+ runtime.jumpSsh = null;
250
+ if (ssh) {
251
+ try {
252
+ await ssh.dispose();
253
+ }
254
+ catch {
255
+ // swallow-ok: disposal must not stop the rest of the teardown
256
+ }
257
+ }
258
+ if (jump) {
259
+ try {
260
+ await jump.dispose();
261
+ }
262
+ catch {
263
+ // swallow-ok: the same disposal rule as the target transport
264
+ }
265
+ }
266
+ }
267
+ /**
268
+ * The single teardown path. `stopRemote` also stops the remote web (keep-alive
269
+ * `stop`), `keepSshForIdle` leaves the transport up for a fast resume, and
270
+ * `keepRemote` preserves the remote facts so the card still describes what is
271
+ * running on the other side.
272
+ */
273
+ /**
274
+ * Wait for an in-flight tunnel rebuild (if any) after the caller cancelled link work.
275
+ * The rebuild closes its own replacement in `finally` when its token is gone, so awaiting
276
+ * here is what makes disconnect / removeHost / shutdown leak-free. Bounded: a stuck rebuild
277
+ * must not delay teardown forever; its token is already cancelled, so it cannot publish.
278
+ * @param ctx - service context.
279
+ * @param runtime - host runtime.
280
+ */
281
+ async function settleTunnelRepair(ctx, runtime) {
282
+ const repair = runtime.tunnelRepair;
283
+ if (!repair)
284
+ return;
285
+ const timeoutMs = Number(ctx.timers?.tunnelRepairSettleMs ?? REMOTE_TUNNEL_REPAIR_SETTLE_MS);
286
+ let timer = null;
287
+ const timeout = new Promise((resolve) => {
288
+ timer = setTimeout(() => resolve('timeout'), Math.max(0, timeoutMs));
289
+ timer.unref?.();
290
+ });
291
+ try {
292
+ const outcome = await Promise.race([repair, timeout]);
293
+ if (outcome === 'timeout') {
294
+ ctx.progress.log(runtime, 'warn', 'tunnel rebuild did not finish in time; abandoning it');
295
+ // The rebuild was cancelled via cancelLinkWork; its own finally will close any listener
296
+ // it creates. Clear the slot so teardown never waits on it again.
297
+ runtime.tunnelRepair = null;
298
+ }
299
+ }
300
+ catch {
301
+ // swallow-ok: the rebuild reports its own failure; teardown must still proceed
302
+ }
303
+ finally {
304
+ if (timer !== null)
305
+ clearTimeout(timer);
306
+ }
307
+ }
308
+ export async function teardownRuntime(ctx, runtime, options = {}) {
309
+ cancelConflict(runtime);
310
+ // A prompt parked on the transport that is about to go away can never be answered: settle
311
+ // it now instead of letting the connect promise wait for its 120s timeout (M1).
312
+ cancelHostKeyPrompt(runtime);
313
+ cancelLinkWork(runtime);
314
+ stopRemoteHeartbeat(runtime);
315
+ runtime.closing = true;
316
+ cancelIdleStop(runtime);
317
+ // A tunnel rebuild owns a listener it may be creating right now. Cancel it (above), then
318
+ // wait for it to clean up: otherwise the listener would be assigned after this teardown.
319
+ await settleTunnelRepair(ctx, runtime);
320
+ // Remember where the remote lives before the facts below are cleared: the idle policy and
321
+ // a later stop still need the real home, never a literal `~` (H1).
322
+ if (typeof runtime.facts?.home === 'string' && runtime.facts.home.trim() !== '') {
323
+ runtime.remoteHome = runtime.facts.home;
324
+ }
325
+ if (typeof runtime.remote.profile === 'string' && runtime.remote.profile !== '') {
326
+ runtime.remoteProfile = runtime.remote.profile;
327
+ }
328
+ const boundPid = Number(runtime.remote.pid ?? 0);
329
+ if (isPid(boundPid))
330
+ runtime.remotePid = boundPid;
331
+ let remoteStopped = false;
332
+ if (options.stopRemote && runtime.ssh?.connected) {
333
+ try {
334
+ const result = await ctx.deps.stopWeb(runtime.ssh, layoutForRuntime(runtime), {
335
+ pid: runtime.remote.pid ?? undefined,
336
+ });
337
+ // Only a confirmed stop means the pid is gone; a refusal keeps the memory so a later
338
+ // stop can try again instead of reporting a process that never stopped.
339
+ remoteStopped = result?.ok === true;
340
+ }
341
+ catch (error) {
342
+ ctx.progress.log(runtime, 'warn', 'stop remote failed:', messageOf(error));
343
+ }
344
+ }
345
+ if (remoteStopped)
346
+ runtime.remotePid = null;
347
+ await closeTunnel(runtime);
348
+ if (!options.keepSshForIdle)
349
+ await disposeSsh(runtime);
350
+ if (!options.keepRemote) {
351
+ runtime.remote = { ...emptyRemote(), version: runtime.remote.version };
352
+ runtime.token = null;
353
+ runtime.facts = null;
354
+ runtime.exchange = null;
355
+ }
356
+ }
357
+ /**
358
+ * Tear one host down and leave it idle: the keep-alive policy decides whether the
359
+ * remote web is stopped and whether the transport survives for a fast resume.
360
+ * `stopped` says the caller already stopped the remote web itself (the explicit
361
+ * "stop remote DSH" action): the policy must then neither arm an idle stop nor send
362
+ * a second stop signal. That second signal would be based on a pid captured several
363
+ * SSH round-trips earlier - a pid the action just proved is the right one (or that
364
+ * it is already gone), so re-signalling it is at best redundant and at worst kills
365
+ * an unrelated process after a pid reuse.
366
+ *
367
+ * The state write, the timer disarms, the prompt settlement, the teardown and the idle timer are
368
+ * one transition (`disconnect.requested`); this function only keeps the log line and the event
369
+ * arguments the API passes.
370
+ */
371
+ export async function disconnectHost(ctx, runtime, options = {}) {
372
+ ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`);
373
+ const event = {
374
+ type: 'disconnect.requested',
375
+ ...(options.stopRemote === true ? { stopRemote: true } : {}),
376
+ ...(options.stopped === true ? { stopped: true } : {}),
377
+ };
378
+ await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
379
+ // The explicit stop action may have kept the transport for its own teardown; the disconnect
380
+ // still releases the token (the teardown path already dropped it, this is the idempotent half).
381
+ runtime.token = null;
382
+ return { ok: true };
383
+ }
384
+ /**
385
+ * Release one runtime during shutdown. This is today's shutdown branch: the `stop` policy stops
386
+ * the managed remote web through the idle-policy proof, every other policy just drops the
387
+ * listener and the transport (the remote keeps running, and the runtime keeps its facts).
388
+ * @param ctx - service context.
389
+ * @param runtime - host runtime being released.
390
+ * @param stopRemote - whether the keep-alive policy says "stop".
391
+ */
392
+ export async function releaseRuntimeForShutdown(ctx, runtime, stopRemote) {
393
+ await settleTunnelRepair(ctx, runtime);
394
+ try {
395
+ if (stopRemote) {
396
+ await stopRemoteForIdle(ctx, runtime, { shutdown: true });
397
+ return;
398
+ }
399
+ await closeTunnel(runtime);
400
+ await disposeSsh(runtime);
401
+ }
402
+ catch {
403
+ // swallow-ok: shutdown is best effort; every resource is released above
404
+ }
405
+ }
406
+ /**
407
+ * Stop every host's timers and release its transport. The `stop` keep-alive
408
+ * policy also stops the remote web so nothing is left running unowned.
409
+ */
410
+ export async function shutdownAll(ctx) {
411
+ for (const runtime of ctx.state.runtimes.values()) {
412
+ // One transition per runtime: it marks the link dead before the first await (a dependent
413
+ // action must not start, or retry, while shutdown is still walking the list) and then
414
+ // releases the transport through the same shutdown branch as before.
415
+ const event = { type: 'shutdown' };
416
+ await dispatch(effectsOf(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'silent' });
417
+ }
418
+ }
419
+ /**
420
+ * The effects of this module, bound to one context.
421
+ *
422
+ * `host-lifecycle` owns the timers and the teardown path, so it builds the effect object itself
423
+ * instead of importing `runtime/effects.ts` (which imports this module). `run` is never reached
424
+ * from here; it is declared because the interface requires it.
425
+ * @param ctx - the watchdog/teardown context.
426
+ * @returns the effect owner for one dispatch call.
427
+ */
428
+ function effectsOf(ctx) {
429
+ return {
430
+ emit: () => ctx.emitState(),
431
+ log: (runtime, level, message) => ctx.progress.log(runtime, level, message),
432
+ logFailure: (runtime, phase, label, view) => ctx.progress.logFailure(runtime, view ?? runtime.error, { phase, label }),
433
+ arm: (runtime, timer) => {
434
+ if (timer === 'idle') {
435
+ scheduleIdleStop(ctx, runtime);
436
+ return;
437
+ }
438
+ // No rule reachable from this module arms the heartbeat: the events that do
439
+ // (`connect.succeeded`, `restart.resumed`, `stop.refused`) are dispatched by `connect/*`,
440
+ // whose effect owner is `runtime/effects.ts`. Importing `watchdog.ts` from here would close
441
+ // the `host-lifecycle -> connect` edge the design forbids, so the branch stays a no-op —
442
+ // declared because the interface requires it, like `run`/`flushLogs` below.
443
+ },
444
+ disarm: (runtime, timer) => {
445
+ if (timer === 'reconnect')
446
+ cancelReconnect(runtime);
447
+ else if (timer === 'idle')
448
+ cancelIdleStop(runtime);
449
+ else
450
+ stopRemoteHeartbeat(runtime);
451
+ },
452
+ settlePrompts: (runtime) => {
453
+ cancelHostKeyPrompt(runtime);
454
+ cancelConflict(runtime);
455
+ },
456
+ closeLink: (runtime) => {
457
+ void closeTunnel(runtime);
458
+ },
459
+ teardown: async (runtime, options) => {
460
+ if (options.shutdown === true) {
461
+ await releaseRuntimeForShutdown(ctx, runtime, options.stopRemote === true);
462
+ return;
463
+ }
464
+ await teardownRuntime(ctx, runtime, {
465
+ stopRemote: options.stopRemote === true,
466
+ ...(options.keepRemote === true ? { keepRemote: true } : {}),
467
+ ...(options.keepSshForIdle === true ? { keepSshForIdle: true } : {}),
468
+ });
469
+ },
470
+ apply: (runtime, patch) => {
471
+ if (patch.kind === 'mark-detached') {
472
+ runtime.remote.uiReady = false;
473
+ runtime.remote.localPort = null;
474
+ return;
475
+ }
476
+ if (patch.kind === 'mark-ui-up') {
477
+ runtime.remote.uiReady = true;
478
+ return;
479
+ }
480
+ if (patch.kind === 'mark-attached') {
481
+ // Kept in step with `runtime/effects.ts#markAttached` (the two effect owners cannot share
482
+ // a module without an import cycle). `connect.succeeded` is the only producer.
483
+ runtime.remote.uiReady = true;
484
+ runtime.remote.viewRev = (Number(runtime.remote.viewRev) || 0) + 1;
485
+ runtime.tunnelRepairFailures = 0;
486
+ runtime.nextTunnelRepairAt = 0;
487
+ return;
488
+ }
489
+ if (patch.kind === 'clear-conflict') {
490
+ runtime.conflict = null;
491
+ return;
492
+ }
493
+ if (patch.kind === 'publish-active-host') {
494
+ ctx.state.activeHostId = patch.hostId;
495
+ return;
496
+ }
497
+ runtime.remote.uiReady = patch.uiReady === true;
498
+ runtime.remote.localPort = patch.localPort;
499
+ },
500
+ flushLogs: () => {
501
+ // The coalescing flush belongs to `connect-progress`; no rule reached from this module emits it.
502
+ },
503
+ };
504
+ }