dsh-remote-go 0.3.0 → 0.3.2

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 (86) hide show
  1. package/README.md +1 -0
  2. package/dist/client.js +1348 -2095
  3. package/dist/src/admission.js +3 -28
  4. package/dist/src/api.js +37 -99
  5. package/dist/src/atomic-json.js +32 -66
  6. package/dist/src/bootstrap.js +17 -27
  7. package/dist/src/connect/attach.js +3 -25
  8. package/dist/src/connect/bootstrap.js +2 -8
  9. package/dist/src/connect/failures.js +3 -18
  10. package/dist/src/connect/guards.js +13 -8
  11. package/dist/src/connect/launch.js +11 -21
  12. package/dist/src/connect/links.js +11 -27
  13. package/dist/src/connect/ownership.js +33 -114
  14. package/dist/src/connect/pipeline.js +62 -159
  15. package/dist/src/connect/reattach.js +26 -44
  16. package/dist/src/connect/registry.js +0 -1
  17. package/dist/src/connect/repair.js +8 -37
  18. package/dist/src/connect/restart.js +36 -97
  19. package/dist/src/connect/stop.js +16 -50
  20. package/dist/src/connect/transport.js +10 -18
  21. package/dist/src/connect/verify.js +3 -12
  22. package/dist/src/connect/watchdog.js +6 -38
  23. package/dist/src/connect-log.js +16 -41
  24. package/dist/src/connect-progress.js +13 -45
  25. package/dist/src/constants.js +18 -43
  26. package/dist/src/context.js +13 -32
  27. package/dist/src/diagnostics.js +56 -25
  28. package/dist/src/download-jobs.js +11 -20
  29. package/dist/src/errors.js +175 -190
  30. package/dist/src/events.js +20 -84
  31. package/dist/src/host-lifecycle.js +69 -177
  32. package/dist/src/host-registry.js +27 -78
  33. package/dist/src/host-runtime.js +0 -9
  34. package/dist/src/host-view.js +6 -29
  35. package/dist/src/index.js +15 -35
  36. package/dist/src/kernel-adapter.js +34 -80
  37. package/dist/src/key-files.js +10 -23
  38. package/dist/src/known-hosts.js +13 -34
  39. package/dist/src/layout.js +3 -20
  40. package/dist/src/local-download.js +94 -163
  41. package/dist/src/local-ssh.js +12 -19
  42. package/dist/src/local-version.js +35 -49
  43. package/dist/src/node/download.js +1 -4
  44. package/dist/src/node-runtime.js +19 -38
  45. package/dist/src/probe.js +6 -7
  46. package/dist/src/prompts.js +56 -128
  47. package/dist/src/proxy/cookies.js +26 -60
  48. package/dist/src/proxy/headers.js +30 -125
  49. package/dist/src/proxy/http.js +33 -41
  50. package/dist/src/proxy/index.js +20 -34
  51. package/dist/src/proxy/limits.js +4 -6
  52. package/dist/src/proxy/routes.js +10 -17
  53. package/dist/src/proxy/upgrade.js +27 -42
  54. package/dist/src/redact.js +14 -33
  55. package/dist/src/remote-files.js +9 -21
  56. package/dist/src/remote-path.js +21 -62
  57. package/dist/src/remote-proc.js +35 -103
  58. package/dist/src/remote-web/registry.js +10 -50
  59. package/dist/src/remote-web/resolve.js +23 -104
  60. package/dist/src/remote-web/start.js +27 -64
  61. package/dist/src/remote-web/stop.js +6 -25
  62. package/dist/src/request-trust.js +15 -32
  63. package/dist/src/runtime/dispatch.js +33 -143
  64. package/dist/src/runtime/effects.js +7 -17
  65. package/dist/src/runtime/events.js +1 -1
  66. package/dist/src/runtime/fsm.js +11 -61
  67. package/dist/src/runtime/rules.js +121 -199
  68. package/dist/src/secrets.js +15 -38
  69. package/dist/src/service.js +22 -128
  70. package/dist/src/settings.js +41 -42
  71. package/dist/src/ssh-config.js +22 -41
  72. package/dist/src/ssh-failures.js +23 -74
  73. package/dist/src/ssh-sftp.js +47 -86
  74. package/dist/src/ssh.js +99 -179
  75. package/dist/src/store.js +31 -48
  76. package/dist/src/tool-shared.js +17 -52
  77. package/dist/src/tools-exec-policy.js +33 -79
  78. package/dist/src/tools-exec.js +87 -151
  79. package/dist/src/tools-report.js +100 -167
  80. package/dist/src/tools.js +59 -133
  81. package/dist/src/tunnel.js +9 -27
  82. package/dist/src/util.js +19 -56
  83. package/dist/src/version.js +6 -12
  84. package/dist/src/watchdog-bus.js +0 -8
  85. package/dist/src/watchdog.js +7 -47
  86. package/package.json +3 -3
