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,565 @@
1
+ /**
2
+ * The transition table of the `HostRuntime.session` state machine: one `Record<EventType, Rule>`
3
+ * row per event with its guards, effects and shared pure helpers. `fsm.ts` is the engine that looks
4
+ * a row up and applies it; together they are the only place allowed to decide what a host runtime's
5
+ * session block becomes next (design-arch §2.4). Nothing here performs I/O, and a refused
6
+ * transition returns the same state object the engine was given.
7
+ */
8
+ import { stillWanted } from './fsm.js';
9
+ /** The two bilingual texts the FSM itself owns; step 4 removes the pipeline's copies. */
10
+ export const RESTART_STOP_WARNING = {
11
+ zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试,或先断开再重连。',
12
+ en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly, or disconnect and reconnect.',
13
+ };
14
+ export const STOP_FAILED_LABEL = {
15
+ zh: '关闭远端 DSH 失败',
16
+ en: 'Stopping the remote DSH failed',
17
+ };
18
+ function move(state, changes) {
19
+ return { ...state, ...changes };
20
+ }
21
+ /** Adopt a caller's token without ever rewinding the epoch: `beginLinkWork` passes `epoch + 1`, so a
22
+ * stale timer token can never take ownership back. */
23
+ function epochAfter(state, token) {
24
+ return Math.max(state.epoch, token);
25
+ }
26
+ function progressOf(code, params) {
27
+ return params === undefined ? { code } : { code, params };
28
+ }
29
+ /* Effect constructors: a rule reads as the event table row it implements. */
30
+ const emit = () => ({ type: 'emit' });
31
+ const settlePrompts = () => ({ type: 'settlePrompts' });
32
+ const closeLink = () => ({ type: 'closeLink' });
33
+ const disarm = (timer) => ({ type: 'disarm', timer });
34
+ const arm = (timer, ms) => ({ type: 'arm', timer, ms });
35
+ const log = (level, message) => ({ type: 'log', level, message });
36
+ const logFailure = (phase, label, view) => ({
37
+ type: 'logFailure',
38
+ phase,
39
+ ...(label === undefined ? {} : { label }),
40
+ // Only a rule that restores a *previous* error needs to name the failure it reports: the
41
+ // executor otherwise logs the error the transition just wrote.
42
+ ...(view === undefined ? {} : { view }),
43
+ });
44
+ const apply = (patch) => ({ type: 'apply', patch });
45
+ const teardown = (options) => ({ type: 'teardown', options });
46
+ const run = (activity, token) => ({ type: 'run', activity, token });
47
+ function transportCloseBranch(state, scope) {
48
+ // This close is a teardown's own closing, or the user already let go: nothing to report.
49
+ if (state.closing || state.desired !== 'connected')
50
+ return 'ignored';
51
+ // A newer transport owns the link; this one is the previous attempt's.
52
+ if (!scope.transportIsCurrent)
53
+ return 'stale';
54
+ // `live` mirrors today's `status === 'connected' || linkBusy !== null`; a connect attempt has
55
+ // its own branch below (it must not schedule the retry twice — the pipeline exit reports it).
56
+ if (state.status === 'connected' || (state.activity !== null && state.activity !== 'connect'))
57
+ return 'dropped';
58
+ if (state.activity === 'connect')
59
+ return 'handshake';
60
+ return 'idle';
61
+ }
62
+ /** The restart/stop entry guard: connected now, or a `remote-unreachable` error that can recover. */
63
+ function entryGuard(state, scope) {
64
+ if (state.activity !== null)
65
+ return 'busy';
66
+ if (state.status === 'connected')
67
+ return true;
68
+ if (state.status === 'error')
69
+ return scope.recoverable ? true : 'not-recoverable';
70
+ return 'not-connected';
71
+ }
72
+ /* ── the table (one row per event, design-arch §2.4.2) ───────────────────────────────────── */
73
+ export const TABLE = {
74
+ 'connect.requested': {
75
+ guard(state, _event, scope) {
76
+ // `promises.connect === null` from the design is `activity === null` here (§2.4.5).
77
+ if (state.activity === 'connect')
78
+ return 'already-connecting';
79
+ if (state.activity !== null)
80
+ return 'already-restarting';
81
+ if (state.status === 'connected' && scope.linkAlive)
82
+ return 'already-connected';
83
+ return true;
84
+ },
85
+ apply: (state, event) => move(state, {
86
+ status: 'connecting',
87
+ desired: 'connected',
88
+ activity: 'connect',
89
+ epoch: epochAfter(state, event.token),
90
+ // A scheduled retry re-enters the pipeline; only a user-requested connect resets the budget.
91
+ reconnectAttempts: event.retry === true ? state.reconnectAttempts : 0,
92
+ connectCancelled: false,
93
+ transportLost: false,
94
+ error: null,
95
+ warning: null,
96
+ warningSource: null,
97
+ phase: null,
98
+ progress: null,
99
+ closing: false,
100
+ }),
101
+ effects: (state, event) => [
102
+ disarm('idle'),
103
+ disarm('reconnect'),
104
+ disarm('heartbeat'),
105
+ emit(),
106
+ run('connect', epochAfter(state, event.token)),
107
+ ],
108
+ },
109
+ 'step.entered': {
110
+ guard: (state) => (state.activity === null ? 'illegal-transition' : true),
111
+ apply: (state, event) => move(state, { phase: event.phase, progress: progressOf(event.code, event.params) }),
112
+ effects: () => [emit()],
113
+ },
114
+ 'step.done': {
115
+ guard: (state) => (state.activity === null ? 'illegal-transition' : true),
116
+ apply: (state) => state,
117
+ // Today probe/node/tunnel/verify completions only log; they do not publish a frame.
118
+ effects: (_state, event) => [log('debug', `step done: ${event.step}`)],
119
+ },
120
+ 'transport.ready': {
121
+ guard: (state) => (state.activity === null ? 'illegal-transition' : true),
122
+ apply: (state) => move(state, { transportLost: false }),
123
+ effects: () => [],
124
+ },
125
+ 'transport.closed': {
126
+ guard: () => true,
127
+ apply: (state, _event, scope) => {
128
+ const branch = transportCloseBranch(state, scope);
129
+ if (branch === 'dropped')
130
+ return move(state, transportDropPatch(state));
131
+ if (branch === 'handshake')
132
+ return move(state, { transportLost: true });
133
+ return state;
134
+ },
135
+ effects: (state, _event, scope) => {
136
+ const branch = transportCloseBranch(state, scope);
137
+ if (branch === 'dropped') {
138
+ return [
139
+ apply({ kind: 'mark-detached' }),
140
+ settlePrompts(),
141
+ disarm('heartbeat'),
142
+ closeLink(),
143
+ arm('reconnect', scope.delays.reconnectMs),
144
+ emit(),
145
+ ];
146
+ }
147
+ if (branch === 'handshake') {
148
+ return [settlePrompts(), log('warn', 'the SSH transport closed while the connection was being set up')];
149
+ }
150
+ return [];
151
+ },
152
+ },
153
+ 'hostkey.pending': {
154
+ guard: (state) => (state.status === 'connecting' ? true : 'illegal-transition'),
155
+ apply: (state, event) => move(state, {
156
+ status: 'fingerprint-pending',
157
+ phase: 'ssh',
158
+ // The same keys `prompts.ts` publishes, including the jump identity (B1: never the target's).
159
+ progress: event.role === 'jump'
160
+ ? progressOf('host-key-confirm', {
161
+ sha256: event.info.sha256,
162
+ keyType: event.info.keyType,
163
+ role: 'jump',
164
+ host: event.host,
165
+ })
166
+ : progressOf('host-key-confirm', { sha256: event.info.sha256, keyType: event.info.keyType }),
167
+ }),
168
+ effects: () => [emit()],
169
+ },
170
+ 'hostkey.answered': {
171
+ guard: (state, _event, scope) => {
172
+ if (!scope.promptsPending)
173
+ return 'stale-prompt';
174
+ return state.status === 'fingerprint-pending' ? true : 'prompt-not-pending';
175
+ },
176
+ apply: (state, event) => move(state, {
177
+ status: 'connecting',
178
+ progress: progressOf('auth-checking'),
179
+ connectCancelled: !event.accept,
180
+ }),
181
+ effects: () => [emit()],
182
+ },
183
+ 'hostkey.timeout': {
184
+ guard: (state, _event, scope) => {
185
+ if (!scope.promptsPending)
186
+ return 'stale-prompt';
187
+ return state.status === 'fingerprint-pending' ? true : 'prompt-not-pending';
188
+ },
189
+ apply: (state, event) => move(state, {
190
+ status: 'error',
191
+ error: event.view,
192
+ phase: null,
193
+ progress: null,
194
+ connectCancelled: true,
195
+ }),
196
+ effects: () => [emit()],
197
+ },
198
+ 'conflict.pending': {
199
+ guard: (state) => (state.status === 'connecting' ? true : 'illegal-transition'),
200
+ apply: (state, event) => move(state, {
201
+ status: 'conflict-pending',
202
+ progress: progressOf('remote-dsh-running', { count: event.count }),
203
+ }),
204
+ effects: () => [emit()],
205
+ },
206
+ 'conflict.answered': {
207
+ guard: (state, _event, scope) => {
208
+ if (!scope.promptsPending)
209
+ return 'stale-prompt';
210
+ return state.status === 'conflict-pending' ? true : 'prompt-not-pending';
211
+ },
212
+ apply: (state, event) => move(state, {
213
+ status: 'connecting',
214
+ progress: progressOf('probing'),
215
+ // The user said "no": a retry would ask again, so the failure that follows must not schedule
216
+ // one. Today's `resolveForeignConflict` sets this flag next to the throw.
217
+ connectCancelled: event.action === 'cancel' ? true : state.connectCancelled,
218
+ }),
219
+ effects: () => [apply({ kind: 'clear-conflict' }), emit()],
220
+ },
221
+ 'connect.succeeded': {
222
+ guard: (state) => {
223
+ const mine = state.activity === 'connect' || state.activity === 'restart' || state.activity === 'reattach';
224
+ return mine && state.status === 'connecting' ? true : 'illegal-transition';
225
+ },
226
+ apply: (state) => {
227
+ // A fresh attach clears a stale restart-stop warning; an `alongside` warning describes a running process.
228
+ const clearsWarning = state.warningSource === 'restart-stop';
229
+ return move(state, {
230
+ status: 'connected',
231
+ phase: 'ready',
232
+ progress: progressOf('ready'),
233
+ error: null,
234
+ reconnectAttempts: 0,
235
+ connectCancelled: false,
236
+ activity: null,
237
+ warning: clearsWarning ? null : state.warning,
238
+ warningSource: clearsWarning ? null : state.warningSource,
239
+ });
240
+ },
241
+ effects: (_state, _event, scope) => [
242
+ disarm('idle'),
243
+ arm('heartbeat', scope.delays.heartbeatMs),
244
+ apply({ kind: 'mark-attached' }),
245
+ apply({ kind: 'publish-active-host', hostId: scope.hostId }),
246
+ emit(),
247
+ ],
248
+ },
249
+ 'connect.cancelled': {
250
+ guard: (state) => (state.activity === null ? 'illegal-transition' : true),
251
+ apply: (state) => move(state, { status: 'disconnected', error: null, phase: null, progress: null, activity: null }),
252
+ // Today's cancel branch published `uiReady:false`/`localPort:null` too: a cancelled attempt that
253
+ // had already set `uiReady` must not leave a half-attached remote view behind.
254
+ effects: () => [teardown({ stopRemote: false, keepRemote: true }), apply({ kind: 'mark-detached' }), emit()],
255
+ },
256
+ 'connect.failed': {
257
+ // The one explicit idempotent self-transition: the host-key timeout and the pipeline catch both
258
+ // report the same failure, so `error` → `error` must be allowed (§2.4.2). Any status: the attempt
259
+ // can fail while parked on a prompt (`fingerprint-pending`, `conflict-pending`) — a transport
260
+ // closing under a parked host-key prompt is H3's "dropped link". `activity !== null` is the real
261
+ // guard: a failure belongs to the script that owns the link.
262
+ guard: (state) => (state.activity === null ? 'illegal-transition' : true),
263
+ apply: (state, event) => move(state, {
264
+ status: 'error',
265
+ error: event.view,
266
+ phase: null,
267
+ progress: null,
268
+ activity: null,
269
+ // Today's pipeline clears the flag after the retry decision; the next attempt starts "not cancelled".
270
+ connectCancelled: false,
271
+ }),
272
+ effects: (state, event, scope) => [
273
+ apply({ kind: 'mark-detached' }),
274
+ logFailure(event.phase),
275
+ teardown({
276
+ stopRemote: scope.remoteStarted && scope.keepAlive === 'stop',
277
+ keepRemote: scope.remoteStarted && scope.keepAlive !== 'stop',
278
+ }),
279
+ // The retry decision (policy, budget, delay) stays in the executor; this only says a retry makes sense.
280
+ ...(state.desired === 'connected' && !state.connectCancelled ? [arm('reconnect', scope.delays.reconnectMs)] : []),
281
+ emit(),
282
+ ],
283
+ },
284
+ 'disconnect.requested': {
285
+ // Total on purpose: the user may cancel during any connect step (M1/H4), and a repeat disconnect is idempotent.
286
+ guard: () => true,
287
+ apply: (state) => move(state, {
288
+ status: 'disconnected',
289
+ desired: 'idle',
290
+ epoch: state.epoch + 1,
291
+ activity: null,
292
+ phase: null,
293
+ progress: null,
294
+ closing: false,
295
+ }),
296
+ effects: (state, event, scope) => {
297
+ const alreadyStopped = event.stopped === true;
298
+ const stopRemote = alreadyStopped ? false : event.stopRemote === true || scope.keepAlive === 'stop';
299
+ const keepSshForIdle = scope.keepAlive === 'idle' && !stopRemote && !alreadyStopped;
300
+ return [
301
+ disarm('reconnect'),
302
+ disarm('idle'),
303
+ disarm('heartbeat'),
304
+ settlePrompts(),
305
+ teardown({ stopRemote, keepSshForIdle }),
306
+ apply({ kind: 'mark-detached' }),
307
+ ...(keepSshForIdle ? [arm('idle', scope.delays.idleMs)] : []),
308
+ emit(),
309
+ ];
310
+ },
311
+ },
312
+ 'idle.elapsed': {
313
+ // A timer that fires for a host the user wants again is stale. Refusing keeps "run the idle
314
+ // script" unambiguous; the script re-checks `stillWanted` (H1). Step 4 logs this refusal at debug
315
+ // ("idle stop skipped: the host is connected again"), not the generic warn level.
316
+ guard: (state, _event, scope) => (stillWanted(state, scope) ? 'illegal-transition' : true),
317
+ apply: (state) => state,
318
+ effects: () => [],
319
+ },
320
+ 'repair.requested': {
321
+ guard: (state, _event, scope) => {
322
+ if (state.activity !== null)
323
+ return 'busy';
324
+ if (state.status !== 'connected' || !scope.tunnelAlive)
325
+ return 'not-connected';
326
+ return true;
327
+ },
328
+ apply: (state, event) => move(state, { activity: 'repair', epoch: epochAfter(state, event.token) }),
329
+ effects: (state, event) => [run('repair', epochAfter(state, event.token))],
330
+ },
331
+ 'repair.finished': {
332
+ guard: (state) => (state.activity === 'repair' ? true : 'illegal-transition'),
333
+ apply: (state) => move(state, { activity: null }),
334
+ // Today a successful rebuild publishes the frame and marks the UI up; a failed one is silent
335
+ // (the repair script logs its own reason).
336
+ effects: (_state, event) => (event.ok ? [apply({ kind: 'mark-ui-up' }), emit()] : []),
337
+ },
338
+ 'restart.requested': {
339
+ guard: (state, _event, scope) => entryGuard(state, scope),
340
+ apply: (state, event) => move(state, {
341
+ activity: 'restart',
342
+ epoch: epochAfter(state, event.token),
343
+ status: 'connecting',
344
+ desired: 'connected',
345
+ phase: 'start',
346
+ progress: progressOf('restarting-remote', {
347
+ pid: Number(event.pid) || 0,
348
+ port: Number(event.port) || 0,
349
+ }),
350
+ error: null,
351
+ }),
352
+ effects: (state, event) => [
353
+ disarm('heartbeat'),
354
+ disarm('reconnect'),
355
+ disarm('idle'),
356
+ // Today's request event emitted the new `connecting` card from `progress.set`; this rule owns it now.
357
+ emit(),
358
+ run('restart', epochAfter(state, event.token)),
359
+ ],
360
+ },
361
+ 'restart.resumed': {
362
+ guard: (state) => (state.activity === 'restart' ? true : 'illegal-transition'),
363
+ apply: (state, event) => {
364
+ // Only the "managed stop was not confirmed" caller warns; a restart cancelled before touching anything resumes plainly.
365
+ const keptInstance = event.keptInstance === true;
366
+ return move(state, {
367
+ status: 'connected',
368
+ warning: keptInstance ? RESTART_STOP_WARNING : state.warning,
369
+ warningSource: keptInstance ? 'restart-stop' : state.warningSource,
370
+ phase: 'ready',
371
+ progress: progressOf('ready'),
372
+ error: null,
373
+ activity: null,
374
+ });
375
+ },
376
+ effects: (_state, _event, scope) => [
377
+ apply({ kind: 'mark-ui-up' }),
378
+ arm('heartbeat', scope.delays.heartbeatMs),
379
+ emit(),
380
+ ],
381
+ },
382
+ 'restart.failed': {
383
+ guard: (state) => (state.activity === 'restart' ? true : 'illegal-transition'),
384
+ apply: (state, event) => move(state, { status: 'error', error: event.view, phase: null, progress: null, activity: null }),
385
+ effects: (_state, event, scope) => [
386
+ apply({ kind: 'mark-detached' }),
387
+ logFailure(event.phase),
388
+ teardown({ stopRemote: scope.keepAlive === 'stop' }),
389
+ emit(),
390
+ ],
391
+ },
392
+ 'stop.requested': {
393
+ guard: (state, _event, scope) => entryGuard(state, scope),
394
+ apply: (state, event) => move(state, {
395
+ activity: 'stop',
396
+ epoch: epochAfter(state, event.token),
397
+ status: 'connecting',
398
+ phase: 'start',
399
+ progress: progressOf('stopping-remote', {
400
+ pid: Number(event.pid) || 0,
401
+ port: Number(event.port) || 0,
402
+ }),
403
+ // Today's `runStopRemote` clears the previous error as it enters the action.
404
+ error: null,
405
+ }),
406
+ effects: (state, event) => [
407
+ disarm('heartbeat'),
408
+ disarm('reconnect'),
409
+ disarm('idle'),
410
+ // Today's `progress.set` published the "stopping" card; the rule owns it now.
411
+ emit(),
412
+ run('stop', epochAfter(state, event.token)),
413
+ ],
414
+ },
415
+ 'stop.refused': {
416
+ guard: (state) => (state.activity === 'stop' ? true : 'illegal-transition'),
417
+ apply(state, event) {
418
+ if (event.unrestorable === true) {
419
+ // §2.4.2's "恢复不了则落 error": the link vanished (or was replaced) while the stop was
420
+ // failing, so the coded failure is published instead of a fake connected state.
421
+ return move(state, {
422
+ status: 'error',
423
+ error: event.view,
424
+ phase: null,
425
+ progress: null,
426
+ activity: null,
427
+ });
428
+ }
429
+ const previous = event.previous;
430
+ return move(state, {
431
+ status: previous.status,
432
+ error: previous.error,
433
+ phase: previous.phase,
434
+ progress: previous.progress,
435
+ activity: null,
436
+ });
437
+ },
438
+ effects: (_state, event, scope) => [
439
+ event.unrestorable === true
440
+ ? apply({ kind: 'mark-detached' })
441
+ : apply({ kind: 'restore-stop', uiReady: event.previous.uiReady, localPort: event.previous.localPort }),
442
+ // A restored `connected` means the link is live again: today's `resumeConnected` restarted
443
+ // the heartbeat the stop had disarmed. The §2.4.2 row omits it; without it a host left in
444
+ // `connected` would never be probed again (behavior freeze wins).
445
+ ...(event.unrestorable === true || event.previous.status !== 'connected'
446
+ ? []
447
+ : [arm('heartbeat', scope.delays.heartbeatMs)]),
448
+ logFailure(event.phase, STOP_FAILED_LABEL, event.view),
449
+ emit(),
450
+ ],
451
+ },
452
+ 'stop.succeeded': {
453
+ guard: (state) => (state.activity === 'stop' ? true : 'illegal-transition'),
454
+ apply: (state) => move(state, {
455
+ status: 'disconnected',
456
+ desired: 'idle',
457
+ epoch: state.epoch + 1,
458
+ phase: null,
459
+ progress: null,
460
+ activity: null,
461
+ }),
462
+ effects: () => [teardown({ stopRemote: false, stopped: true }), apply({ kind: 'mark-detached' }), emit()],
463
+ },
464
+ 'reattach.requested': {
465
+ guard: (state, _event, scope) => {
466
+ if (state.activity !== null)
467
+ return 'busy';
468
+ if (state.status !== 'connected' || !scope.tunnelAlive)
469
+ return 'not-connected';
470
+ return true;
471
+ },
472
+ apply: (state, event) => move(state, {
473
+ activity: 'reattach',
474
+ epoch: epochAfter(state, event.token),
475
+ status: 'connecting',
476
+ phase: 'start',
477
+ progress: progressOf('restarting-remote', { reason: event.reason }),
478
+ error: null,
479
+ }),
480
+ effects: (state, event) => [
481
+ disarm('heartbeat'),
482
+ disarm('reconnect'),
483
+ disarm('idle'),
484
+ // Today's `progress.set` published the "re-attaching" card; the rule owns it now.
485
+ emit(),
486
+ run('reattach', epochAfter(state, event.token)),
487
+ ],
488
+ },
489
+ 'reattach.failed': {
490
+ guard: (state) => (state.activity === 'reattach' ? true : 'illegal-transition'),
491
+ apply: (state, event) => move(state, { status: 'error', error: event.view, phase: null, progress: null, activity: null }),
492
+ effects: (state) => [
493
+ apply({ kind: 'mark-detached' }),
494
+ closeLink(),
495
+ disarm('heartbeat'),
496
+ logFailure(state.phase),
497
+ emit(),
498
+ ],
499
+ },
500
+ 'reconnect.scheduled': {
501
+ guard: (state) => (state.desired === 'connected' ? true : 'illegal-transition'),
502
+ apply: (state, event) => move(state, {
503
+ reconnectAttempts: event.attempt,
504
+ progress: progressOf('reconnecting', { attempt: event.attempt, max: event.max }),
505
+ }),
506
+ effects: (_state, event) => [arm('reconnect', event.delayMs), emit()],
507
+ },
508
+ 'reconnect.gaveup': {
509
+ guard: (state) => (state.desired === 'connected' ? true : 'illegal-transition'),
510
+ apply: (state, event) => move(state, { status: 'error', error: event.view, progress: null }),
511
+ effects: () => [emit()],
512
+ },
513
+ 'reconnect.skipped': {
514
+ // The executor already took the policy decision (no auto-reconnect, or the user let go); here
515
+ // the machine only records the outcome the Client renders. `progress` is deliberately left
516
+ // alone: today's `scheduleReconnect` patched only the status, so a dropped link that was not
517
+ // retried keeps the `reconnecting` line it had just published (behaviour freeze wins).
518
+ guard: () => true,
519
+ apply: (state) => move(state, { status: 'disconnected' }),
520
+ effects: () => [emit()],
521
+ },
522
+ 'link.cancelled': {
523
+ guard: () => true,
524
+ // Today's `cancelLinkWork` clears unconditionally; the canonical event carries no token, so this cannot be answered here.
525
+ apply: (state) => move(state, { epoch: state.epoch + 1, activity: null }),
526
+ effects: () => [log('debug', 'link work cancelled')],
527
+ },
528
+ shutdown: {
529
+ guard: () => true,
530
+ // `activity: null` is today's `cancelLinkWork` (the shutdown walks the registry after marking
531
+ // every link dead); leaving an action name behind would make the block describe work that no
532
+ // longer runs.
533
+ apply: (state) => move(state, { closing: true, desired: 'idle', epoch: state.epoch + 1, activity: null }),
534
+ effects: (_state, _event, scope) => [
535
+ disarm('reconnect'),
536
+ disarm('idle'),
537
+ disarm('heartbeat'),
538
+ disarm('remoteCheck'),
539
+ settlePrompts(),
540
+ teardown({ stopRemote: scope.keepAlive === 'stop', shutdown: true }),
541
+ ],
542
+ },
543
+ 'host.removed': {
544
+ guard: () => true,
545
+ apply: (state) => move(state, { desired: 'idle', activity: null, epoch: state.epoch + 1 }),
546
+ effects: (_state, event) => [
547
+ disarm('reconnect'),
548
+ disarm('idle'),
549
+ settlePrompts(),
550
+ teardown({ stopRemote: event.keepAlive === 'stop' }),
551
+ emit(),
552
+ ],
553
+ },
554
+ };
555
+ /** The state the "the transport dropped under a live link" branch produces (§2.4.2 row 3). */
556
+ function transportDropPatch(state) {
557
+ return {
558
+ status: 'disconnected',
559
+ transportLost: true,
560
+ activity: null,
561
+ epoch: state.epoch + 1,
562
+ phase: null,
563
+ progress: progressOf('reconnecting', { attempt: state.reconnectAttempts + 1 }),
564
+ };
565
+ }