dsh-remote-go 0.1.0 → 0.2.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.
package/src/remote-web.js CHANGED
@@ -4,9 +4,16 @@
4
4
  import { DEFAULT_REMOTE_PROFILE, REMOTE_START_TIMEOUT_MS } from './constants.js'
5
5
  import { errors } from './errors.js'
6
6
  import { remoteLayout } from './layout.js'
7
- import { headTail, isLoopbackHost, isPid, messageOf, shellQuote } from './util.js'
7
+ import { headTail, isLoopbackHost, isPid, messageOf, nowIso, shellQuote } from './util.js'
8
8
  import { normalizeVersion } from './version.js'
9
- import { isUiUp, remoteHttpStatus } from './remote-proc.js'
9
+ import {
10
+ findForeignDshProcesses,
11
+ isUiUp,
12
+ remoteHttpStatus,
13
+ remoteListenPorts,
14
+ remotePortOwnerPid,
15
+ remoteProcessIdentity,
16
+ } from './remote-proc.js'
10
17
 
11
18
  const WEB_LINE_RE = /dsh web:\s*(https?:\/\/[^\s]+)/
12
19
 
@@ -63,11 +70,15 @@ export function buildBrowserCarrierProbe(plan, layout, profile) {
63
70
  const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
64
71
  const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`)
65
72
  const patchFile = shellQuote(`${layout.root}/${BROWSER_CARRIER_PATCH_FILE}`)
73
+ // The dump contains the profile's effective configuration: it is created 0600 and removed
74
+ // again before this script returns, on both the success and the failure path (M3).
66
75
  return `set -u
76
+ umask 077
67
77
  mkdir -p ${shellQuote(layout.root)}
68
78
  DUMP=${dumpFile}
69
79
  if ! env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --profile ${shellQuote(profile)} --dump-config > "$DUMP" 2>/dev/null; then
70
80
  echo "DUMP-FAILED"
81
+ rm -f "$DUMP"
71
82
  exit 0
72
83
  fi
73
84
  if grep -A6 'id: api-remotes' "$DUMP" | grep -q 'disabled: true'; then
@@ -77,7 +88,8 @@ DSH_REMOTE_GO_PATCH
77
88
  echo "PATCH"
78
89
  else
79
90
  echo "CLEAR"
80
- fi`
91
+ fi
92
+ rm -f "$DUMP"`
81
93
  }
82
94
 
