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
@@ -2,28 +2,22 @@ import { REMOTE_START_TIMEOUT_MS, SSH_READY_TIMEOUT_MS } from '../constants.js';
2
2
  import { beginConnectLog } from '../connect-log.js';
3
3
  import { errors } from '../errors.js';
4
4
  import { disposeSsh, scheduleReconnect } from '../host-lifecycle.js';
5
- import { findKnownHostEntries, parseKnownHosts } from '../known-hosts.js';
6
5
  import { layoutForRuntime } from '../layout.js';
7
6
  import { applyManagedNodeFacts, managedNodeVersionFromEngine } from '../node-runtime.js';
8
7
  import { requestHostKey } from '../prompts.js';
8
+ import { registryNamesInstance } from '../remote-web/registry.js';
9
9
  import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
10
10
  import { createRuntimeEffects } from '../runtime/effects.js';
11
- import { isPid, messageOf, nowIso } from '../util.js';
11
+ import { messageOf, nowIso } from '../util.js';
12
12
  import { normalizeVersion, versionsEqual } from '../version.js';
13
13
  import { markConnected } from './attach.js';
14
14
  import { normalizeConnectFailure } from './failures.js';
15
15
  import { LinkCancelled, assertStillWanted, assertTransportOpen, linkTaken } from './guards.js';
16
- import { resolveForeignConflict } from './launch.js';
16
+ import { PATCHED_CARRIER_NOTE, resolveForeignConflict } from './launch.js';
17
17
  import { rememberBound, rememberLaunched } from './ownership.js';
18
- import { captureFingerprint, openTunnelFor, resolveTargetForRuntime, settlePasswordStorage } from './transport.js';
18
+ import { captureFingerprint, knownFingerprintsFor, openTunnelFor, resolveTargetForRuntime, settlePasswordStorage, } from './transport.js';
19
19
  import { verifyRemoteUi } from './verify.js';
20
- /**
21
- * Start the pipeline in the background and make sure its promise never rejects: a listener
22
- * or a step outside the pipeline's own error handling must not become an unhandled
23
- * rejection that Node reports as a process-level failure (L).
24
- * @param ctx - service context.
25
- * @param runtime - host runtime.
26
- */
20
+ /** Start the pipeline in the background and keep its promise off the rejection path, so a listener or a step outside its error handling cannot become an unhandled rejection. */
27
21
  export function startConnectPromise(ctx, runtime) {
28
22
  const run = connectPipeline(ctx, runtime).catch((error) => {
29
23
  ctx.progress.log(runtime, 'debug', 'connect pipeline stopped outside its error path:', messageOf(error));
@@ -34,14 +28,7 @@ export function startConnectPromise(ctx, runtime) {
34
28
  runtime.connectPromise = null;
35
29
  });
36
30
  }
37
- /**
38
- * Re-enter the pipeline after a dropped link. Lives here rather than in the
39
- * lifecycle module so `scheduleReconnect` stays a pure timer with a callback.
40
- *
41
- * The retry is a `connect.requested` with `retry: true`: it must publish `connecting` and clear
42
- * the previous failure, but it must **not** reset the retry budget the user's connect set (R5/H2),
43
- * so the event carries the one difference.
44
- */
31
+ /** Re-enter the pipeline after a dropped link, as a `connect.requested` with `retry: true`: it publishes `connecting` and clears the previous failure but must not reset the retry budget the user's connect set. */
45
32
  async function reconnectNow(ctx, runtime) {
46
33
  if (ctx.state.disposed || runtime.desired !== 'connected')
47
34
  return;
@@ -53,32 +40,18 @@ async function reconnectNow(ctx, runtime) {
53
40
  run: () => startConnectPromise(ctx, runtime),
54
41
  });
55
42
  }
56
- /** A timer callback that starts a retry: report a throw instead of leaving it unhandled (L). */
43
+ /** A timer callback that starts a retry: report a throw instead of leaving it unhandled. */
57
44
  function retryNow(ctx, runtime) {
58
45
  void reconnectNow(ctx, runtime).catch((error) => {
59
46
  ctx.progress.log(runtime, 'warn', 'the automatic retry could not start:', messageOf(error));
60
47
  });
61
48
  }