@@ -1,12 +1,5 @@
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
1
  import { stillWanted } from './fsm.js';
9
- /** The two bilingual texts the FSM itself owns; step 4 removes the pipeline's copies. */
2
+ /** The two bilingual texts the FSM itself owns. */
10
3
  export const RESTART_STOP_WARNING = {
11
4
  zh: '远端受管 DSH 没有确认停止,本次没有启动新实例;请稍后重试,或先断开再重连。',
12
5
  en: 'The managed remote DSH did not confirm its stop, so no new instance was started; retry shortly, or disconnect and reconnect.',
@@ -18,11 +11,12 @@ export const STOP_FAILED_LABEL = {
18
11
  function move(state, changes) {
19
12
  return { ...state, ...changes };
20
13
  }
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. */
14
+ /** Adopt a caller's token without ever rewinding the epoch: `beginLinkWork` passes `epoch + 1`, so a stale timer
15
+ * token can never take ownership back. */
23
16
  function epochAfter(state, token) {
24
17
  return Math.max(state.epoch, token);
25
18
  }
19
+ /** One progress card: the code plus the values the Client renders next to it. */
26
20
  function progressOf(code, params) {
27
21
  return params === undefined ? { code } : { code, params };
28
22
  }
@@ -37,13 +31,47 @@ const logFailure = (phase, label, view) => ({
37
31
  type: 'logFailure',
38
32
  phase,
39
33
  ...(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.
34
+ // Only a rule that restores a *previous* error names the failure it reports; otherwise the executor logs the error
35
+ // the transition just wrote.
42
36
  ...(view === undefined ? {} : { view }),
43
37
  });
44
38
  const apply = (patch) => ({ type: 'apply', patch });
45
39
  const teardown = (options) => ({ type: 'teardown', options });
46
40
  const run = (activity, token) => ({ type: 'run', activity, token });
41
+ // Frozen shared effect lists: freezing stops a caller that sorted/pushed a result from corrupting later transitions.
42
+ const EMIT_ONLY = Object.freeze([emit()]);
43
+ const NO_EFFECTS = Object.freeze([]);
44
+ const needsActivity = (state) => (state.activity === null ? 'illegal-transition' : true);
45
+ const ownsActivity = (activity) => (state) => state.activity === activity ? true : 'illegal-transition';
46
+ const promptGuard = (status) => (state, _event, scope) => !scope.promptsPending ? 'stale-prompt' : state.status === status ? true : 'prompt-not-pending';
47
+ /** The shared effect list of the four request events: stop every timer, publish the `connecting` card (today's
48
+ * `progress.set` published it) and start the action script. */
49
+ const requestEffects = (state, token, activity) => [
50
+ disarm('heartbeat'),
51
+ disarm('reconnect'),
52
+ disarm('idle'),
53
+ emit(),
54
+ run(activity, epochAfter(state, token)),
55
+ ];
56
+ /** Enter one one-shot action: it takes the link lock, adopts the token, and clears the previous error on entry. */
57
+ const enter = (state, activity, token, progress, extra = {}) => move(state, {
58
+ activity,
59
+ epoch: epochAfter(state, token),
60
+ status: 'connecting',
61
+ phase: 'start',
62
+ progress,
63
+ error: null,
64
+ ...extra,
65
+ });
66
+ const released = (state) => move(state, {
67
+ status: 'disconnected',
68
+ desired: 'idle',
69
+ epoch: state.epoch + 1,
70
+ phase: null,
71
+ progress: null,
72
+ activity: null,
73
+ });
74
+ const toError = (state, view) => move(state, { status: 'error', error: view, phase: null, progress: null, activity: null });
47
75
  function transportCloseBranch(state, scope) {
48
76
  // This close is a teardown's own closing, or the user already let go: nothing to report.
49
77
  if (state.closing || state.desired !== 'connected')
@@ -51,8 +79,7 @@ function transportCloseBranch(state, scope) {
51
79
  // A newer transport owns the link; this one is the previous attempt's.
52
80
  if (!scope.transportIsCurrent)
53
81
  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).
82
+ // `live` mirrors today's `status === 'connected' || linkBusy !== null`; a connect attempt has its own branch below.
56
83
  if (state.status === 'connected' || (state.activity !== null && state.activity !== 'connect'))
57
84
  return 'dropped';
58
85
  if (state.activity === 'connect')
@@ -60,7 +87,7 @@ function transportCloseBranch(state, scope) {
60
87
  return 'idle';
61
88
  }
62
89
  /** The restart/stop entry guard: connected now, or a `remote-unreachable` error that can recover. */
63
- function entryGuard(state, scope) {
90
+ function entryGuard(state, _event, scope) {
64
91
  if (state.activity !== null)
65
92
  return 'busy';
66
93
  if (state.status === 'connected')
@@ -69,11 +96,9 @@ function entryGuard(state, scope) {
69
96
  return scope.recoverable ? true : 'not-recoverable';
70
97
  return 'not-connected';
71
98
  }
72
- /* ── the table (one row per event, design-arch §2.4.2) ───────────────────────────────────── */
73
99
  export const TABLE = {
74
100
  'connect.requested': {
75
101
  guard(state, _event, scope) {
76
- // `promises.connect === null` from the design is `activity === null` here (§2.4.5).
77
102
  if (state.activity === 'connect')
78
103
  return 'already-connecting';
79
104
  if (state.activity !== null)
@@ -107,20 +132,20 @@ export const TABLE = {
107
132
  ],
108
133
  },
109
134
  'step.entered': {
110
- guard: (state) => (state.activity === null ? 'illegal-transition' : true),
135
+ guard: needsActivity,
111
136
  apply: (state, event) => move(state, { phase: event.phase, progress: progressOf(event.code, event.params) }),
112
- effects: () => [emit()],
137
+ effects: () => EMIT_ONLY,
113
138
  },
114
139
  'step.done': {
115
- guard: (state) => (state.activity === null ? 'illegal-transition' : true),
140
+ guard: needsActivity,
116
141
  apply: (state) => state,
117
142
  // Today probe/node/tunnel/verify completions only log; they do not publish a frame.
118
143
  effects: (_state, event) => [log('debug', `step done: ${event.step}`)],
119
144
  },
120
145
  'transport.ready': {
121
- guard: (state) => (state.activity === null ? 'illegal-transition' : true),
146
+ guard: needsActivity,
122
147
  apply: (state) => move(state, { transportLost: false }),
123
- effects: () => [],
148
+ effects: () => NO_EFFECTS,
124
149
  },
125
150
  'transport.closed': {
126
151
  guard: () => true,
@@ -147,73 +172,42 @@ export const TABLE = {
147
172
  if (branch === 'handshake') {
148
173
  return [settlePrompts(), log('warn', 'the SSH transport closed while the connection was being set up')];
149
174
  }
150
- return [];
175
+ return NO_EFFECTS;
151
176
  },
152
177
  },
153
178
  'hostkey.pending': {
154
179
  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()],
180
+ apply: (state, event) => {
181
+ // The same keys `prompts.ts` publishes, including the jump identity (never the target's).
182
+ const params = { sha256: event.info.sha256, keyType: event.info.keyType };
183
+ const progress = event.role === 'jump'
184
+ ? progressOf('host-key-confirm', { ...params, role: 'jump', host: event.host })
185
+ : progressOf('host-key-confirm', params);
186
+ return move(state, { status: 'fingerprint-pending', phase: 'ssh', progress });
187
+ },
188
+ effects: () => EMIT_ONLY,
169
189
  },
170
190
  '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()],
191
+ guard: promptGuard('fingerprint-pending'),
192
+ apply: (state, event) => move(state, { status: 'connecting', progress: progressOf('auth-checking'), connectCancelled: !event.accept }),
193
+ effects: () => EMIT_ONLY,
182
194
  },
183
195
  '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()],
196
+ guard: promptGuard('fingerprint-pending'),
197
+ apply: (state, event) => move(state, { status: 'error', error: event.view, phase: null, progress: null, connectCancelled: true }),
198
+ effects: () => EMIT_ONLY,
197
199
  },
198
200
  'conflict.pending': {
199
201
  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()],
202
+ apply: (state, event) => move(state, { status: 'conflict-pending', progress: progressOf('remote-dsh-running', { count: event.count }) }),
203
+ effects: () => EMIT_ONLY,
205
204
  },
206
205
  '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
- },
206
+ guard: promptGuard('conflict-pending'),
212
207
  apply: (state, event) => move(state, {
213
208
  status: 'connecting',
214
209
  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.
210
+ // The user said "no": a retry would ask again, so the failure that follows must not schedule one.
217
211
  connectCancelled: event.action === 'cancel' ? true : state.connectCancelled,
218
212
  }),
219
213
  effects: () => [apply({ kind: 'clear-conflict' }), emit()],
@@ -247,19 +241,17 @@ export const TABLE = {
247
241
  ],
248
242
  },
249
243
  'connect.cancelled': {
250
- guard: (state) => (state.activity === null ? 'illegal-transition' : true),
244
+ guard: needsActivity,
251
245
  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.
246
+ // Today's cancel branch published `uiReady:false`/`localPort:null` too: a cancelled attempt that had already set
247
+ // `uiReady` must not leave a half-attached remote view behind.
254
248
  effects: () => [teardown({ stopRemote: false, keepRemote: true }), apply({ kind: 'mark-detached' }), emit()],
255
249
  },
256
250
  '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),
251
+ // The one explicit idempotent self-transition: the host-key timeout and the pipeline catch report the same failure,
252
+ // so `error` → `error` is allowed, and any status may fail (a transport closing under a parked prompt).
253
+ // `activity !== null` is the real guard: a failure belongs to the script that owns the link.
254
+ guard: needsActivity,
263
255
  apply: (state, event) => move(state, {
264
256
  status: 'error',
265
257
  error: event.view,
@@ -282,18 +274,10 @@ export const TABLE = {
282
274
  ],
283
275
  },
284
276
  'disconnect.requested': {
285
- // Total on purpose: the user may cancel during any connect step (M1/H4), and a repeat disconnect is idempotent.
277
+ // Total on purpose: the user may cancel during any connect step, and a repeat disconnect is idempotent.
286
278
  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) => {
279
+ apply: (state) => move(state, { ...released(state), closing: false }),
280
+ effects: (_state, event, scope) => {
297
281
  const alreadyStopped = event.stopped === true;
298
282
  const stopRemote = alreadyStopped ? false : event.stopRemote === true || scope.keepAlive === 'stop';
299
283
  const keepSshForIdle = scope.keepAlive === 'idle' && !stopRemote && !alreadyStopped;
@@ -310,12 +294,11 @@ export const TABLE = {
310
294
  },
311
295
  },
312
296
  '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.
297
+ // A timer that fires for a host the user wants again is stale. Refusing keeps "run the idle script" unambiguous;
298
+ // the script re-checks `stillWanted`, and this refusal is logged at debug, not the generic warn level.
316
299
  guard: (state, _event, scope) => (stillWanted(state, scope) ? 'illegal-transition' : true),
317
300
  apply: (state) => state,
318
- effects: () => [],
301
+ effects: () => NO_EFFECTS,
319
302
  },
320
303
  'repair.requested': {
321
304
  guard: (state, _event, scope) => {
@@ -329,39 +312,23 @@ export const TABLE = {
329
312
  effects: (state, event) => [run('repair', epochAfter(state, event.token))],
330
313
  },
331
314
  'repair.finished': {
332
- guard: (state) => (state.activity === 'repair' ? true : 'illegal-transition'),
315
+ guard: ownsActivity('repair'),
333
316
  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()] : []),
317
+ // Today a successful rebuild publishes the frame and marks the UI up; a failed one is silent (the repair script
318
+ // logs its own reason).
319
+ effects: (_state, event) => (event.ok ? [apply({ kind: 'mark-ui-up' }), emit()] : NO_EFFECTS),
337
320
  },
338
321
  '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',
322
+ guard: entryGuard,
323
+ apply: (state, event) => enter(state, 'restart', event.token, progressOf('restarting-remote', { pid: Number(event.pid) || 0, port: Number(event.port) || 0 }), {
344
324
  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
325
  }),
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
- ],
326
+ effects: (state, event) => requestEffects(state, event.token, 'restart'),
360
327
  },
361
328
  'restart.resumed': {
362
- guard: (state) => (state.activity === 'restart' ? true : 'illegal-transition'),
329
+ guard: ownsActivity('restart'),
363
330
  apply: (state, event) => {
364
- // Only the "managed stop was not confirmed" caller warns; a restart cancelled before touching anything resumes plainly.
331
+ // Only the "managed stop was not confirmed" caller warns; a restart cancelled before that resumes plainly.
365
332
  const keptInstance = event.keptInstance === true;
366
333
  return move(state, {
367
334
  status: 'connected',
@@ -380,8 +347,8 @@ export const TABLE = {
380
347
  ],
381
348
  },
382
349
  '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 }),
350
+ guard: ownsActivity('restart'),
351
+ apply: (state, event) => toError(state, event.view),
385
352
  effects: (_state, event, scope) => [
386
353
  apply({ kind: 'mark-detached' }),
387
354
  logFailure(event.phase),
@@ -390,42 +357,16 @@ export const TABLE = {
390
357
  ],
391
358
  },
392
359
  '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
- ],
360
+ guard: entryGuard,
361
+ apply: (state, event) => enter(state, 'stop', event.token, progressOf('stopping-remote', { pid: Number(event.pid) || 0, port: Number(event.port) || 0 })),
362
+ effects: (state, event) => requestEffects(state, event.token, 'stop'),
414
363
  },
415
364
  'stop.refused': {
416
- guard: (state) => (state.activity === 'stop' ? true : 'illegal-transition'),
365
+ guard: ownsActivity('stop'),
417
366
  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
- }
367
+ // Unrestorable: the link vanished while the stop was failing, so publish the coded failure, not a fake state.
368
+ if (event.unrestorable === true)
369
+ return toError(state, event.view);
429
370
  const previous = event.previous;
430
371
  return move(state, {
431
372
  status: previous.status,
@@ -439,9 +380,7 @@ export const TABLE = {
439
380
  event.unrestorable === true
440
381
  ? apply({ kind: 'mark-detached' })
441
382
  : 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).
383
+ // A restored `connected` link is live again: `resumeConnected` restarted the heartbeat the stop disarmed.
445
384
  ...(event.unrestorable === true || event.previous.status !== 'connected'
446
385
  ? []
447
386
  : [arm('heartbeat', scope.delays.heartbeatMs)]),
@@ -450,15 +389,8 @@ export const TABLE = {
450
389
  ],
451
390
  },
452
391
  '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
- }),
392
+ guard: ownsActivity('stop'),
393
+ apply: (state) => released(state),
462
394
  effects: () => [teardown({ stopRemote: false, stopped: true }), apply({ kind: 'mark-detached' }), emit()],
463
395
  },