83
95
  export async function ensureBrowserCarrier(ssh, options) {
@@ -114,10 +126,16 @@ export function buildStartScript(startCommand, layout, options = {}) {
114
126
  const logFile = shellQuote(layout.logFile)
115
127
  const runFile = shellQuote(layout.runFile)
116
128
  const startedAtPlaceholder = '$(date -u +%Y-%m-%dT%H:%M:%SZ)'
129
+ // `umask 077` keeps the log (and the launch's state directory) private: the log carries the
130
+ // launch URL with its token, and the default umask used to leave it world-readable (M3).
131
+ // The run registry is written to a temp file and renamed, so a reader never sees a
132
+ // half-written record (M4).
117
133
  return `set -eu
134
+ umask 077
118
135
  mkdir -p ${shellQuote(layout.logsDir)} ${shellQuote(layout.runDir)} ${shellQuote(layout.stateHome)}
119
136
  LOG=${logFile}
120
137
  : > "$LOG"
138
+ chmod 600 "$LOG" 2>/dev/null || true
121
139
  cd "$HOME"
122
140
  setsid nohup bash -lc ${shellQuote(startCommand)} >> "$LOG" 2>&1 < /dev/null &
123
141
  PID=$!
@@ -144,13 +162,59 @@ fi
144
162
  echo "LINE:$LINE"
145
163
  PORT=$(printf '%s' "$LINE" | sed -n 's#.*127\\.0\\.0\\.1:\\([0-9][0-9]*\\)/.*#\\1#p')
146
164
  if [ -z "$PORT" ]; then PORT=$(printf '%s' "$LINE" | sed -n 's#.*:\\([0-9][0-9]*\\)/.*#\\1#p'); fi
147
- printf '{"pid":%s,"port":%s,"startedAt":"%s","profile":%s,"version":%s,"dshHome":%s,"launch":"${LAUNCH_MARKER}"}\\n' "$PID" "\${PORT:-0}" "${startedAtPlaceholder}" ${shellQuote(JSON.stringify(profile))} ${shellQuote(JSON.stringify(version))} ${shellQuote(JSON.stringify(layout.dshHome))} > ${runFile}
165
+ RUN=${runFile}
166
+ TMP="$RUN.tmp.$$"
167
+ printf '{"pid":%s,"port":%s,"startedAt":"%s","profile":%s,"version":%s,"dshHome":%s,"launch":"${LAUNCH_MARKER}"}\\n' "$PID" "\${PORT:-0}" "${startedAtPlaceholder}" ${shellQuote(JSON.stringify(profile))} ${shellQuote(JSON.stringify(version))} ${shellQuote(JSON.stringify(layout.dshHome))} > "$TMP"
168
+ mv -f "$TMP" "$RUN"
148
169
  echo "DONE:$PID:$PORT"
149
170
  `
150
171
  }
151
172
 
173
+ /** The pid the launch script announced, from `DONE:` or the earlier `PID:` line. */
174
+ export function parseLaunchedPid(text) {
175
+ const combined = String(text ?? '')
176
+ const done = /DONE:(\d+):(\d+)/.exec(combined)
177
+ if (done) return { pid: Number(done[1]), port: Number(done[2]) }
178
+ const started = /(?:^|\n)PID:(\d+)\s*(?:\n|$)/.exec(combined)
179
+ if (started) return { pid: Number(started[1]), port: 0 }
180
+ return { pid: 0, port: 0 }
181
+ }
182
+
183
+ /**
184
+ * Stop a launch that failed *after* it started: the detached process must not be left
185
+ * running on the remote just because its readiness line never parsed (M2).
186
+ *
187
+ * Only the pid this launch script printed is ours to stop. `run/web.json` may name another
188
+ * instance (a re-attached process, or a previous launch), so it is deliberately not used as
189
+ * a fallback here: killing that pid would be exactly the "a re-attached instance is not
190
+ * stopped" rule the connect pipeline enforces (review blocker 2).
191
+ * @param {object} ssh - SSH transport.
192
+ * @param {object} layout - remote layout.
193
+ * @param {number} startedPid - the pid the launch script printed.
194
+ * @param {(line: string) => void} [onLine] - progress sink.
195
+ * @returns {Promise<{ ok: boolean, pid: number | null, output?: string }>}
196
+ */
197
+ async function stopFailedLaunch(ssh, layout, startedPid, onLine) {
198
+ if (!isPid(startedPid)) return { ok: false, pid: null }
199
+ let alive = false
200
+ try {
201
+ alive = await remotePidAlive(ssh, startedPid)
202
+ } catch {
203
+ // swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
204
+ return { ok: false, pid: null }
205
+ }
206
+ if (!alive) return { ok: false, pid: null }
207
+ const stopped = await stopRemoteWeb(ssh, layout, { pid: startedPid })
208
+ onLine?.(
209
+ `start failed after pid ${startedPid} was launched; ${
210
+ stopped.ok === true ? 'it was stopped' : 'it could not be stopped'
211
+ }`,
212
+ )
213
+ return { ok: stopped.ok === true, pid: startedPid, output: stopped.output }
214
+ }
215
+
152
216
  export async function startRemoteWeb(ssh, options) {
153
- const layout = options.layout ?? remoteLayout(options.home ?? null)
217
+ const layout = options.layout ?? remoteLayout(options.home)
154
218
  const profile = options.profile ?? options.plan.profile ?? DEFAULT_REMOTE_PROFILE
155
219
  const carrier = await ensureBrowserCarrier(ssh, { plan: options.plan, layout, profile, onLine: options.onLine })
156
220
  const startCommand = buildStartCommand(options.plan, layout, { profile, patchPath: carrier.patchPath })
@@ -173,19 +237,27 @@ export async function startRemoteWeb(ssh, options) {
173
237
  },
174
238
  })
175
239
  const combined = `${result.stdout}\n${result.stderr}`