62
- /**
63
- * Watch one transport for its close. A close is one `transport.closed` event, and the rule
64
- * decides (design-arch §2.4.2) whether it was a stale listener, the teardown's own close, a
65
- * handshake that died (record the loss, settle the parked prompts, log) or a live link that
66
- * dropped (publish `disconnected`, close the listener, ask the retry policy for a timer).
67
- *
68
- * Attached as soon as the transport exists — before `connect()` — because a drop while the
69
- * handshake waits on a host-key prompt must resolve that prompt instead of parking the pipeline
70
- * until its 120 s timeout (H3/M1). This replaces the two listeners this module used to keep
71
- * (a silent handshake one and the live/in-flight one); their work is the event's effects now.
72
- * @param ctx - the orchestration context (the effect owner is bound to it).
73
- * @param runtime - host runtime.
74
- * @param ssh - the transport that was just created.
75
- */
49
+ /** Watch one transport for its close; attached before `connect()` so a drop while a host-key prompt is parked resolves that prompt instead of stalling the pipeline. */
76
50
  function watchTransport(ctx, runtime, ssh) {
77
51
  if (!ssh || typeof ssh.on !== 'function')
78
52
  return;
79
53
  ssh.on('close', () => {
80
- // A transport this runtime no longer dials (replaced, or disposed before a new attempt)
81
- // is not a lost link: its close is the teardown itself.
54
+ // A transport this runtime no longer dials (replaced, or disposed before a new attempt) is not a lost link.
82
55
  if (runtime.ssh !== ssh && runtime.jumpSsh !== ssh)
83
56
  return;
84
57
  if (runtime.closing || runtime.desired !== 'connected')
@@ -87,28 +60,14 @@ function watchTransport(ctx, runtime, ssh) {
87
60
  void dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
88
61
  caller: 'callback',
89
62
  }).then((result) => {
90
- // The rule said "a retry makes sense" (its `arm(reconnect)` effect); the randomized delay,
91
- // the budget and the settings switch stay in `scheduleReconnect`, the single place that
92
- // actually creates the retry timer (never a second loop here, P2b hand-off).
63
+ // The rule only says "a retry makes sense"; `scheduleReconnect` owns the delay, the budget and the switch.
93
64
  const wantsRetry = result.ok && result.effects.some((effect) => effect.type === 'arm' && effect.timer === 'reconnect');
94
65
  if (wantsRetry)
95
66
  scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime));
96
67
  });
97
68
  });
98
69
  }