464
396
  'reattach.requested': {
@@ -469,26 +401,12 @@ export const TABLE = {
469
401
  return 'not-connected';
470
402
  return true;
471
403
  },
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
- ],
404
+ apply: (state, event) => enter(state, 'reattach', event.token, progressOf('restarting-remote', { reason: event.reason })),
405
+ effects: (state, event) => requestEffects(state, event.token, 'reattach'),
488
406
  },
489
407
  '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 }),
408
+ guard: ownsActivity('reattach'),
409
+ apply: (state, event) => toError(state, event.view),
492
410
  effects: (state) => [
493
411
  apply({ kind: 'mark-detached' }),
494
412
  closeLink(),
@@ -501,35 +419,39 @@ export const TABLE = {
501
419
  guard: (state) => (state.desired === 'connected' ? true : 'illegal-transition'),
502
420
  apply: (state, event) => move(state, {
503
421
  reconnectAttempts: event.attempt,
504
- progress: progressOf('reconnecting', { attempt: event.attempt, max: event.max }),
422
+ // A slow retry says when it comes back rather than how many quick attempts were spent: after the fast budget
423
+ // the attempt count alone would read as "the 7th of 5 tries".
424
+ progress: event.slow === true
425
+ ? progressOf('reconnect-waiting', {
426
+ attempt: event.attempt,
427
+ retryInSec: Math.round(event.delayMs / 100) / 10,
428
+ })
429
+ : progressOf('reconnecting', { attempt: event.attempt, max: event.max }),
505
430
  }),
506
431
  effects: (_state, event) => [arm('reconnect', event.delayMs), emit()],
507
432
  },
508
433
  'reconnect.gaveup': {
509
434
  guard: (state) => (state.desired === 'connected' ? true : 'illegal-transition'),
510
435
  apply: (state, event) => move(state, { status: 'error', error: event.view, progress: null }),
511
- effects: () => [emit()],
436
+ effects: () => EMIT_ONLY,
512
437
  },
513
438
  '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).
439
+ // The executor already took the policy decision; the machine only records the outcome the Client renders.
440
+ // `progress` is deliberately left alone: today's `scheduleReconnect` patched only the status, so a dropped link
441
+ // that was not retried keeps the `reconnecting` line it had published.
518
442
  guard: () => true,
519
443
  apply: (state) => move(state, { status: 'disconnected' }),
520
- effects: () => [emit()],
444
+ effects: () => EMIT_ONLY,
521
445
  },