240
+ // The launch script prints its pid before it waits for the readiness line: keep it even
241
+ // when the wait itself fails, so a failure can stop what it started (M2).
242
+ const launched = parseLaunchedPid(combined)
243
+ const failed = async (error) => {
244
+ await stopFailedLaunch(ssh, layout, launched.pid, options.onLine)
245
+ return error
246
+ }
176
247
  if (result.code !== 0) {
177
- throw errors.remoteDshStartFailed(headTail(combined, 1500))
248
+ throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)))
178
249
  }
179
250
  const parsed = parseWebLine(combined)
180
- if (!parsed) throw errors.remoteDshStartFailed(headTail(combined, 1500))
251
+ if (!parsed) throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)))
181
252
  if (!isLoopbackHost(parsed.host)) {
182
- throw errors.remoteUiUnreachable({
183
- zh: `远端 DSH 宣布的地址不是回环地址(${parsed.host}),无法安全地经 SSH 隧道访问。`,
184
- en: `The remote DSH advertised a non-loopback host (${parsed.host}); it cannot be reached safely through the SSH tunnel.`,
185
- })
253
+ throw await failed(
254
+ errors.remoteUiUnreachable({
255
+ zh: `远端 DSH 宣布的地址不是回环地址(${parsed.host}),无法安全地经 SSH 隧道访问。`,
256
+ en: `The remote DSH advertised a non-loopback host (${parsed.host}); it cannot be reached safely through the SSH tunnel.`,
257
+ }),
258
+ )
186
259
  }
187
- const pidMatch = /DONE:(\d+):(\d+)/.exec(combined)
188
- const pid = pidMatch ? Number(pidMatch[1]) : 0
260
+ const pid = launched.pid
189
261
  const startedAt = new Date().toISOString()
190
262
  return {
191
263
  pid,
@@ -201,31 +273,123 @@ export async function startRemoteWeb(ssh, options) {
201
273
  }
202
274
  }
203
275
 
