dsh-remote-go 0.2.0 → 0.3.1

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 (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -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/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/remote-web.js DELETED
@@ -1,751 +0,0 @@
1
- /**
2
- * Remote DSH web lifecycle — start (detached, logged), parse the `dsh web:` URL, stop, adopt; the launch token stays in memory.
3
- */
4
- import { DEFAULT_REMOTE_PROFILE, REMOTE_START_TIMEOUT_MS } from './constants.js'
5
- import { errors } from './errors.js'
6
- import { remoteLayout } from './layout.js'
7
- import { headTail, isLoopbackHost, isPid, messageOf, nowIso, shellQuote } from './util.js'
8
- import { normalizeVersion } from './version.js'
9
- import {
10
- findForeignDshProcesses,
11
- isUiUp,
12
- remoteHttpStatus,
13
- remoteListenPorts,
14
- remotePortOwnerPid,
15
- remoteProcessIdentity,
16
- } from './remote-proc.js'
17
-
18
- const WEB_LINE_RE = /dsh web:\s*(https?:\/\/[^\s]+)/
19
-
20
- /**
21
- * Version tag written into the run registry. Bumping it invalidates adoption of
22
- * instances started by an older launch path (they may lack the browser-carrier
23
- * overlay, which would leave the in-window page stuck at "failed to load plugins").
24
- */
25
- export const LAUNCH_MARKER = 'browser-carrier-v1'
26
-
27
- /** Overlay file the launch passes with `--patch` when the profile disables the carrier. */
28
- export const BROWSER_CARRIER_PATCH_FILE = 'browser-carrier.patch.yml'
29
-
30
- /**
31
- * The window shows the remote DSH *web* UI, so the `api-remotes` Remote-Event
32
- * carrier must stay mounted. A profile bundle aimed at a native companion can
33
- * disable that row (e.g. goldenpigeon's patch does), which leaves the browser
34
- * client with `typert gateway: $events: forwarded Remote event source is
35
- * unavailable` and a blank "failed to load plugins" page. Re-enable the row with
36
- * a launch-only overlay instead of editing the user's profile.
37
- */
38
- const BROWSER_CARRIER_PATCH = `# Written by dsh-remote-go. The remote window is a browser client, so the
39
- # Remote-Event carrier (api-remotes) must stay enabled even when a profile
40
- # bundle disables it for a native-UI companion.
41
- - id: api-remotes
42
- disabled: false`
43
-
44
- export function parseWebLine(text) {
45
- const match = WEB_LINE_RE.exec(String(text ?? ''))
46
- if (!match) return null
47
- const rawUrl = match[1]
48
- let url
49
- try {
50
- url = new URL(rawUrl)
51
- } catch {
52
- return null
53
- }
54
- const host = url.hostname.replace(/^\[|\]$/g, '')
55
- const port = url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80
56
- const token = url.searchParams.get('token') ?? ''
57
- if (!isPid(port)) return null
58
- return { url: rawUrl, host, port, token, rawLine: match[0] }
59
- }
60
-
61
- export function buildStartCommand(plan, layout, options = {}) {
62
- const profile = options.profile ?? plan.profile ?? DEFAULT_REMOTE_PROFILE
63
- const patch = options.patchPath ? `--patch ${shellQuote(options.patchPath)} ` : ''
64
- const args = `${patch}--profile ${shellQuote(profile)} --no-open --port 0`
65
- const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
66
- return `env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} ${args}`
67
- }
68
-
69
- export function buildBrowserCarrierProbe(plan, layout, profile) {
70
- const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
71
- const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`)
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).
75
- return `set -u
76
- umask 077
77
- mkdir -p ${shellQuote(layout.root)}
78
- DUMP=${dumpFile}
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
80
- echo "DUMP-FAILED"
81
- rm -f "$DUMP"
82
- exit 0
83
- fi
84
- if grep -A6 'id: api-remotes' "$DUMP" | grep -q 'disabled: true'; then
85
- cat > ${patchFile} <<'DSH_REMOTE_GO_PATCH'
86
- ${BROWSER_CARRIER_PATCH}
87
- DSH_REMOTE_GO_PATCH
88
- echo "PATCH"
89
- else
90
- echo "CLEAR"
91
- fi
92
- rm -f "$DUMP"`
93
- }
94
-
95
- export async function ensureBrowserCarrier(ssh, options) {
96
- try {
97
- const result = await ssh.exec(buildBrowserCarrierProbe(options.plan, options.layout, options.profile), {
98
- timeoutMs: 60_000,
99
- maxBytes: 64_000,
100
- })
101
- if (result.code === 0 && result.stdout.includes('PATCH')) {
102
- options.onLine?.('browser carrier: the profile disables api-remotes; re-enabling it for this launch')
103
- return {
104
- status: 'patched',
105
- patchPath: `${options.layout.root}/${BROWSER_CARRIER_PATCH_FILE}`,
106
- }
107
- }
108
- if (result.code === 0 && result.stdout.includes('CLEAR')) {
109
- options.onLine?.('browser carrier: api-remotes is enabled by the profile')
110
- return { status: 'clear', patchPath: null }
111
- }
112
- options.onLine?.(`browser carrier: profile probe failed (${headTail(result.stdout + result.stderr, 300)})`)
113
- return { status: 'unknown', patchPath: null }
114
- } catch (error) {
115
- // swallow-ok: probe failure — launching without the overlay keeps the start
116
- // error (missing profile, npx failure) as the actionable one.
117
- options.onLine?.(`browser carrier: probe failed (${messageOf(error)})`)
118
- return { status: 'unknown', patchPath: null }
119
- }
120
- }
121
-
122
- export function buildStartScript(startCommand, layout, options = {}) {
123
- const waitSeconds = options.waitSeconds ?? Math.ceil(REMOTE_START_TIMEOUT_MS / 1000)
124
- const version = normalizeVersion(options.version ?? '')
125
- const profile = options.profile ?? DEFAULT_REMOTE_PROFILE
126
- const logFile = shellQuote(layout.logFile)
127
- const runFile = shellQuote(layout.runFile)
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).
133
- return `set -eu
134
- umask 077
135
- mkdir -p ${shellQuote(layout.logsDir)} ${shellQuote(layout.runDir)} ${shellQuote(layout.stateHome)}
136
- LOG=${logFile}
137
- : > "$LOG"
138
- chmod 600 "$LOG" 2>/dev/null || true
139
- cd "$HOME"
140
- setsid nohup bash -lc ${shellQuote(startCommand)} >> "$LOG" 2>&1 < /dev/null &
141
- PID=$!
142
- echo "PID:$PID"
143
- i=0
144
- while [ "$i" -lt ${waitSeconds} ]; do
145
- if grep -q 'dsh web:' "$LOG" 2>/dev/null; then break; fi
146
- if ! kill -0 "$PID" 2>/dev/null; then
147
- echo "EXITED:$PID"
148
- echo "---LOG---"
149
- tail -n 60 "$LOG" 2>/dev/null || true
150
- exit 3
151
- fi
152
- i=$((i+1))
153
- sleep 1
154
- done
155
- LINE=$(grep -m1 'dsh web:' "$LOG" 2>/dev/null || true)
156
- if [ -z "$LINE" ]; then
157
- echo "TIMEOUT"
158
- echo "---LOG---"
159
- tail -n 60 "$LOG" 2>/dev/null || true
160
- exit 4
161
- fi
162
- echo "LINE:$LINE"
163
- PORT=$(printf '%s' "$LINE" | sed -n 's#.*127\\.0\\.0\\.1:\\([0-9][0-9]*\\)/.*#\\1#p')
164
- if [ -z "$PORT" ]; then PORT=$(printf '%s' "$LINE" | sed -n 's#.*:\\([0-9][0-9]*\\)/.*#\\1#p'); fi
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"
169
- echo "DONE:$PID:$PORT"
170
- `
171
- }
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
-
216
- export async function startRemoteWeb(ssh, options) {
217
- const layout = options.layout ?? remoteLayout(options.home)
218
- const profile = options.profile ?? options.plan.profile ?? DEFAULT_REMOTE_PROFILE
219
- const carrier = await ensureBrowserCarrier(ssh, { plan: options.plan, layout, profile, onLine: options.onLine })
220
- const startCommand = buildStartCommand(options.plan, layout, { profile, patchPath: carrier.patchPath })
221
- const script = buildStartScript(startCommand, layout, {
222
- waitSeconds: Math.ceil((options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) / 1000),
223
- version: options.plan.start.targetVersion,
224
- profile,
225
- })
226
- const lines = []
227
- const result = await ssh.exec(script, {
228
- timeoutMs: (options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) + 30_000,
229
- maxBytes: 200_000,
230
- onStdout: (chunk) => {
231
- for (const line of chunk.split(/\r?\n/)) {
232
- if (line !== '') {
233
- lines.push(line)
234
- options.onLine?.(line)
235
- }
236
- }
237
- },
238
- })
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
- }
247
- if (result.code !== 0) {
248
- throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)))
249
- }
250
- const parsed = parseWebLine(combined)
251
- if (!parsed) throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)))
252
- if (!isLoopbackHost(parsed.host)) {
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
- )
259
- }
260
- const pid = launched.pid
261
- const startedAt = new Date().toISOString()
262
- return {
263
- pid,
264
- port: parsed.port,
265
- token: parsed.token,
266
- url: parsed.url,
267
- logPath: layout.logFile,
268
- startedAt,
269
- rawLine: parsed.rawLine,
270
- profile,
271
- dshHome: layout.dshHome,
272
- browserCarrier: carrier.status,
273
- }
274
- }
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
-
287
- export async function stopRemoteWeb(ssh, layout, options = {}) {
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.
300
- const script = `set -u
301
- umask 077
302
- RUN=${shellQuote(layout.runFile)}
303
- PID=${isPid(pid) ? pid : 0}
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
321
- fi
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
331
- n=0
332
- while [ "$n" -lt 10 ]; do
333
- kill -0 "$PID" 2>/dev/null || break
334
- n=$((n+1))
335
- sleep 0.5
336
- done
337
- fi
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"
344
- `
345
- try {
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 }
354
- } catch (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'),
393
- }
394
- }
395
-
396
- export async function readRunRegistry(ssh, layout) {
397
- try {
398
- const result = await ssh.exec(`cat ${shellQuote(layout.runFile)} 2>/dev/null || true`, { timeoutMs: 10_000 })
399
- if (result.code !== 0 || result.stdout.trim() === '') return null
400
- return parseRunRegistry(result.stdout)
401
- } catch {
402
- return null
403
- }
404
- }
405
-
406
- export async function readWebLineFromLog(ssh, layout) {
407
- try {
408
- const result = await ssh.exec(`grep 'dsh web:' ${shellQuote(layout.logFile)} 2>/dev/null | tail -n 1 || true`, {
409
- timeoutMs: 15_000,
410
- })
411
- if (result.code !== 0 || !result.stdout.trim()) return null
412
- return parseWebLine(result.stdout)
413
- } catch {
414
- return null
415
- }
416
- }
417
-
418
- export async function remotePidAlive(ssh, pid) {
419
- if (!isPid(pid)) return false
420
- try {
421
- const result = await ssh.exec(`kill -0 ${pid} 2>/dev/null && echo alive || true`, { timeoutMs: 10_000 })
422
- return result.stdout.includes('alive')
423
- } catch {
424
- return false
425
- }
426
- }
427
-
428
- /**
429
- * Try to adopt a still-running remote web instance from a previous local
430
- * process: registry pid alive + last log line parseable + loopback HTTP alive.
431
- *
432
- * The registry must name the same DSH home and profile this connection is about
433
- * to use; a process left over from another home or profile would show a
434
- * different DSH state than the user asked for.
435
- */
436
- export async function adoptRemoteWeb(ssh, layout, options = {}) {
437
- const profile = options.profile ?? DEFAULT_REMOTE_PROFILE
438
- const registry = await readRunRegistry(ssh, layout)
439
- // Instances from a launch path that did not apply the browser-carrier overlay
440
- // cannot be adopted: the page they serve may be stuck at "failed to load
441
- // plugins", and nothing on the server side reveals that.
442
- if (registry?.launch !== LAUNCH_MARKER) return null
443
- if (registry?.dshHome !== layout.dshHome) return null
444
- if (registry?.profile !== profile) return null
445
- const pid = Number(registry?.pid ?? 0)
446
- if (!(await remotePidAlive(ssh, pid))) return null
447
- const line = await readWebLineFromLog(ssh, layout)
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
453
- const status = await remoteHttpStatus(ssh, line.port)
454
- if (!isUiUp(status)) return null
455
- const version =
456
- typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null
457
- return {
458
- pid,
459
- port: line.port,
460
- token: line.token,
461
- url: line.url,
462
- version,
463
- profile,
464
- dshHome: layout.dshHome,
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
- }
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' }
751
- }