522
446
  'link.cancelled': {
523
447
  guard: () => true,
524
- // Today's `cancelLinkWork` clears unconditionally; the canonical event carries no token, so this cannot be answered here.
448
+ // Today's `cancelLinkWork` clears unconditionally; the event carries no token, so nothing can be checked here.
525
449
  apply: (state) => move(state, { epoch: state.epoch + 1, activity: null }),
526
450
  effects: () => [log('debug', 'link work cancelled')],
527
451
  },
528
452
  shutdown: {
529
453
  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.
454
+ // `activity: null` is today's `cancelLinkWork`; a leftover action name would describe work that no longer runs.
533
455
  apply: (state) => move(state, { closing: true, desired: 'idle', epoch: state.epoch + 1, activity: null }),
534
456
  effects: (_state, _event, scope) => [
535
457
  disarm('reconnect'),
@@ -552,7 +474,7 @@ export const TABLE = {
552
474
  ],
553
475
  },
554
476
  };
555
- /** The state the "the transport dropped under a live link" branch produces (§2.4.2 row 3). */
477
+ /** The state the "the transport dropped under a live link" branch produces. */
556
478
  function transportDropPatch(state) {
557
479
  return {
558
480
  status: 'disconnected',
@@ -1,54 +1,32 @@
1
- /**
2
- * Per-host SSH password storage in DSH's own credential store (`ctx.credentials`), never in
3
- * `hosts.json`; with no credential service nothing is persisted.
4
- *
5
- * Both kernel shapes this store touches live in `kernel-adapter.ts`: the record API and the
6
- * `<scope>/<id>` key grammar, which is replicated there and confirmed against the kernel's own
7
- * parser when one is exposed. A kernel whose grammar moved (`changed`) does not change the keys
8
- * this plugin generates — the stored form is the one already on users' machines — but it is
9
- * reported once, because a save the moved grammar later refuses must not look like a silent no-op.
10
- *
11
- * The same applies to a credential service that is present but whose members changed shape: the
12
- * store answers "not stored" exactly as it does without a service, so that `changed` would make a
13
- * remembered password look forgotten. It is warned about once per store, at the same level as the
14
- * grammar warning.
15
- */
1
+ /** Per-host SSH password storage in DSH's own credential store (`ctx.credentials`), never in `hosts.json`; with no
2
+ * credential service nothing is persisted. The record API and the `<scope>/<id>` grammar live in `kernel-adapter.ts`.
3
+ * A moved grammar (`changed`) does not change the keys this plugin generates — the stored form is the one already on
4
+ * users' machines — but it is reported once, because a later refused save must not look like a silent no-op. A service
5
+ * whose members changed shape gets the same warning: the store answers "not stored" as without a service, and silence
6
+ * would look like amnesia. */
16
7
  import { credentialRecordKey, createKernelAdapter } from './kernel-adapter.js';
17
8
  import { HOST_ID_RE } from './settings.js';
18
9
  import { isPlainObject } from './util.js';
19
10
  const RECORD_SCOPE = 'dsh-remote-go';
20
11
  const RECORD_ID_PREFIX = 'ssh-password-';
21
12
  const PAYLOAD_VERSION = 1;
22
- /**
23
- * DSH addresses a stored record as `<scope>/<id>`, and both segments must match
24
- * `/^[a-z][a-z0-9-]*$/` (`parseCredentialKey` in `@deepseek-ai/dsh-credentials`). A colon-separated
25
- * key such as `dsh-remote-go:ssh-password:h_1` is stored as given but rejected the next time the
26
- * credential document is read — the whole file then fails to load, taking every other credential
27
- * with it. A host id is `h_<base36>`: its only character outside the grammar is the underscore,
28
- * which maps onto `-` without collisions because the issued suffix never contains one. Only an id
29
- * this plugin issued is addressable, so an unexpected value never reaches the document.
30
- * @param hostId - the host id as it appears in `hosts.json`.
31
- * @returns the record key, or `null` when the id is not addressable.
32
- */
13
+ /** DSH addresses a record as `<scope>/<id>` and both segments must match `/^[a-z][a-z0-9-]*$/` (`parseCredentialKey` in
14
+ * `@deepseek-ai/dsh-credentials`): a colon-separated key would be stored as given and rejected on the next read,
15
+ * failing every other credential with it. A host id is `h_<base36>`, whose only out-of-grammar character is the
16
+ * underscore; it maps onto `-` without collisions (the suffix never contains one), so only our ids are addressable. */
33
17
  export function passwordRecordKey(hostId) {
34
18
  if (typeof hostId !== 'string' || !HOST_ID_RE.test(hostId))
35
19
  return null;
36
20
  return credentialRecordKey(RECORD_SCOPE, RECORD_ID_PREFIX + hostId.replace(/_/g, '-'));
37
21
  }
38
- /**
39
- * Build the store for one plugin activation.
40
- * @param options - the kernel context (a fake in tests) and the warning sink.
41
- * @returns the store; every method answers "not stored"/"not saved" instead of throwing.
42
- */
22
+ /** Build the store for one plugin activation; every method answers "not stored"/"not saved" instead of throwing. */
43
23
  export function createSecretStore(options = {}) {
44
24
  const logger = options.logger ?? console;
45
25
  const kernel = createKernelAdapter(options.ctx);
46
26
  let grammarChecked = false;
47
27
  let serviceChangedNoted = false;
48
- /**
49
- * Report a moved key grammar once per store. The keys stay in their stored form on purpose: a
50
- * changed grammar is a kernel we do not recognize, not a reason to orphan every saved password.
51
- */
28
+ // Report a moved key grammar once per store. The keys keep their stored form on purpose: a changed
29
+ // grammar is a kernel we do not recognize, not a reason to orphan every saved password.
52
30
  function noteGrammar() {
53
31
  if (grammarChecked)
54
32
  return;
@@ -65,9 +43,8 @@ export function createSecretStore(options = {}) {
65
43
  noteGrammar();
66
44
  return probe.value;
67
45
  }
68
- // A service that exists but no longer has the record members is not "no credential service":
69
- // answering null silently would present every remembered password as forgotten. Report it
70
- // once per store, like the grammar warning; repeated lookups stay quiet.
46
+ // A present service whose members changed shape is not "no credential service": answering null
47
+ // silently would present every remembered password as forgotten. Report it once per store.
71
48
  if (probe.state === 'changed') {
72
49
  if (!serviceChangedNoted) {
73
50
  serviceChangedNoted = true;