276
+ /**
277
+ * The pid a readiness line in the log belongs to, as a last resort for a stop whose pid is
278
+ * unknown. The log only names the port; `/proc` proves which process listens on it (M4).
279
+ */
280
+ async function pidFromReadinessLine(ssh, layout) {
281
+ const line = await readWebLineFromLog(ssh, layout)
282
+ if (!line || !isPid(line.port)) return 0
283
+ const owner = await remotePortOwnerPid(ssh, line.port)
284
+ return isPid(Number(owner)) ? Number(owner) : 0
285
+ }
286
+
204
287
  export async function stopRemoteWeb(ssh, layout, options = {}) {
205
- const pid = Number(options.pid ?? 0)
288
+ let pid = Number(options.pid ?? 0)
289
+ if (!isPid(pid)) {
290
+ // The run registry is the primary record; a partially written one still names a pid, and
291
+ // the readiness line's port owner is the last resort (M4).
292
+ const registry = await readRunRegistry(ssh, layout)
293
+ pid = Number(registry?.pid ?? 0)
294
+ }
295
+ if (!isPid(pid)) pid = await pidFromReadinessLine(ssh, layout)
296
+ // The registry is removed only after the stop is confirmed: a failed stop must leave the
297
+ // record in place, otherwise the next connect adopts nothing and a second instance starts
298
+ // next to the surviving one (M4). It is also removed only when it names *this* pid: a
299
+ // record that belongs to another instance (a re-attach) is not ours to delete.
206
300
  const script = `set -u
301
+ umask 077
302
+ RUN=${shellQuote(layout.runFile)}
207
303
  PID=${isPid(pid) ? pid : 0}
208
- if [ "$PID" -eq 0 ] && [ -f ${shellQuote(layout.runFile)} ]; then
209
- PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' ${shellQuote(layout.runFile)} | head -n 1)
304
+ if [ "$PID" -eq 0 ] && [ -f "$RUN" ]; then
305
+ PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$RUN" | head -n 1)
306
+ fi
307
+ PID="\${PID:-0}"
308
+ if [ "$PID" -eq 0 ]; then
309
+ echo "NO-TARGET"
310
+ exit 5
311
+ fi
312
+ drop_own_record() {
313
+ if [ ! -f "$RUN" ]; then return 0; fi
314
+ REC_PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$RUN" 2>/dev/null | head -n 1)
315
+ if [ "\${REC_PID:-}" = "$PID" ]; then rm -f "$RUN"; fi
316
+ }
317
+ if ! kill -0 "$PID" 2>/dev/null; then
318
+ echo "GONE:$PID"
319
+ drop_own_record
320
+ exit 0
210
321
  fi
211
- if [ -n "\${PID:-}" ] && [ "$PID" -ne 0 ]; then
212
- kill -TERM "-$PID" 2>/dev/null || kill -TERM "$PID" 2>/dev/null || true
322
+ kill -TERM "-$PID" 2>/dev/null || kill -TERM "$PID" 2>/dev/null || true
323
+ n=0
324
+ while [ "$n" -lt 20 ]; do
325
+ kill -0 "$PID" 2>/dev/null || break
326
+ n=$((n+1))
327
+ sleep 0.5
328
+ done
329
+ if kill -0 "$PID" 2>/dev/null; then
330
+ kill -KILL "-$PID" 2>/dev/null || kill -KILL "$PID" 2>/dev/null || true
213
331
  n=0
214
- while [ "$n" -lt 20 ]; do
332
+ while [ "$n" -lt 10 ]; do
215
333
  kill -0 "$PID" 2>/dev/null || break
216
334
  n=$((n+1))
217
335
  sleep 0.5
218
336
  done
219
- kill -KILL "-$PID" 2>/dev/null || kill -KILL "$PID" 2>/dev/null || true
220
337
  fi
221
- rm -f ${shellQuote(layout.runFile)}
222
- echo "STOPPED"
338
+ if kill -0 "$PID" 2>/dev/null; then
339
+ echo "ALIVE:$PID"
340
+ exit 6
341
+ fi
342
+ drop_own_record
343
+ echo "STOPPED:$PID"
223
344
  `
224
345
  try {
225
- const result = await ssh.exec(script, { timeoutMs: 30_000 })
226
- return { ok: result.code === 0, output: result.stdout.trim() }
346
+ const result = await ssh.exec(script, { timeoutMs: 40_000 })
347
+ const output = result.stdout.trim()
348
+ // An explicit pid that is already gone means the same thing as no target at all: there
349
+ // is nothing left to signal (the caller can clear the stale registry).
350
+ if (output.includes('NO-TARGET')) return { ok: false, reason: 'no-target', output }
351
+ if (output.includes('ALIVE:')) return { ok: false, reason: 'alive', output }
352
+ if (result.code !== 0) return { ok: false, reason: 'not-confirmed', output }
353
+ return { ok: true, output }
227
354
  } catch (error) {
228
- return { ok: false, output: messageOf(error) }
355
+ // swallow-ok: a throw here is a transport failure, reported as an unconfirmed stop so the
356
+ // caller keeps the run registry instead of adopting nothing on the next connect
357
+ return { ok: false, reason: 'error', output: messageOf(error) }
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Read `run/web.json`. The record is written atomically (temp + rename), but a record from an
363
+ * older launch path or a truncated file still names the process: parse what is there instead
364
+ * of reporting "no record" and losing the only pid (M4).
365
+ * @param {string} text - the raw file content.
366
+ * @returns {object | null} the parsed record, or null when it names no pid.
367
+ */
368
+ export function parseRunRegistry(text) {
369
+ const raw = String(text ?? '').trim()
370
+ if (raw === '') return null
371
+ try {
372
+ const parsed = JSON.parse(raw)
373
+ return parsed && typeof parsed === 'object' ? parsed : null
374
+ } catch {
375
+ // swallow-ok: fall through to the field-by-field recovery below
376
+ }
377
+ const field = (name) => new RegExp(`"${name}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(raw)?.[1] ?? null
378
+ // A number must be terminated by the next field or the record end: `{"pid":42` is a
379
+ // truncated record, not a pid of 42 (review: no prefix matches).
380
+ const number = (name) => Number(new RegExp(`"${name}"\\s*:\\s*(\\d+)\\s*[,}]`).exec(raw)?.[1] ?? 0)
381
+ const pid = number('pid')
382
+ if (!isPid(pid)) return null
383
+ const port = number('port')
384
+ return {
385
+ pid,
386
+ port: isPid(port) ? port : 0,
387
+ startedAt: field('startedAt'),
388
+ profile: field('profile'),
389
+ version: field('version'),
390
+ dshHome: field('dshHome'),
391
+ launch: field('launch'),
392
+ origin: field('origin'),
229
393
  }
230
394
  }
231
395
 
@@ -233,8 +397,7 @@ export async function readRunRegistry(ssh, layout) {
233
397
  try {
234
398
  const result = await ssh.exec(`cat ${shellQuote(layout.runFile)} 2>/dev/null || true`, { timeoutMs: 10_000 })
235
399
  if (result.code !== 0 || result.stdout.trim() === '') return null
236
- const parsed = JSON.parse(result.stdout.trim())
237
- return parsed && typeof parsed === 'object' ? parsed : null
400
+ return parseRunRegistry(result.stdout)
238
401
  } catch {
239
402
  return null
240
403
  }
@@ -282,7 +445,11 @@ export async function adoptRemoteWeb(ssh, layout, options = {}) {
282
445
  const pid = Number(registry?.pid ?? 0)
283
446
  if (!(await remotePidAlive(ssh, pid))) return null
284
447
  const line = await readWebLineFromLog(ssh, layout)
285
- if (!line) return null
448
+ if (!line || line.token === '') return null
449
+ // An adopted instance is reached through the loopback tunnel only: a process that
450
+ // advertises another host cannot be served safely and must not be adopted (adopt parity
451
+ // with a fresh launch, which refuses a non-loopback URL).
452
+ if (!isLoopbackHost(line.host)) return null
286
453
  const status = await remoteHttpStatus(ssh, line.port)
287
454
  if (!isUiUp(status)) return null
288
455
  const version =
@@ -296,5 +463,289 @@ export async function adoptRemoteWeb(ssh, layout, options = {}) {
296
463
  profile,
297
464
  dshHome: layout.dshHome,
298
465
  adopted: true,
466
+ // Only a record written by the launch script (or a local restart) proves the process was
467
+ // started by this plugin; a re-attached record names a process the remote restarted itself
468
+ // and must not grant kill rights to the next connection.
469
+ origin: registry.origin === 'reattach' ? 'reattach' : 'launch',
470
+ }
471
+ }
472
+
473
+ /**
474
+ * The pid/port record the plugin writes to `run/web.json` (the same shape the
475
+ * launch script writes). Kept pure so a re-attach can be tested without SSH.
476
+ * @param {object} input - pid, port, profile, dshHome, version, startedAt.
477
+ * @returns {object} the registry record.
478
+ */
479
+ export function buildRunRegistryRecord(input = {}) {
480
+ const pid = Number(input.pid ?? 0)
481
+ const port = Number(input.port ?? 0)
482
+ if (!isPid(pid)) throw errors.invalidInput('pid', { zh: 'pid 不合法。', en: 'The pid is invalid.' })
483
+ if (!isPid(port) || port > 65535)
484
+ throw errors.invalidInput('port', { zh: '端口不合法。', en: 'The port is invalid.' })
485
+ const dshHome = String(input.dshHome ?? '').trim()
486
+ if (dshHome === '') {
487
+ throw errors.invalidInput('dshHome', { zh: '远端 DSH_HOME 未知。', en: 'The remote DSH_HOME is unknown.' })
488
+ }
489
+ return {
490
+ pid,
491
+ port,
492
+ startedAt: typeof input.startedAt === 'string' && input.startedAt !== '' ? input.startedAt : nowIso(),
493
+ profile: typeof input.profile === 'string' && input.profile !== '' ? input.profile : DEFAULT_REMOTE_PROFILE,
494
+ version: normalizeVersion(input.version ?? ''),
495
+ dshHome,
496
+ launch: LAUNCH_MARKER,
497
+ // `launch`: this plugin started the process; `reattach`: the plugin only took it over.
498
+ // The next connection reads this so a re-attached process never gains kill rights.
499
+ origin: input.origin === 'reattach' ? 'reattach' : 'launch',
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Drop `run/web.json` without signalling anything: used when the bound process is already
505
+ * gone (a stop) or the record is known stale. Never kills a pid.
506
+ * @param {object} ssh - SSH transport.
507
+ * @param {object} layout - remote layout.
508
+ * @returns {Promise<{ ok: boolean, output: string }>} whether the removal was acknowledged.
509
+ */
510
+ export async function clearRunRegistry(ssh, layout) {
511
+ try {
512
+ const result = await ssh.exec(`rm -f ${shellQuote(layout.runFile)}`, { timeoutMs: 10_000 })
513
+ return { ok: result.code === 0, output: String(result.stdout ?? '').trim() }
514
+ } catch (error) {
515
+ // swallow-ok: a failed removal is returned as ok:false and the caller logs it; the next
516
+ // connect still re-checks the registry, and a dead pid is never adopted
517
+ return { ok: false, output: messageOf(error) }
518
+ }
519
+ }
520
+
521
+ /**
522
+ * Rewrite `run/web.json` after a re-attach: the remote restarted on a new port
523
+ * (and possibly a new pid) without going through the launch script, so the stale
524
+ * record would mislead the next connect's adopt step.
525
+ * @param {object} ssh - SSH transport.
526
+ * @param {object} layout - remote layout.
527
+ * @param {object} record - validated record from {@link buildRunRegistryRecord}.
528
+ * @returns {Promise<{ ok: boolean, output: string }>} whether the write was acknowledged.
529
+ */
530
+ export async function writeRunRegistry(ssh, layout, record) {
531
+ const payload = JSON.stringify(record)
532
+ // Temp file + rename: a concurrent reader (`cat run/web.json`) sees the old record or the
533
+ // new one, never a truncated line that makes the adopt step misread the pid (M4).
534
+ const script = `set -eu
535
+ umask 077
536
+ mkdir -p ${shellQuote(layout.runDir)}
537
+ RUN=${shellQuote(layout.runFile)}
538
+ TMP="$RUN.tmp.$$"
539
+ printf '%s\\n' ${shellQuote(payload)} > "$TMP"
540
+ mv -f "$TMP" "$RUN"
541
+ echo "REGISTRY-WRITTEN"
542
+ `
543
+ try {
544
+ const result = await ssh.exec(script, { timeoutMs: 15_000, maxBytes: 8_000 })
545
+ return { ok: result.code === 0 && result.stdout.includes('REGISTRY-WRITTEN'), output: result.stdout.trim() }
546
+ } catch (error) {
547
+ // A registry write failure is reported to the caller, which logs it and carries on:
548
+ // the live tunnel is what matters, the next connect re-adopts from the log line.
549
+ return { ok: false, output: messageOf(error) }
550
+ }
551
+ }
552
+
553
+ /** Whether a `ps` command line is the DSH process for this profile. */
554
+ export function commandMatchesProfile(command, profile) {
555
+ const wanted = String(profile ?? '')
556
+ if (wanted === '') return false
557
+ const escaped = wanted.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
558
+ return new RegExp(`--profile[=\\s]+${escaped}(?:\\s|$)`).test(String(command ?? ''))
559
+ }
560
+
561
+ /** The pinned `@deepseek-ai/dsh@<version>` an npx command line names, if any. */
562
+ export function versionFromCommand(command) {
563
+ const match = /@deepseek-ai\/dsh@([^\s'"]+)/.exec(String(command ?? ''))
564
+ return match ? normalizeVersion(match[1]) : null
565
+ }
566
+
567
+ /**
568
+ * The installed package directory a real node argv names, e.g.
569
+ * `/home/u/.npm/_npx/<hash>/node_modules/@deepseek-ai/dsh` or an app install path.
570
+ * The version is read from that directory's `package.json` (the argv itself does not
571
+ * carry one in the npx-cache and app-install shapes).
572
+ */
573
+ export function dshPackageDirFromCommand(command) {
574
+ const text = String(command ?? '')
575
+ const marker = '/node_modules/@deepseek-ai/dsh'
576
+ // Linear scan on purpose: a nested-quantifier regex over an argv with many `/` segments can be
577
+ // made to backtrack exponentially, and the command line is remote input.
578
+ let at = text.indexOf(marker)
579
+ while (at !== -1) {
580
+ const rest = text.slice(at + marker.length)
581
+ if (/^(?:\/lib\/bin\.js|[\s'"]|$)/.test(rest)) {
582
+ let start = at
583
+ while (start > 0 && !/[\s'"]/.test(text[start - 1])) start -= 1
584
+ const dir = text.slice(start, at + marker.length)
585
+ if (dir.startsWith('/') && !dir.split('/').includes('..')) return dir
586
+ return null
587
+ }
588
+ at = text.indexOf(marker, at + marker.length)
589
+ }
590
+ return null
591
+ }
592
+
593
+ /** Read the version of the DSH package a process actually loaded, over SFTP (no shell). */
594
+ async function packageVersionFromDir(ssh, dir) {
595
+ if (!dir || typeof ssh.readRemoteFile !== 'function') return null
596
+ try {
597
+ const file = await ssh.readRemoteFile(`${dir}/package.json`, { maxBytes: 64 * 1024 })
598
+ const text = Buffer.isBuffer(file?.data) ? file.data.toString('utf8') : String(file?.data ?? '')
599
+ const parsed = JSON.parse(text)
600
+ const version = typeof parsed?.version === 'string' ? normalizeVersion(parsed.version) : ''
601
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ? version : null
602
+ } catch {
603
+ // swallow-ok: an unreadable package.json only means the version stays unknown (never assumed)
604
+ return null
605
+ }
606
+ }
607
+
608
+ /**
609
+ * The real version a remote DSH process runs: the pinned npx spec when there is one,
610
+ * otherwise the `package.json` of the package its argv loaded. Null when it cannot be
611
+ * proven - the caller must not fill in the local version.
612
+ */
613
+ export async function remoteDshVersion(ssh, command) {
614
+ const pinned = versionFromCommand(command)
615
+ if (pinned) return pinned
616
+ const dir = dshPackageDirFromCommand(command)
617
+ return dir === null ? null : packageVersionFromDir(ssh, dir)
618
+ }
619
+
620
+ /**
621
+ * Re-read the remote's real web state after it restarted: the same pid on a new
622
+ * random port (in-place exec) or a new pid from a supervisor. The run registry is only
623
+ * a hint; a candidate is accepted only when all of these hold:
624
+ *
625
+ * - the listening port belongs to the pid the plugin thinks it owns;
626
+ * - that pid's `/proc` identity proves the same `DSH_HOME` and the same `--profile`;
627
+ * - the newest `dsh web:` line names that exact port, so a launch token is available.
628
+ *
629
+ * A candidate that answers HTTP but has no token is **not** usable: a real DSH answers
630
+ * `/?token=` with 401, so claiming success would be dishonest. The process-scan fallback
631
+ * therefore never yields a takeover; it only turns the failure reason into `no-token`
632
+ * ("still running, but no way to authenticate") so the user gets the right remedy.
633
+ *
634
+ * @param {object} ssh - SSH transport.
635
+ * @param {object} layout - remote layout (`~/.dsh/remote-go`).
636
+ * @param {{ profile?: string, timeoutMs?: number }} [options]
637
+ * @returns {Promise<{ ok: true, pid: number, port: number, token: string, url: string,
638
+ * version: string | null, profile: string, dshHome: string, source: string } |
639
+ * { ok: false, reason: string }>}
640
+ */
641
+ export async function resolveRemoteWeb(ssh, layout, options = {}) {
642
+ const profile = options.profile ?? DEFAULT_REMOTE_PROFILE
643
+ const registry = await readRunRegistry(ssh, layout)
644
+ const line = await readWebLineFromLog(ssh, layout)
645
+ const registryMatches =
646
+ registry !== null &&
647
+ registry.dshHome === layout.dshHome &&
648
+ registry.profile === profile &&
649
+ registry.launch === LAUNCH_MARKER
650
+ const registryPid = Number(registry?.pid ?? 0)
651
+ const registryVersion =
652
+ typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null
653
+ const alive = registryMatches && isPid(registryPid) && (await remotePidAlive(ssh, registryPid))
654
+ let listeners = null
655
+ const listenersOf = async (pid) => {
656
+ if (listeners === null) listeners = await remoteListenPorts(ssh, pid)
657
+ return listeners
658
+ }
659
+ let tokenlessPort = 0
660
+ let firstFailure = null
661
+
662
+ /**
663
+ * Accept one reachable candidate only when its identity and its token both check out.
664
+ * Returns null for "reachable but no token" and a typed failure for "wrong process".
665
+ */
666
+ const take = async (pid, port, source) => {
667
+ const identity = await remoteProcessIdentity(ssh, pid)
668
+ if (identity.ok !== true) return { ok: false, reason: `identity-${identity.reason}` }
669
+ if (!commandMatchesProfile(identity.command, profile)) return { ok: false, reason: 'profile-mismatch' }
670
+ if (identity.dshHome === '' || identity.dshHome !== layout.dshHome) {
671
+ return { ok: false, reason: 'dsh-home-mismatch' }
672
+ }
673
+ const token = line !== null && line.port === port ? line.token : ''
674
+ if (token === '') {
675
+ tokenlessPort = port
676
+ return null
677
+ }
678
+ const proven = await remoteDshVersion(ssh, identity.command)
679
+ return {
680
+ ok: true,
681
+ pid,
682
+ port,
683
+ token,
684
+ url: line.url,
685
+ // Never backfill the local version: an unproven version stays null.
686
+ version: proven ?? (pid === registryPid ? registryVersion : null),
687
+ profile,
688
+ dshHome: identity.dshHome,
689
+ source,
690
+ }
691
+ }
692
+ const rememberFailure = (candidate) => {
693
+ if (candidate !== null && candidate.ok !== true && firstFailure === null) firstFailure = candidate
694
+ }
695
+
696
+ // 1. The instance this plugin started: the registry still names a live pid. Only ports
697
+ // that pid actually listens on are candidates, and the readiness line must name the
698
+ // same port for its launch token to be used.
699
+ if (alive) {
700
+ const candidates = [...(await listenersOf(registryPid))]
701
+ if (isPid(Number(registry?.port ?? 0))) candidates.push(Number(registry.port))
702
+ for (const port of [...new Set(candidates.filter((value) => isPid(value) && value <= 65535))]) {
703
+ if (!isUiUp(await remoteHttpStatus(ssh, port))) continue
704
+ // The port must belong to the pid whose identity we are about to trust. Without a
705
+ // readable owner (restricted /proc) the candidate is refused: fail closed.
706
+ const owner = await remotePortOwnerPid(ssh, port)
707
+ if (!isPid(owner) || owner !== registryPid) continue
708
+ const candidate = await take(registryPid, port, 'registry')
709
+ if (candidate?.ok === true) return candidate
710
+ rememberFailure(candidate)
711
+ }
712
+ }
713
+
714
+ // 2. A readiness line for a port owned by some other pid (the market restart re-execs
715
+ // in place, or a supervisor re-launched it). The owner pid must prove itself.
716
+ if (line !== null && isPid(line.port) && isUiUp(await remoteHttpStatus(ssh, line.port))) {
717
+ let pid = 0
718
+ if (alive && (await listenersOf(registryPid)).includes(line.port)) pid = registryPid
719
+ // The owner lookup is authoritative even when the registry pid is alive: the newest line
720
+ // may belong to another profile's process that shares this plugin's log file.
721
+ if (!isPid(pid)) pid = await remotePortOwnerPid(ssh, line.port)
722
+ if (isPid(pid)) {
723
+ const candidate = await take(pid, line.port, 'log')
724
+ if (candidate?.ok === true) return candidate
725
+ rememberFailure(candidate)
726
+ } else {
727
+ firstFailure = { ok: false, reason: 'pid-unknown' }
728
+ }
729
+ }
730
+
731
+ // 3. No usable readiness line (a supervisor may redirect stdout). Find the same-profile
732
+ // DSH process only to explain the failure: without its launch token it cannot be
733
+ // re-attached, so this path never returns ok.
734
+ const scanned = await findForeignDshProcesses(ssh, { ignorePids: alive ? [registryPid] : [] })
735
+ if (scanned.ok === true) {
736
+ for (const process of scanned.processes) {
737
+ if (!commandMatchesProfile(process.command, profile)) continue
738
+ const ports = await remoteListenPorts(ssh, process.pid)
739
+ for (const port of ports) {
740
+ if (!isUiUp(await remoteHttpStatus(ssh, port))) continue
741
+ const identity = await remoteProcessIdentity(ssh, process.pid)
742
+ if (identity.ok === true && identity.dshHome === layout.dshHome) {
743
+ return { ok: false, reason: 'no-token' }
744
+ }
745
+ }
746
+ }
299
747
  }
748
+ if (firstFailure !== null) return firstFailure
749
+ if (tokenlessPort !== 0) return { ok: false, reason: 'no-token' }
750
+ return { ok: false, reason: alive ? 'no-listener' : 'no-running-web' }
300
751
  }