99
- /**
100
- * Open the transport: direct, or through a jump host with a forwarded stream.
101
- *
102
- * The jump host and the target are separate security contexts. Each one gets its own
103
- * options — its own policy, its own pin and its own `onHostKey` role — so a key confirmed
104
- * for one can never be checked against, or written into, the other (B1).
105
- */
106
- /**
107
- * The dial. It reads only Config/Transport/Reporter/Store itself, but it hands `ctx` to
108
- * `watchTransport`, whose close listener re-enters the pipeline after a drop — and that path needs
109
- * the orchestration context. Narrowing the parameter therefore does not compile; the gate's
110
- * `godCtxParams` entry records exactly that.
111
- */
70
+ /** The dial: direct, or through a jump host with a forwarded stream. The two are separate security contexts, each with its own policy, pin and `onHostKey` role, so a key confirmed for one can never be checked against, or written into, the other. It reads only Config/Transport/Reporter/Store itself but hands `ctx` to `watchTransport`, whose close listener re-enters the pipeline, so the parameter cannot be narrowed. */
112
71
  async function openTransport(ctx, runtime, target) {
113
72
  const settings = ctx.settings();
114
73
  const auth = () => ({
@@ -118,10 +77,8 @@ async function openTransport(ctx, runtime, target) {
118
77
  });
119
78
  const buildOptions = (resolved, role, sock) => {
120
79
  const isJump = role === 'jump';
121
- // A per-host policy and pin describe the saved target. A jump host only obeys the
122
- // global policy and, at most, a pin remembered for this session (it is not persisted).
123
- const hostKeyPolicy = isJump ? settings.hostKeyPolicy : (runtime.entry.hostKeyPolicy ?? settings.hostKeyPolicy);
124
80
  const resolvedPort = resolved.port ?? 22;
81
+ const hostKeyPolicy = isJump ? settings.hostKeyPolicy : (runtime.entry.hostKeyPolicy ?? settings.hostKeyPolicy);
125
82
  const jumpPinMatches = isJump &&
126
83
  runtime.jumpFingerprint?.host === resolved.host &&
127
84
  (Number(runtime.jumpFingerprint?.port) || 22) === resolvedPort;
@@ -134,8 +91,6 @@ async function openTransport(ctx, runtime, target) {
134
91
  host: resolved.host,
135
92
  port: resolvedPort,
136
93
  username: resolved.username ?? resolved.user ?? null,
137
- // The key path expands against the *user* home (`~/.ssh/...`), never against
138
- // DSH_HOME, so the SSH layer needs to know which one that is.
139
94
  home: ctx.userHome(),
140
95
  auth: auth(),
141
96
  identityFiles: resolved.identityFiles ?? [],
@@ -156,13 +111,12 @@ async function openTransport(ctx, runtime, target) {
156
111
  return;
157
112
  }
158
113
  ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.jumpHost.host, jump: true });
114
+ const jumpMaterial = await ctx.deps.loadSshMaterial({ home: ctx.userHome() });
159
115
  const jumpTarget = {
160
116
  ...target.jumpHost,
161
117
  username: target.jumpHost.user ?? target.username,
162
- knownFingerprints: findKnownHostEntries(parseKnownHosts((await ctx.deps.loadSshMaterial({ home: ctx.userHome() })).knownHostsText), target.jumpHost.host, target.jumpHost.port ?? 22).map((item) => item.fingerprint),
118
+ knownFingerprints: knownFingerprintsFor(jumpMaterial, target.jumpHost.host, target.jumpHost.port ?? 22),
163
119
  };
164
- // An edited `jumpHost` is a different machine: a pin remembered for the previous jump host
165
- // must not make the new one fail as `host-key-changed` (review blocker 3).
166
120
  const rememberedJump = runtime.jumpFingerprint;
167
121
  const rememberedJumpPort = (Number(rememberedJump?.port) || 22) === (jumpTarget.port ?? 22);
168
122
  if (rememberedJump !== null && (!rememberedJumpPort || rememberedJump.host !== jumpTarget.host)) {
@@ -172,8 +126,6 @@ async function openTransport(ctx, runtime, target) {
172
126
  runtime.jumpSsh = ctx.deps.sshFactory(buildOptions(jumpTarget, 'jump'));
173
127
  watchTransport(ctx, runtime, runtime.jumpSsh);
174
128
  await runtime.jumpSsh.connect();
175
- // The jump host's key is settled (its own context above); from here the fingerprint the host
176
- // card describes is the target's, which `captureFingerprint` fills once it answers.
177
129
  runtime.fingerprint = null;
178
130
  ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host, via: target.jumpHost.host });
179
131
  const stream = await runtime.jumpSsh.forwardOut(target.host, target.port ?? 22);
@@ -184,26 +136,26 @@ async function openTransport(ctx, runtime, target) {
184
136
  async function connectPipeline(ctx, runtime) {
185
137
  const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
186
138
  const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
187
- // Every attempt (a user connect or a scheduled retry) entered through `connect.requested`,
188
- // which owns `closing`, `transportLost`, the timer disarms and the `connecting` card.
139
+ // Guards after every await: the link must still be wanted and the transport open, so a late write cannot revive it.
140
+ const gate = () => {
141
+ assertStillWanted(ctx, runtime);
142
+ assertTransportOpen(runtime);
143
+ };
144
+ // Every attempt entered through `connect.requested`, which owns `closing`, `transportLost`, the disarms and the card.
189
145
  runtime.alongsidePids = [];
190
- // Kill rights belong to this connection: a fresh connect starts with no launched pids.
191
146
  runtime.launched = new Map();
192
147
  runtime.bound = null;
193
148
  runtime.tunnelRepairFailures = 0;
194
149
  runtime.nextTunnelRepairAt = 0;
195
150
  let remoteStarted = false;
196
151
  let layout = null;
197
- // Whether the SSH transport ever came up during this attempt: a link that was up and then
198
- // dropped is a connection event and is retried like one (H3).
199
152
  let transportUp = false;
200
153
  try {
201
154
  const target = await resolveTargetForRuntime(ctx, runtime);
202
155
  assertStillWanted(ctx, runtime);
156
+ const { host: targetHost, port: targetPort, username } = target;
203
157
  const viaJump = target.jumpHost ? ` via ${target.jumpHost.host}` : '';
204
- log('debug', `target resolved: ${target.username ?? '(default)'}@${target.host}:${target.port}${viaJump}`);
205
- // A password-auth host may have one remembered: load it before the transport
206
- // is opened, so reconnect and background retries work without a prompt.
158
+ log('debug', `target resolved: ${username ?? '(default)'}@${targetHost}:${targetPort}${viaJump}`);
207
159
  if (runtime.entry.auth?.type === 'password' && !runtime.password && ctx.secrets) {
208
160
  const remembered = await ctx.secrets.get(runtime.id);
209
161
  if (remembered) {
@@ -213,38 +165,28 @@ async function connectPipeline(ctx, runtime) {
213
165
  assertStillWanted(ctx, runtime);
214
166
  }
215
167
  phase('ssh', 'ssh-connecting', { host: runtime.entry.name });
216
- // An idle host keeps its SSH session for a fast resume; this attempt replaces it, so the
217
- // old one is released here instead of being overwritten (and leaked) by openTransport.
168
+ // An idle host keeps its SSH session for a fast resume; this attempt replaces it, so release it, do not leak it.
218
169
  if (runtime.ssh !== null || runtime.jumpSsh !== null) {
219
170
  log('debug', 'releasing the transport kept by the idle policy before dialling again');
220
171
  await disposeSsh(runtime);
221
172
  assertStillWanted(ctx, runtime);
222
173
  }
223
174
  await openTransport(ctx, runtime, target);
224
- // The transport is the link from here on: a drop during probe/bootstrap is a lost
225
- // connection too, so the close handler is attached before the remaining steps (H3).
226
- assertStillWanted(ctx, runtime);
227
- assertTransportOpen(runtime);
175
+ gate();
228
176
  transportUp = true;
229
- log('info', `SSH connected to ${target.host}:${target.port} as ${target.username ?? '(default)'} (fingerprint ${runtime.fingerprint?.sha256 ?? 'unknown'})`);
230
- // SSH accepted the credential: this is the point the password is proven, before any
231
- // bootstrap step can fail and force the user to type it again.
177
+ const fingerprint = runtime.fingerprint?.sha256 ?? 'unknown';
178
+ log('info', `SSH connected to ${targetHost}:${targetPort} as ${username ?? '(default)'} (fingerprint ${fingerprint})`);
179
+ // SSH accepted the credential: prove the password now, before a later bootstrap failure makes the user retype it.
232
180
  await settlePasswordStorage(ctx, runtime, log);
233
181
  assertStillWanted(ctx, runtime);
234
182
  phase('probe', 'probing');
235
183
  let facts = await ctx.deps.probe(runtime.ssh);
236
- assertStillWanted(ctx, runtime);
237
- assertTransportOpen(runtime);
184
+ gate();
238
185
  const freeGb = Math.round(Number(facts.diskFreeKb ?? 0) / 1_048_576);
239
186
  log('debug', `probe: ${facts.os}/${facts.arch} · ${String(facts.osName ?? 'unknown OS')} · node ${facts.nodeVersion ?? 'not found'} · ${freeGb} GB free`);
240
- // The runtime always runs on a plugin-owned Node (`~/.dsh/remote-go/node`),
241
- // whether or not the remote already has one: a shared system/nvm Node is
242
- // exactly what makes "works for my other project" break the remote DSH.
243
- // There is no system fallback on purpose, so this failure is the connection's.
244
187
  const profile = ctx.settings().bootstrap.profile;
245
188
  const managedVersion = managedNodeVersionFromEngine(ctx.engineNodeRange());
246
- // A probe that did not report $HOME cannot address the remote layout: `remoteLayout`
247
- // throws instead of building a literal-tilde path (H1).
189
+ // A probe that did not report $HOME cannot address the remote layout: `layoutForRuntime` throws.
248
190
  const nodeLayout = layoutForRuntime({ facts });
249
191
  log('info', `managed Node: expecting v${managedVersion} in ${nodeLayout.nodeDir}`);
250
192
  const managed = await ctx.deps.ensureNode(runtime.ssh, {
@@ -253,12 +195,11 @@ async function connectPipeline(ctx, runtime) {
253
195
  version: managedVersion,
254
196
  onProgress: (event) => ctx.progress.nodeProgress(runtime, event),
255
197
  });
256
- assertStillWanted(ctx, runtime);
257
- assertTransportOpen(runtime);
258
- // The probe above reported every field, so the merged object is a full `RemoteFacts`; the
259
- // helper's own return type stays `Partial` because it also accepts a partial input.
198
+ gate();
199
+ // The probe reported every field, so the merged object is a full `RemoteFacts`.
260
200
  facts = applyManagedNodeFacts(facts, managed);
261
- log('info', `managed Node ${managed.version}${managed.installed ? ' installed' : ' reused'} at ${managed.nodeBinDir}`);
201
+ const { version: nodeVersion, installed, nodeBinDir } = managed;
202
+ log('info', `managed Node ${nodeVersion}${installed ? ' installed' : ' reused'} at ${nodeBinDir}`);
262
203
  runtime.facts = facts;
263
204
  const targetVersion = ctx.localVersion();
264
205
  if (!targetVersion) {
@@ -271,29 +212,25 @@ async function connectPipeline(ctx, runtime) {
271
212
  log('info', `runtime plan ${plan.level}: ${plan.reason.en}`);
272
213
  phase('start', 'starting-remote', { level: plan.level });
273
214
  layout = layoutForRuntime(runtime);
215
+ // Adopt an instance left by a previous local process before the npx preflight: adoption must not need the registry.
274
216
  let webInfo = null;
275
- // Adopt an instance left running by a previous local process (keep-alive).
276
- // Checked before the npx preflight: an adoptable instance should not require
277
- // registry access just to reconnect.
278
217
  try {
279
218
  const adopted = await ctx.deps.adopt(runtime.ssh, layout, { profile });
280
219
  const adoptedVersion = adopted?.version ? normalizeVersion(adopted.version) : null;
220
+ const mismatch = `running remote web version ${adoptedVersion} != ${targetVersion}`;
281
221
  if (adopted && (!adoptedVersion || versionsEqual(adoptedVersion, targetVersion))) {
282
222
  webInfo = { ...adopted, logPath: layout.logFile, startedAt: nowIso(), rawLine: '' };
283
223
  log('info', `adopted running remote web pid=${adopted.pid} port=${adopted.port}`);
284
- // Only a record written by a launch script proves the process is ours to stop; a
285
- // re-attached record is hosted, not owned (B1). It is still the instance this
286
- // connection is bound to, so the explicit "Stop remote DSH" may stop it by identity.
224
+ // Only a launch record proves the process is ours to stop; a re-attached one is merely hosted.
287
225
  if (adopted.origin !== 'reattach')
288
226
  await rememberLaunched(ctx, runtime, adopted.pid, layout, profile);
289
227
  else
290
228
  await rememberBound(ctx, runtime, adopted.pid, layout, profile, 'reattach');
291
229
  }
292
230
  else if (adopted && adopted.origin !== 'reattach') {
293
- log('info', `running remote web version ${adoptedVersion} != ${targetVersion}; stopping it and starting a matching instance`);
294
- // The old process owns the same `~/.dsh` profile; leaving it running next
295
- // to the new one would share session files with a stale version.
231
+ log('info', `${mismatch}; stopping it and starting a matching instance`);
296
232
  try {
233
+ // The old process owns the same `~/.dsh` profile: leaving it next to the new one would share session files.
297
234
  await ctx.deps.stopWeb(runtime.ssh, layout, { pid: adopted.pid });
298
235
  }
299
236
  catch (error) {
@@ -301,7 +238,7 @@ async function connectPipeline(ctx, runtime) {
301
238
  }
302
239
  }
303
240
  else if (adopted) {
304
- log('warn', `running remote web version ${adoptedVersion} != ${targetVersion}, but it was only re-attached; leaving it running`);
241
+ log('warn', `${mismatch}, but it was only re-attached; leaving it running`);
305
242
  }
306
243
  else {
307
244
  log('debug', 'adopt: no running remote web to reuse');
@@ -310,20 +247,16 @@ async function connectPipeline(ctx, runtime) {
310
247
  catch (error) {
311
248
  log('debug', 'adopt check failed:', messageOf(error));
312
249
  }
313
- assertStillWanted(ctx, runtime);
314
- assertTransportOpen(runtime);
250
+ gate();
315
251
  if (!webInfo) {
316
- // The registry row we refused to adopt (stale launch marker, unresponsive
317
- // HTTP, ...) still names a process on this ~/.dsh profile. Starting a second
318
- // one would let two clients write the same session files. A record written by a
319
- // re-attach names a process this plugin did not launch, so it is never stopped here.
252
+ // A row we refused to adopt still names a process on this ~/.dsh profile: two clients must not write the same session files.
320
253
  const leftover = await ctx.deps.readRegistry(runtime.ssh, layout);
321
254
  assertStillWanted(ctx, runtime);
322
255
  const leftoverPid = Number(leftover?.pid ?? 0);
323
256
  if (leftover?.origin === 'reattach') {
324
257
  log('info', `leaving a re-attached remote web instance alone (pid ${leftoverPid || 'unknown'})`);
325
258
  }
326
- else if (leftover?.dshHome === layout.dshHome && leftover?.profile === profile && isPid(leftoverPid)) {
259
+ else if (registryNamesInstance(leftover, layout, profile, leftoverPid)) {
327
260
  try {
328
261
  await ctx.deps.stopWeb(runtime.ssh, layout, { pid: leftoverPid });
329
262
  log('info', `stopped a non-adoptable remote web instance pid=${leftoverPid}`);
@@ -333,18 +266,15 @@ async function connectPipeline(ctx, runtime) {
333
266
  }
334
267
  }
335
268
  await resolveForeignConflict(ctx, runtime, layout, profile);
336
- assertStillWanted(ctx, runtime);
337
- assertTransportOpen(runtime);
269
+ gate();
338
270
  phase('bootstrap', 'bootstrapping', { level: plan.level });
339
- // Resolve the exact package in the foreground first: a cold npx download
340
- // belongs in the connect error, not in a detached process that only leaves a
341
- // log behind. This also warms the cache for the real start below.
271
+ // Resolve the exact package in the foreground first: a cold npx download belongs in the connect error, not in a
272
+ // detached process that only leaves a log behind.
342
273
  log('info', `npx preflight: resolving @deepseek-ai/dsh@${plan.start.targetVersion}`);
343
274
  const onStdout = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion);
344
275
  const onStderr = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion);
345
276
  await ctx.deps.preflight(runtime.ssh, plan, { onStdout, onStderr });
346
- assertStillWanted(ctx, runtime);
347
- assertTransportOpen(runtime);
277
+ gate();
348
278
  log('info', `npx preflight ready: @deepseek-ai/dsh@${plan.start.targetVersion}`);
349
279
  phase('start', 'starting-remote', { level: plan.level });
350
280
  webInfo = await ctx.deps.startWeb(runtime.ssh, {
@@ -356,14 +286,10 @@ async function connectPipeline(ctx, runtime) {
356
286
  });
357
287
  log('info', `remote DSH started: pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`);
358
288
  }
359
- assertStillWanted(ctx, runtime);
360
- assertTransportOpen(runtime);
361
- if (webInfo.browserCarrier === 'patched') {
362
- log('info', 'the remote profile disables api-remotes (browser Remote-Event carrier); re-enabled it for this launch');
363
- }
289
+ gate();
290
+ if (webInfo.browserCarrier === 'patched')
291
+ log('info', PATCHED_CARRIER_NOTE);
364
292
  remoteStarted = true;
365
- // Only the instance launched by this connection's start script may be stopped later;
366
- // an adopted one was already recorded above only when its record proves a launch.
367
293
  if (webInfo.adopted !== true)
368
294
  await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile);
369
295
  assertStillWanted(ctx, runtime);
@@ -387,27 +313,19 @@ async function connectPipeline(ctx, runtime) {
387
313
  assertStillWanted(ctx, runtime);
388
314
  phase('verifying', 'verifying');
389
315
  await verifyRemoteUi(ctx, runtime, webInfo.port, webInfo.token, tunnel.localPort);
390
- assertStillWanted(ctx, runtime);
391
- assertTransportOpen(runtime);
392
- // The remote UI is reachable both ways: the desktop half hands the loopback origin to a
393
- // Chromium guest, and the browser half frames it through the same-origin proxy (which strips
394
- // any X-Frame-Options). Either way this exchange proves the launch token works.
316
+ gate();
317
+ // The remote UI is reachable both ways (desktop guest and same-origin proxy): the exchange proves the launch token.
395
318
  runtime.remote.uiReady = true;
396
319
  await ctx.store.patchHost(runtime.id, { lastOpenedAt: nowIso() });
397
- // The store write is an await: the user may have disconnected or deleted the host while
398
- // it was in flight, and a late write must not resurrect the link (H4).
399
- assertStillWanted(ctx, runtime);
400
- assertTransportOpen(runtime);
320
+ gate();
321
+ // The store write is an await: a disconnect may land meanwhile, and a late write must not resurrect the link.
401
322
  runtime.entry = ctx.store.getHost(runtime.id) ?? runtime.entry;
402
323
  if (ctx.settings().saveTokens) {
403
324
  await ctx.store.saveToken(runtime.id, webInfo.token);
404
325
  assertStillWanted(ctx, runtime);
405
326
  }
406
- // Last gate before publishing: never report a connected host that the user just removed
407
- // or disconnected (H4), and never dereference a tunnel this pipeline no longer owns.
408
- assertStillWanted(ctx, runtime);
409
- assertTransportOpen(runtime);
410
- // `connect.succeeded` publishes `activeHostId` (the `publish-active-host` patch).
327
+ gate();
328
+ // Last gate before publishing: never report a host the user just removed or a tunnel this pipeline no longer owns.
411
329
  await markConnected(ctx, runtime);
412
330
  const localPort = runtime.tunnel?.localPort ?? runtime.remote.localPort ?? '?';
413
331
  log('info', `connected: remote ${runtime.remote.version} on 127.0.0.1:${localPort}`);
@@ -415,27 +333,19 @@ async function connectPipeline(ctx, runtime) {
415
333
  catch (error) {
416
334
  // Phase is cleared with the status; capture it first so the log says where it stopped.
417
335
  const failedPhase = runtime.phase;
418
- // The transport was up earlier in this attempt and is gone now: the link dropped, which
419
- // is what the retry policy exists for, even while the remote was still being set up (H3).
336
+ // The link was up earlier in this attempt and is gone now: it dropped, which is what the retry policy is for.
420
337
  const droppedTransport = runtime.transportLost === true || (transportUp === true && runtime.ssh?.connected !== true);
338
+ // The transition owns the state, the teardown and the failure lines; the caller keeps only its own
339
+ // publication point.
421
340
  const cancelled = error instanceof LinkCancelled || linkTaken(ctx, runtime);
422
- // The user's "no" is read *before* the failure transition: `connect.failed` clears the flag
423
- // for the next attempt (today's catch reset it right after the decision), and the decision
424
- // itself still has to see it. This is the H2 "a refused prompt is final" rule.
341
+ // The user's "no" is read before the failure transition clears the flag: a refused prompt is final.
425
342
  const saidNo = runtime.connectCancelled === true;
426
- // The transition owns the state, the teardown and the failure lines; the caller only keeps
427
- // its own publication point (the retry decision below emits exactly like the old code) and
428
- // the one informational line the cancel branch used to write.
429
343
  const event = cancelled
430
344
  ? { type: 'connect.cancelled' }
431
345
  : { type: 'connect.failed', view: normalizeConnectFailure(runtime, error), phase: failedPhase };
432
346
  await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
433
347
  caller: 'script',
434
348
  emit: false,
435
- // "A remote was started in this attempt" is this pipeline's own flag (it becomes true
436
- // before the remote block is written, and survives a failure inside the registry write);
437
- // the scope can only see the block. Pass the caller's verdict so a cancellation after the
438
- // remote started still honours the `stop` keep-alive policy.
439
349
  teardown: {
440
350
  stopRemote: remoteStarted && runtime.entry.keepAlive === 'stop',
441
351
  keepRemote: remoteStarted && runtime.entry.keepAlive !== 'stop',
@@ -443,9 +353,7 @@ async function connectPipeline(ctx, runtime) {
443
353
  });
444
354
  if (cancelled)
445
355
  log('info', 'connect cancelled by disconnect');
446
- // One place decides whether a failed attempt is retried, and the budget lives in
447
- // `scheduleReconnect` (H2). A user's "no" (host-key/conflict prompt) is final, and a
448
- // first manual connect that never reached the remote is reported instead of looping.
356
+ // One place decides whether a failed attempt is retried, and the budget lives in `scheduleReconnect`.
449
357
  if (!cancelled) {
450
358
  const retryable = runtime.error?.retryable !== false && !saidNo;
451
359
  const repairAttempt = (Number(runtime.reconnectAttempts) || 0) > 0;
@@ -458,13 +366,8 @@ async function connectPipeline(ctx, runtime) {
458
366
  runtime.connectPromise = null;
459
367
  }
460
368
  }
461
- /**
462
- * Arm the next automatic attempt after a failed connect/reconnect; `scheduleReconnect`
463
- * owns the settings gate and the attempt budget, so a spent budget is reported once.
464
- * @param {object} ctx - service context.
465
- * @param {object} runtime - host runtime.
466
- */
467
- function scheduleConnectRetry(ctx, runtime) {
369
+ /** Arm the next automatic attempt; `scheduleReconnect` owns the settings gate and the budget, so a spent budget is reported once. Exported for the one-shot actions whose failure leaves no usable transport (`reattach.ts`): they must hand the link back to the same retry loop instead of parking at an error card. */
370
+ export function scheduleConnectRetry(ctx, runtime) {
468
371
  if (ctx.state.disposed === true || runtime.desired !== 'connected')
469
372
  return;
470
373
  if (!runtime.entry.autoReconnect || !ctx.settings().autoReconnect.enabled)
@@ -1,8 +1,4 @@
1
- /**
2
- * The re-attach to a remote web that restarted on its own (plugin-market update, supervisor,
3
- * remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel, take the
4
- * new launch token and verify. The SSH session and the host entry are untouched.
5
- */
1
+ /** The re-attach to a remote web that restarted on its own (plugin-market update, supervisor, remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel, take the new launch token and verify. The SSH session and the host entry are untouched. */
6
2
  import { REMOTE_REATTACH_ATTEMPTS, REMOTE_REATTACH_INTERVAL_MS } from '../constants.js';
7
3
  import { errors, toErrorView } from '../errors.js';
8
4
  import { closeTunnel, endLinkWork, isLinkWorkCurrent } from '../host-lifecycle.js';
@@ -14,30 +10,20 @@ import { nowIso, sleep } from '../util.js';
14
10
  import { normalizeVersion, versionsEqual } from '../version.js';
15
11
  import { markConnected, recordRestart } from './attach.js';
16
12
  import { SSH_CLOSED_DETAIL } from './failures.js';
17
- import { LinkCancelled } from './guards.js';
13
+ import { LinkCancelled, linkActionState } from './guards.js';
18
14
  import { rememberBound } from './ownership.js';
15
+ import { scheduleConnectRetry } from './pipeline.js';
19
16
  import { openTunnelFor } from './transport.js';
20
17
  import { verifyRemoteUi } from './verify.js';
21
- /**
22
- * Re-attach to a remote web that restarted on its own (plugin-market update, supervisor,
23
- * remote reboot): re-read the real pid/port, refresh `run/web.json`, rebuild the tunnel,
24
- * take the new launch token and verify. The SSH session and the host entry are untouched.
25
- *
26
- * @param ctx - service context.
27
- * @param runtime - host runtime the watchdog decided is unreachable.
28
- * @param info - why the re-attach was requested.
29
- * @returns whether the re-attach started.
30
- */
31
18
  export async function reattachHost(ctx, runtime, info = {}) {
32
- if (runtime.status !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null) {
19
+ if (linkActionState(runtime) !== 'connected')
33
20
  return { accepted: false, reason: 'not-connected' };
34
- }
35
21
  if (runtime.connectPromise || runtime.linkBusy !== null)
36
22
  return { accepted: false, reason: 'busy' };
37
- // One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`);
38
- // the token is the old `beginLinkWork` one so the late-write filter keeps its semantics.
39
23
  const token = (Number(runtime.linkToken) || 0) + 1;
40
24
  const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable';
25
+ // One transition owns `activity`/`epoch`, the `connecting` card and the action start (`run`); the token
26
+ // is the old `beginLinkWork` one so the late-write filter keeps its semantics.
41
27
  const event = { type: 'reattach.requested', token, reason };
42
28
  await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
43
29
  caller: 'script',
@@ -55,11 +41,6 @@ export async function reattachHost(ctx, runtime, info = {}) {
55
41
  });
56
42
  return { accepted: true };
57
43
  }
58
- /**
59
- * The action body: the re-attach re-reads the remote state, rewrites the run registry, rebuilds the
60
- * tunnel and verifies the UI, so it spans all six slices exactly like its entry point — the same
61
- * `ConnectCtx`, not a copied intersection (the gate's `godCtxParams` entries name it).
62
- */
63
44
  async function runReattach(ctx, runtime, info, token) {
64
45
  const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
65
46
  const phase = (name, code, params) => ctx.progress.phase(runtime, name, code, params);
@@ -69,27 +50,24 @@ async function runReattach(ctx, runtime, info, token) {
69
50
  const reason = typeof info?.reason === 'string' && info.reason !== '' ? info.reason : 'remote-unreachable';
70
51
  let tunnelCreated = false;
71
52
  try {
72
- // `reattach.requested` already disarmed the timers and published the `restarting-remote` card.
73
53
  log('info', `remote restart suspected: ${reason}; re-reading the remote state`);
74
- // A restart takes a moment to print its new readiness line: retry before giving up.
75
54
  const attempts = Math.max(1, Number(ctx.timers.reattachAttempts) || REMOTE_REATTACH_ATTEMPTS);
76
55
  const intervalMs = Math.max(0, Number(ctx.timers.reattachIntervalMs ?? REMOTE_REATTACH_INTERVAL_MS) || 0);
77
56
  let resolved = null;
57
+ // A restart takes a moment to print its new readiness line: retry before giving up.
78
58
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
79
59
  if (!isLinkWorkCurrent(runtime, token))
80
60
  return;
81
61
  resolved = await ctx.deps.resolveRemote(runtime.ssh, layout, { profile });
82
62
  if (resolved?.ok === true)
83
63
  break;
84
- log('debug', `re-attach: remote state not ready yet (${resolved?.reason ?? 'unreadable'}), attempt ${attempt}/${attempts}`);
64
+ const why = resolved?.reason ?? 'unreadable';
65
+ log('debug', `re-attach: remote state not ready yet (${why}), attempt ${attempt}/${attempts}`);
85
66
  if (attempt < attempts && intervalMs > 0)
86
67
  await sleep(intervalMs);
87
68
  }
88
69
  if (!isLinkWorkCurrent(runtime, token))
89
70
  return;
90
- // `resolved?.ok !== true` is the same test as `!resolved || resolved.ok !== true`, and it is
91
- // the form the compiler can narrow: with `strictNullChecks` off the disjunction's `!resolved`
92
- // arm widens the branch back to the whole union.
93
71
  if (resolved?.ok !== true) {
94
72
  const detail = resolved?.reason === 'no-token'
95
73
  ? {
@@ -104,8 +82,8 @@ async function runReattach(ctx, runtime, info, token) {
104
82
  technical: `reason=${resolved?.reason ?? 'unknown'} fromPort=${fromPort ?? 'unknown'}`,
105
83
  });
106
84
  }
107
- // A takeover needs the new launch token: a real DSH rejects `/?token=` and a cookie-less
108
- // request, so an empty token can never be treated as success (B4).
85
+ // A takeover needs the new launch token: a real DSH rejects `/?token=` and a cookie-less request,
86
+ // so an empty token can never be treated as success.
109
87
  if (typeof resolved.token !== 'string' || resolved.token === '') {
110
88
  throw errors.remoteUnreachable({
111
89
  zh: '远端 DSH 重启后没有留下可用的 launch token,无法自动重新挂载;请点「重启」或「重连」。',
@@ -114,16 +92,15 @@ async function runReattach(ctx, runtime, info, token) {
114
92
  }
115
93
  const targetVersion = ctx.localVersion();
116
94
  const remoteVersion = typeof resolved.version === 'string' && resolved.version !== '' ? normalizeVersion(resolved.version) : null;
95
+ // A different DSH under the same ~/.dsh would show a UI that does not match this machine; the
96
+ // user's remedy is the explicit restart, which launches the pinned version.
117
97
  if (remoteVersion && targetVersion && !versionsEqual(remoteVersion, targetVersion)) {
118
- // A different DSH under the same ~/.dsh would show a UI that does not match this machine;
119
- // the user's remedy is the explicit restart, which launches the pinned version.
120
98
  throw errors.versionMismatch(targetVersion, remoteVersion);
121
99
  }
122
- if (remoteVersion === null) {
100
+ if (remoteVersion === null)
123
101
  log('warn', 're-attach: the running DSH version could not be proven; keeping it unknown, not assuming the local one');
124
- }
125
- // The pid that actually listens may differ from the wrapper this connection launched (npx
126
- // spawns the DSH). Keep the kill right only for the pid we are now attached to.
102
+ // The pid that listens may differ from the wrapper this connection launched (npx spawns the DSH):
103
+ // keep the kill right only for the pid we are now attached to.
127
104
  if (runtime.launched instanceof Map) {
128
105
  for (const pid of [...runtime.launched.keys()]) {
129
106
  if (pid !== resolved.pid)
@@ -173,8 +150,8 @@ async function runReattach(ctx, runtime, info, token) {
173
150
  await ctx.store.saveToken(runtime.id, resolved.token);
174
151
  if (!isLinkWorkCurrent(runtime, token))
175
152
  return;
176
- // The re-attached instance is now the one this connection is bound to. It stays out of
177
- // `launched` (a restart must not kill it), but the explicit stop action may end exactly it.
153
+ // The re-attached instance is now the one this connection is bound to: it stays out of
154
+ // `launched` (a restart must not kill it), but the explicit stop may end exactly it.
178
155
  await rememberBound(ctx, runtime, resolved.pid, layout, profile, 'reattach');
179
156
  if (!isLinkWorkCurrent(runtime, token))
180
157
  return;
@@ -197,17 +174,22 @@ async function runReattach(ctx, runtime, info, token) {
197
174
  const view = error instanceof LinkCancelled
198
175
  ? toErrorView(errors.network(SSH_CLOSED_DETAIL, { technical: 'reason=ssh-closed during re-attach' }))
199
176
  : toErrorView(error);
200
- // The transition owns the error state, the listener release, the heartbeat disarm, the
201
- // failure lines (`logFailure` reads the phase it is about to clear) and the publication.
177
+ // The transition owns the error state, the listener release, the heartbeat disarm, the failure lines
178
+ // (which read the phase they are about to clear) and the publication.
202
179
  const failure = { type: 'reattach.failed', view };
203
180
  await dispatch(createRuntimeEffects(ctx), runtime, failure, scopeFactsFor(ctx, runtime, failure), {
204
181
  caller: 'script',
205
182
  emit: false,
206
183
  });
184
+ // A re-attach that lost the transport (the stall the probe saw first) leaves no usable link: hand it back to the
185
+ // retry loop, otherwise the error card would wait for a click while the network has already recovered. A policy
186
+ // failure (no launch token, version mismatch) stays terminal — reconnecting cannot fix it.
187
+ if (runtime.ssh?.connected !== true || view.code === 'network')
188
+ scheduleConnectRetry(ctx, runtime);
207
189
  ctx.emitState();
208
190
  }
209
191
  finally {
210
- // A listener this action created must never outlive the action (see runRestart).
192
+ // A listener this action created must never outlive the action (see `runRestart`).
211
193
  if (tunnelCreated && !isLinkWorkCurrent(runtime, token))
212
194
  await closeTunnel(runtime);
213
195
  endLinkWork(runtime, token);
@@ -4,7 +4,6 @@ export async function readRegistryQuietly(ctx, runtime, layout) {
4
4
  return await ctx.deps.readRegistry(runtime.ssh, layout);
5
5
  }
6
6
  catch (error) {
7
- // swallow-ok: registry absence only means the restart cannot attribute the running pid
8
7
  ctx.progress.log(runtime, 'debug', 'restart: registry read failed:', messageOf(error));
9
8
  return null;
10
9
  }