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,473 @@
1
+ import { REMOTE_START_TIMEOUT_MS, SSH_READY_TIMEOUT_MS } from '../constants.js';
2
+ import { beginConnectLog } from '../connect-log.js';
3
+ import { errors } from '../errors.js';
4
+ import { disposeSsh, scheduleReconnect } from '../host-lifecycle.js';
5
+ import { findKnownHostEntries, parseKnownHosts } from '../known-hosts.js';
6
+ import { layoutForRuntime } from '../layout.js';
7
+ import { applyManagedNodeFacts, managedNodeVersionFromEngine } from '../node-runtime.js';
8
+ import { requestHostKey } from '../prompts.js';
9
+ import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
10
+ import { createRuntimeEffects } from '../runtime/effects.js';
11
+ import { isPid, messageOf, nowIso } from '../util.js';
12
+ import { normalizeVersion, versionsEqual } from '../version.js';
13
+ import { markConnected } from './attach.js';
14
+ import { normalizeConnectFailure } from './failures.js';
15
+ import { LinkCancelled, assertStillWanted, assertTransportOpen, linkTaken } from './guards.js';
16
+ import { resolveForeignConflict } from './launch.js';
17
+ import { rememberBound, rememberLaunched } from './ownership.js';
18
+ import { captureFingerprint, openTunnelFor, resolveTargetForRuntime, settlePasswordStorage } from './transport.js';
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
+ */
27
+ export function startConnectPromise(ctx, runtime) {
28
+ const run = connectPipeline(ctx, runtime).catch((error) => {
29
+ ctx.progress.log(runtime, 'debug', 'connect pipeline stopped outside its error path:', messageOf(error));
30
+ });
31
+ runtime.connectPromise = run;
32
+ void run.finally(() => {
33
+ if (runtime.connectPromise === run)
34
+ runtime.connectPromise = null;
35
+ });
36
+ }
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
+ */
45
+ async function reconnectNow(ctx, runtime) {
46
+ if (ctx.state.disposed || runtime.desired !== 'connected')
47
+ return;
48
+ await disposeSsh(runtime);
49
+ // A dropped link's retry is a new connection too: start from a clean log.
50
+ beginConnectLog(runtime);
51
+ const event = { type: 'connect.requested', token: Number(runtime.linkToken) || 0, retry: true };
52
+ await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
53
+ run: () => startConnectPromise(ctx, runtime),
54
+ });
55
+ }
56
+ /** A timer callback that starts a retry: report a throw instead of leaving it unhandled (L). */
57
+ function retryNow(ctx, runtime) {
58
+ void reconnectNow(ctx, runtime).catch((error) => {
59
+ ctx.progress.log(runtime, 'warn', 'the automatic retry could not start:', messageOf(error));
60
+ });
61
+ }
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
+ */
76
+ function watchTransport(ctx, runtime, ssh) {
77
+ if (!ssh || typeof ssh.on !== 'function')
78
+ return;
79
+ 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.
82
+ if (runtime.ssh !== ssh && runtime.jumpSsh !== ssh)
83
+ return;
84
+ if (runtime.closing || runtime.desired !== 'connected')
85
+ return;
86
+ const event = { type: 'transport.closed', transport: ssh };
87
+ void dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
88
+ caller: 'callback',
89
+ }).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).
93
+ const wantsRetry = result.ok && result.effects.some((effect) => effect.type === 'arm' && effect.timer === 'reconnect');
94
+ if (wantsRetry)
95
+ scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime));
96
+ });
97
+ });
98
+ }
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
+ */
112
+ async function openTransport(ctx, runtime, target) {
113
+ const settings = ctx.settings();
114
+ const auth = () => ({
115
+ type: runtime.entry.auth?.type ?? 'key',
116
+ keyPath: runtime.entry.auth?.keyPath ?? null,
117
+ password: runtime.password ?? null,
118
+ });
119
+ const buildOptions = (resolved, role, sock) => {
120
+ 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
+ const resolvedPort = resolved.port ?? 22;
125
+ const jumpPinMatches = isJump &&
126
+ runtime.jumpFingerprint?.host === resolved.host &&
127
+ (Number(runtime.jumpFingerprint?.port) || 22) === resolvedPort;
128
+ const pinnedFingerprint = isJump
129
+ ? jumpPinMatches
130
+ ? (runtime.jumpFingerprint?.pinned ?? null)
131
+ : null
132
+ : (runtime.entry.pinnedFingerprint ?? null);
133
+ return {
134
+ host: resolved.host,
135
+ port: resolvedPort,
136
+ 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
+ home: ctx.userHome(),
140
+ auth: auth(),
141
+ identityFiles: resolved.identityFiles ?? [],
142
+ hostKeyPolicy,
143
+ pinnedFingerprint,
144
+ knownHostFingerprints: resolved.knownFingerprints ?? [],
145
+ acceptUnknownHostKey: false,
146
+ readyTimeoutMs: settings.connectTimeoutSec * 1000 || SSH_READY_TIMEOUT_MS,
147
+ ...(sock ? { sock } : {}),
148
+ onHostKey: (info) => requestHostKey(ctx, runtime, info, { role, host: resolved.host, port: resolvedPort }),
149
+ };
150
+ };
151
+ if (!target.jumpHost) {
152
+ runtime.ssh = ctx.deps.sshFactory(buildOptions(target, 'target'));
153
+ watchTransport(ctx, runtime, runtime.ssh);
154
+ ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host });
155
+ captureFingerprint(ctx, runtime, await runtime.ssh.connect());
156
+ return;
157
+ }
158
+ ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.jumpHost.host, jump: true });
159
+ const jumpTarget = {
160
+ ...target.jumpHost,
161
+ 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),
163
+ };
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
+ const rememberedJump = runtime.jumpFingerprint;
167
+ const rememberedJumpPort = (Number(rememberedJump?.port) || 22) === (jumpTarget.port ?? 22);
168
+ if (rememberedJump !== null && (!rememberedJumpPort || rememberedJump.host !== jumpTarget.host)) {
169
+ ctx.progress.log(runtime, 'info', `the jump host changed (${rememberedJump.host ?? 'unknown'} -> ${jumpTarget.host}); forgetting its previous host key`);
170
+ runtime.jumpFingerprint = null;
171
+ }
172
+ runtime.jumpSsh = ctx.deps.sshFactory(buildOptions(jumpTarget, 'jump'));
173
+ watchTransport(ctx, runtime, runtime.jumpSsh);
174
+ 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
+ runtime.fingerprint = null;
178
+ ctx.progress.phase(runtime, 'ssh', 'ssh-connecting', { host: target.host, via: target.jumpHost.host });
179
+ const stream = await runtime.jumpSsh.forwardOut(target.host, target.port ?? 22);
180
+ runtime.ssh = ctx.deps.sshFactory(buildOptions(target, 'target', stream));
181
+ watchTransport(ctx, runtime, runtime.ssh);
182
+ captureFingerprint(ctx, runtime, await runtime.ssh.connect());
183
+ }
184
+ async function connectPipeline(ctx, runtime) {
185
+ const log = (level, ...args) => ctx.progress.log(runtime, level, ...args);
186
+ 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.
189
+ runtime.alongsidePids = [];
190
+ // Kill rights belong to this connection: a fresh connect starts with no launched pids.
191
+ runtime.launched = new Map();
192
+ runtime.bound = null;
193
+ runtime.tunnelRepairFailures = 0;
194
+ runtime.nextTunnelRepairAt = 0;
195
+ let remoteStarted = false;
196
+ 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
+ let transportUp = false;
200
+ try {
201
+ const target = await resolveTargetForRuntime(ctx, runtime);
202
+ assertStillWanted(ctx, runtime);
203
+ 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.
207
+ if (runtime.entry.auth?.type === 'password' && !runtime.password && ctx.secrets) {
208
+ const remembered = await ctx.secrets.get(runtime.id);
209
+ if (remembered) {
210
+ runtime.password = remembered;
211
+ runtime.passwordSaved = true;
212
+ }
213
+ assertStillWanted(ctx, runtime);
214
+ }
215
+ 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.
218
+ if (runtime.ssh !== null || runtime.jumpSsh !== null) {
219
+ log('debug', 'releasing the transport kept by the idle policy before dialling again');
220
+ await disposeSsh(runtime);
221
+ assertStillWanted(ctx, runtime);
222
+ }
223
+ 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);
228
+ 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.
232
+ await settlePasswordStorage(ctx, runtime, log);
233
+ assertStillWanted(ctx, runtime);
234
+ phase('probe', 'probing');
235
+ let facts = await ctx.deps.probe(runtime.ssh);
236
+ assertStillWanted(ctx, runtime);
237
+ assertTransportOpen(runtime);
238
+ const freeGb = Math.round(Number(facts.diskFreeKb ?? 0) / 1_048_576);
239
+ 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
+ const profile = ctx.settings().bootstrap.profile;
245
+ 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).
248
+ const nodeLayout = layoutForRuntime({ facts });
249
+ log('info', `managed Node: expecting v${managedVersion} in ${nodeLayout.nodeDir}`);
250
+ const managed = await ctx.deps.ensureNode(runtime.ssh, {
251
+ facts,
252
+ layout: nodeLayout,
253
+ version: managedVersion,
254
+ onProgress: (event) => ctx.progress.nodeProgress(runtime, event),
255
+ });
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.
260
+ facts = applyManagedNodeFacts(facts, managed);
261
+ log('info', `managed Node ${managed.version}${managed.installed ? ' installed' : ' reused'} at ${managed.nodeBinDir}`);
262
+ runtime.facts = facts;
263
+ const targetVersion = ctx.localVersion();
264
+ if (!targetVersion) {
265
+ throw errors.invalidInput('version', {
266
+ zh: '无法确定本机 DSH 版本,无法用 npx 固定同版本启动远端。请从 DSH 界面启动本插件,让 Host 读到本机版本。',
267
+ en: 'The local DSH version is unknown, so the remote cannot be pinned to the same version. Start the plugin from the DSH UI so the Host can read the local version.',
268
+ });
269
+ }
270
+ const plan = ctx.deps.plan({ facts, targetVersion, profile });
271
+ log('info', `runtime plan ${plan.level}: ${plan.reason.en}`);
272
+ phase('start', 'starting-remote', { level: plan.level });
273
+ layout = layoutForRuntime(runtime);
274
+ 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
+ try {
279
+ const adopted = await ctx.deps.adopt(runtime.ssh, layout, { profile });
280
+ const adoptedVersion = adopted?.version ? normalizeVersion(adopted.version) : null;
281
+ if (adopted && (!adoptedVersion || versionsEqual(adoptedVersion, targetVersion))) {
282
+ webInfo = { ...adopted, logPath: layout.logFile, startedAt: nowIso(), rawLine: '' };
283
+ 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.
287
+ if (adopted.origin !== 'reattach')
288
+ await rememberLaunched(ctx, runtime, adopted.pid, layout, profile);
289
+ else
290
+ await rememberBound(ctx, runtime, adopted.pid, layout, profile, 'reattach');
291
+ }
292
+ 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.
296
+ try {
297
+ await ctx.deps.stopWeb(runtime.ssh, layout, { pid: adopted.pid });
298
+ }
299
+ catch (error) {
300
+ log('warn', 'could not stop the stale remote web:', messageOf(error));
301
+ }
302
+ }
303
+ else if (adopted) {
304
+ log('warn', `running remote web version ${adoptedVersion} != ${targetVersion}, but it was only re-attached; leaving it running`);
305
+ }
306
+ else {
307
+ log('debug', 'adopt: no running remote web to reuse');
308
+ }
309
+ }
310
+ catch (error) {
311
+ log('debug', 'adopt check failed:', messageOf(error));
312
+ }
313
+ assertStillWanted(ctx, runtime);
314
+ assertTransportOpen(runtime);
315
+ 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.
320
+ const leftover = await ctx.deps.readRegistry(runtime.ssh, layout);
321
+ assertStillWanted(ctx, runtime);
322
+ const leftoverPid = Number(leftover?.pid ?? 0);
323
+ if (leftover?.origin === 'reattach') {
324
+ log('info', `leaving a re-attached remote web instance alone (pid ${leftoverPid || 'unknown'})`);
325
+ }
326
+ else if (leftover?.dshHome === layout.dshHome && leftover?.profile === profile && isPid(leftoverPid)) {
327
+ try {
328
+ await ctx.deps.stopWeb(runtime.ssh, layout, { pid: leftoverPid });
329
+ log('info', `stopped a non-adoptable remote web instance pid=${leftoverPid}`);
330
+ }
331
+ catch (error) {
332
+ log('warn', 'could not stop the non-adoptable remote web:', messageOf(error));
333
+ }
334
+ }
335
+ await resolveForeignConflict(ctx, runtime, layout, profile);
336
+ assertStillWanted(ctx, runtime);
337
+ assertTransportOpen(runtime);
338
+ 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.
342
+ log('info', `npx preflight: resolving @deepseek-ai/dsh@${plan.start.targetVersion}`);
343
+ const onStdout = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion);
344
+ const onStderr = ctx.progress.bootstrapReporter(runtime, plan.start.targetVersion);
345
+ await ctx.deps.preflight(runtime.ssh, plan, { onStdout, onStderr });
346
+ assertStillWanted(ctx, runtime);
347
+ assertTransportOpen(runtime);
348
+ log('info', `npx preflight ready: @deepseek-ai/dsh@${plan.start.targetVersion}`);
349
+ phase('start', 'starting-remote', { level: plan.level });
350
+ webInfo = await ctx.deps.startWeb(runtime.ssh, {
351
+ plan,
352
+ layout,
353
+ profile,
354
+ timeoutMs: REMOTE_START_TIMEOUT_MS,
355
+ onLine: (line) => log('debug', `remote: ${line}`),
356
+ });
357
+ log('info', `remote DSH started: pid ${webInfo.pid ?? '?'}, port ${webInfo.port}`);
358
+ }
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
+ }
364
+ 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
+ if (webInfo.adopted !== true)
368
+ await rememberLaunched(ctx, runtime, webInfo.pid, layout, profile);
369
+ assertStillWanted(ctx, runtime);
370
+ runtime.token = webInfo.token;
371
+ runtime.remote = {
372
+ version: targetVersion,
373
+ uiReady: false,
374
+ localPort: null,
375
+ port: webInfo.port,
376
+ pid: webInfo.pid ?? null,
377
+ dshHome: layout.dshHome,
378
+ profile,
379
+ bootstrapLevel: plan.level,
380
+ nodeVersion: facts.nodeVersion,
381
+ nodeSource: 'managed',
382
+ startedAt: webInfo.startedAt ?? nowIso(),
383
+ viewRev: Number(runtime.remote.viewRev) || 0,
384
+ };
385
+ phase('tunnel', 'tunneling');
386
+ const tunnel = await openTunnelFor(ctx, runtime, webInfo.port);
387
+ assertStillWanted(ctx, runtime);
388
+ phase('verifying', 'verifying');
389
+ 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.
395
+ runtime.remote.uiReady = true;
396
+ 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);
401
+ runtime.entry = ctx.store.getHost(runtime.id) ?? runtime.entry;
402
+ if (ctx.settings().saveTokens) {
403
+ await ctx.store.saveToken(runtime.id, webInfo.token);
404
+ assertStillWanted(ctx, runtime);
405
+ }
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).
411
+ await markConnected(ctx, runtime);
412
+ const localPort = runtime.tunnel?.localPort ?? runtime.remote.localPort ?? '?';
413
+ log('info', `connected: remote ${runtime.remote.version} on 127.0.0.1:${localPort}`);
414
+ }
415
+ catch (error) {
416
+ // Phase is cleared with the status; capture it first so the log says where it stopped.
417
+ 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).
420
+ const droppedTransport = runtime.transportLost === true || (transportUp === true && runtime.ssh?.connected !== true);
421
+ 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.
425
+ 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
+ const event = cancelled
430
+ ? { type: 'connect.cancelled' }
431
+ : { type: 'connect.failed', view: normalizeConnectFailure(runtime, error), phase: failedPhase };
432
+ await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
433
+ caller: 'script',
434
+ 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
+ teardown: {
440
+ stopRemote: remoteStarted && runtime.entry.keepAlive === 'stop',
441
+ keepRemote: remoteStarted && runtime.entry.keepAlive !== 'stop',
442
+ },
443
+ });
444
+ if (cancelled)
445
+ 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.
449
+ if (!cancelled) {
450
+ const retryable = runtime.error?.retryable !== false && !saidNo;
451
+ const repairAttempt = (Number(runtime.reconnectAttempts) || 0) > 0;
452
+ if (retryable && (repairAttempt || droppedTransport))
453
+ scheduleConnectRetry(ctx, runtime);
454
+ }
455
+ ctx.emitState();
456
+ }
457
+ finally {
458
+ runtime.connectPromise = null;
459
+ }
460
+ }
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) {
468
+ if (ctx.state.disposed === true || runtime.desired !== 'connected')
469
+ return;
470
+ if (!runtime.entry.autoReconnect || !ctx.settings().autoReconnect.enabled)
471
+ return;
472
+ scheduleReconnect(ctx, runtime, () => retryNow(ctx, runtime));
473
+ }