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,310 @@
1
+ /**
2
+ * Probing the remote DSH web: the `dsh web:` readiness line, the pid liveness check, adoption of
3
+ * an instance an earlier local run left behind, the real version a process runs, and the
4
+ * re-attach probe that refuses a candidate it cannot prove (`no-token`, `identity-*`, …).
5
+ *
6
+ * Everything here answers "what is running, and may this connection talk to it?"; starting and
7
+ * stopping live in `start.ts` / `stop.ts`, and the run-registry record in `registry.ts`.
8
+ */
9
+ import { DEFAULT_REMOTE_PROFILE } from '../constants.js';
10
+ import { findForeignDshProcesses, isUiUp, remoteHttpStatus, remoteListenPorts, remotePortOwnerPid, remoteProcessIdentity, } from '../remote-proc.js';
11
+ import { isLoopbackHost, isPid, shellQuote } from '../util.js';
12
+ import { normalizeVersion } from '../version.js';
13
+ import { LAUNCH_MARKER, isPlainObjectValue, readRunRegistry } from './registry.js';
14
+ const WEB_LINE_RE = /dsh web:\s*(https?:\/\/[^\s]+)/;
15
+ export function parseWebLine(text) {
16
+ const match = WEB_LINE_RE.exec(String(text ?? ''));
17
+ if (!match)
18
+ return null;
19
+ const rawUrl = match[1];
20
+ let url;
21
+ try {
22
+ url = new URL(rawUrl);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ const host = url.hostname.replace(/^\[|\]$/g, '');
28
+ const port = url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80;
29
+ const token = url.searchParams.get('token') ?? '';
30
+ if (!isPid(port))
31
+ return null;
32
+ return { url: rawUrl, host, port, token, rawLine: match[0] };
33
+ }
34
+ export async function readWebLineFromLog(ssh, layout) {
35
+ try {
36
+ const result = await ssh.exec(`grep 'dsh web:' ${shellQuote(layout.logFile)} 2>/dev/null | tail -n 1 || true`, {
37
+ timeoutMs: 15_000,
38
+ });
39
+ if (result.code !== 0 || !result.stdout.trim())
40
+ return null;
41
+ return parseWebLine(result.stdout);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ export async function remotePidAlive(ssh, pid) {
48
+ if (!isPid(pid))
49
+ return false;
50
+ try {
51
+ const result = await ssh.exec(`kill -0 ${pid} 2>/dev/null && echo alive || true`, { timeoutMs: 10_000 });
52
+ return result.stdout.includes('alive');
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /**
59
+ * Try to adopt a still-running remote web instance from a previous local
60
+ * process: registry pid alive + last log line parseable + loopback HTTP alive.
61
+ *
62
+ * The registry must name the same DSH home and profile this connection is about
63
+ * to use; a process left over from another home or profile would show a
64
+ * different DSH state than the user asked for.
65
+ */
66
+ export async function adoptRemoteWeb(ssh, layout, options = {}) {
67
+ const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
68
+ const registry = await readRunRegistry(ssh, layout);
69
+ // Instances from a launch path that did not apply the browser-carrier overlay
70
+ // cannot be adopted: the page they serve may be stuck at "failed to load
71
+ // plugins", and nothing on the server side reveals that.
72
+ if (registry?.launch !== LAUNCH_MARKER)
73
+ return null;
74
+ if (registry?.dshHome !== layout.dshHome)
75
+ return null;
76
+ if (registry?.profile !== profile)
77
+ return null;
78
+ const pid = Number(registry?.pid ?? 0);
79
+ if (!(await remotePidAlive(ssh, pid)))
80
+ return null;
81
+ const line = await readWebLineFromLog(ssh, layout);
82
+ if (!line || line.token === '')
83
+ return null;
84
+ // An adopted instance is reached through the loopback tunnel only: a process that
85
+ // advertises another host cannot be served safely and must not be adopted (adopt parity
86
+ // with a fresh launch, which refuses a non-loopback URL).
87
+ if (!isLoopbackHost(line.host))
88
+ return null;
89
+ const status = await remoteHttpStatus(ssh, line.port);
90
+ if (!isUiUp(status))
91
+ return null;
92
+ const version = typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null;
93
+ return {
94
+ pid,
95
+ port: line.port,
96
+ token: line.token,
97
+ url: line.url,
98
+ version,
99
+ profile,
100
+ dshHome: layout.dshHome,
101
+ adopted: true,
102
+ // Only a record written by the launch script (or a local restart) proves the process was
103
+ // started by this plugin; a re-attached record names a process the remote restarted itself
104
+ // and must not grant kill rights to the next connection.
105
+ origin: registry.origin === 'reattach' ? 'reattach' : 'launch',
106
+ };
107
+ }
108
+ /** Whether a `ps` command line is the DSH process for this profile. */
109
+ export function commandMatchesProfile(command, profile) {
110
+ const wanted = String(profile ?? '');
111
+ if (wanted === '')
112
+ return false;
113
+ const escaped = wanted.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
114
+ return new RegExp(`--profile[=\\s]+${escaped}(?:\\s|$)`).test(String(command ?? ''));
115
+ }
116
+ /** The pinned `@deepseek-ai/dsh@<version>` an npx command line names, if any. */
117
+ export function versionFromCommand(command) {
118
+ const match = /@deepseek-ai\/dsh@([^\s'"]+)/.exec(String(command ?? ''));
119
+ return match ? normalizeVersion(match[1]) : null;
120
+ }
121
+ /**
122
+ * The installed package directory a real node argv names, e.g.
123
+ * `/home/u/.npm/_npx/<hash>/node_modules/@deepseek-ai/dsh` or an app install path.
124
+ * The version is read from that directory's `package.json` (the argv itself does not
125
+ * carry one in the npx-cache and app-install shapes).
126
+ */
127
+ export function dshPackageDirFromCommand(command) {
128
+ const text = String(command ?? '');
129
+ const marker = '/node_modules/@deepseek-ai/dsh';
130
+ // Linear scan on purpose: a nested-quantifier regex over an argv with many `/` segments can be
131
+ // made to backtrack exponentially, and the command line is remote input.
132
+ let at = text.indexOf(marker);
133
+ while (at !== -1) {
134
+ const rest = text.slice(at + marker.length);
135
+ if (/^(?:\/lib\/bin\.js|[\s'"]|$)/.test(rest)) {
136
+ let start = at;
137
+ while (start > 0 && !/[\s'"]/.test(text[start - 1]))
138
+ start -= 1;
139
+ const dir = text.slice(start, at + marker.length);
140
+ if (dir.startsWith('/') && !dir.split('/').includes('..'))
141
+ return dir;
142
+ return null;
143
+ }
144
+ at = text.indexOf(marker, at + marker.length);
145
+ }
146
+ return null;
147
+ }
148
+ /** Read the version of the DSH package a process actually loaded, over SFTP (no shell). */
149
+ async function packageVersionFromDir(ssh, dir) {
150
+ if (!dir || typeof ssh.readRemoteFile !== 'function')
151
+ return null;
152
+ try {
153
+ const file = await ssh.readRemoteFile(`${dir}/package.json`, { maxBytes: 64 * 1024 });
154
+ const text = Buffer.isBuffer(file?.data) ? file.data.toString('utf8') : String(file?.data ?? '');
155
+ const parsed = JSON.parse(text);
156
+ const version = isPlainObjectValue(parsed) && typeof parsed.version === 'string' ? normalizeVersion(parsed.version) : '';
157
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ? version : null;
158
+ }
159
+ catch {
160
+ // swallow-ok: an unreadable package.json only means the version stays unknown (never assumed)
161
+ return null;
162
+ }
163
+ }
164
+ /**
165
+ * The real version a remote DSH process runs: the pinned npx spec when there is one,
166
+ * otherwise the `package.json` of the package its argv loaded. Null when it cannot be
167
+ * proven - the caller must not fill in the local version.
168
+ */
169
+ export async function remoteDshVersion(ssh, command) {
170
+ const pinned = versionFromCommand(command);
171
+ if (pinned)
172
+ return pinned;
173
+ const dir = dshPackageDirFromCommand(command);
174
+ return dir === null ? null : packageVersionFromDir(ssh, dir);
175
+ }
176
+ /**
177
+ * Re-read the remote's real web state after it restarted: the same pid on a new
178
+ * random port (in-place exec) or a new pid from a supervisor. The run registry is only
179
+ * a hint; a candidate is accepted only when all of these hold:
180
+ *
181
+ * - the listening port belongs to the pid the plugin thinks it owns;
182
+ * - that pid's `/proc` identity proves the same `DSH_HOME` and the same `--profile`;
183
+ * - the newest `dsh web:` line names that exact port, so a launch token is available.
184
+ *
185
+ * A candidate that answers HTTP but has no token is **not** usable: a real DSH answers
186
+ * `/?token=` with 401, so claiming success would be dishonest. The process-scan fallback
187
+ * therefore never yields a takeover; it only turns the failure reason into `no-token`
188
+ * ("still running, but no way to authenticate") so the user gets the right remedy.
189
+ */
190
+ export async function resolveRemoteWeb(ssh, layout, options = {}) {
191
+ const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
192
+ const registry = await readRunRegistry(ssh, layout);
193
+ const line = await readWebLineFromLog(ssh, layout);
194
+ const registryMatches = registry !== null &&
195
+ registry.dshHome === layout.dshHome &&
196
+ registry.profile === profile &&
197
+ registry.launch === LAUNCH_MARKER;
198
+ const registryPid = Number(registry?.pid ?? 0);
199
+ const registryVersion = typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null;
200
+ const alive = registryMatches && isPid(registryPid) && (await remotePidAlive(ssh, registryPid));
201
+ let listeners = null;
202
+ const listenersOf = async (pid) => {
203
+ if (listeners === null)
204
+ listeners = await remoteListenPorts(ssh, pid);
205
+ return listeners;
206
+ };
207
+ let tokenlessPort = 0;
208
+ let firstFailure = null;
209
+ /**
210
+ * Accept one reachable candidate only when its identity and its token both check out.
211
+ * Returns null for "reachable but no token" and a typed failure for "wrong process".
212
+ */
213
+ const take = async (pid, port, source) => {
214
+ const identity = await remoteProcessIdentity(ssh, pid);
215
+ if (identity.ok !== true)
216
+ return { ok: false, reason: `identity-${identity.reason}` };
217
+ if (!commandMatchesProfile(identity.command, profile))
218
+ return { ok: false, reason: 'profile-mismatch' };
219
+ if (identity.dshHome === '' || identity.dshHome !== layout.dshHome) {
220
+ return { ok: false, reason: 'dsh-home-mismatch' };
221
+ }
222
+ const token = line !== null && line.port === port ? line.token : '';
223
+ if (token === '') {
224
+ tokenlessPort = port;
225
+ return null;
226
+ }
227
+ const proven = await remoteDshVersion(ssh, identity.command);
228
+ return {
229
+ ok: true,
230
+ pid,
231
+ port,
232
+ token,
233
+ url: line.url,
234
+ // Never backfill the local version: an unproven version stays null.
235
+ version: proven ?? (pid === registryPid ? registryVersion : null),
236
+ profile,
237
+ dshHome: identity.dshHome,
238
+ source,
239
+ };
240
+ };
241
+ const rememberFailure = (candidate) => {
242
+ if (candidate !== null && candidate.ok !== true && firstFailure === null)
243
+ firstFailure = candidate;
244
+ };
245
+ // 1. The instance this plugin started: the registry still names a live pid. Only ports
246
+ // that pid actually listens on are candidates, and the readiness line must name the
247
+ // same port for its launch token to be used.
248
+ if (alive) {
249
+ const candidates = [...(await listenersOf(registryPid))];
250
+ if (isPid(Number(registry?.port ?? 0)))
251
+ candidates.push(Number(registry.port));
252
+ for (const port of [...new Set(candidates.filter((value) => isPid(value) && value <= 65535))]) {
253
+ if (!isUiUp(await remoteHttpStatus(ssh, port)))
254
+ continue;
255
+ // The port must belong to the pid whose identity we are about to trust. Without a
256
+ // readable owner (restricted /proc) the candidate is refused: fail closed.
257
+ const owner = await remotePortOwnerPid(ssh, port);
258
+ if (!isPid(owner) || owner !== registryPid)
259
+ continue;
260
+ const candidate = await take(registryPid, port, 'registry');
261
+ if (candidate?.ok === true)
262
+ return candidate;
263
+ rememberFailure(candidate);
264
+ }
265
+ }
266
+ // 2. A readiness line for a port owned by some other pid (the market restart re-execs
267
+ // in place, or a supervisor re-launched it). The owner pid must prove itself.
268
+ if (line !== null && isPid(line.port) && isUiUp(await remoteHttpStatus(ssh, line.port))) {
269
+ let pid = 0;
270
+ if (alive && (await listenersOf(registryPid)).includes(line.port))
271
+ pid = registryPid;
272
+ // The owner lookup is authoritative even when the registry pid is alive: the newest line
273
+ // may belong to another profile's process that shares this plugin's log file.
274
+ if (!isPid(pid))
275
+ pid = await remotePortOwnerPid(ssh, line.port);
276
+ if (isPid(pid)) {
277
+ const candidate = await take(pid, line.port, 'log');
278
+ if (candidate?.ok === true)
279
+ return candidate;
280
+ rememberFailure(candidate);
281
+ }
282
+ else {
283
+ firstFailure = { ok: false, reason: 'pid-unknown' };
284
+ }
285
+ }
286
+ // 3. No usable readiness line (a supervisor may redirect stdout). Find the same-profile
287
+ // DSH process only to explain the failure: without its launch token it cannot be
288
+ // re-attached, so this path never returns ok.
289
+ const scanned = await findForeignDshProcesses(ssh, { ignorePids: alive ? [registryPid] : [] });
290
+ if (scanned.ok === true) {
291
+ for (const process of scanned.processes) {
292
+ if (!commandMatchesProfile(process.command, profile))
293
+ continue;
294
+ const ports = await remoteListenPorts(ssh, process.pid);
295
+ for (const port of ports) {
296
+ if (!isUiUp(await remoteHttpStatus(ssh, port)))
297
+ continue;
298
+ const identity = await remoteProcessIdentity(ssh, process.pid);
299
+ if (identity.ok === true && identity.dshHome === layout.dshHome) {
300
+ return { ok: false, reason: 'no-token' };
301
+ }
302
+ }
303
+ }
304
+ }
305
+ if (firstFailure !== null)
306
+ return firstFailure;
307
+ if (tokenlessPort !== 0)
308
+ return { ok: false, reason: 'no-token' };
309
+ return { ok: false, reason: alive ? 'no-listener' : 'no-running-web' };
310
+ }
@@ -0,0 +1,227 @@
1
+ import { DEFAULT_REMOTE_PROFILE, REMOTE_START_TIMEOUT_MS } from '../constants.js';
2
+ import { errors } from '../errors.js';
3
+ import { remoteLayout } from '../layout.js';
4
+ import { headTail, isLoopbackHost, isPid, messageOf, shellQuote } from '../util.js';
5
+ import { normalizeVersion } from '../version.js';
6
+ import { LAUNCH_MARKER } from './registry.js';
7
+ import { parseWebLine, remotePidAlive } from './resolve.js';
8
+ import { stopRemoteWeb } from './stop.js';
9
+ /** Overlay file the launch passes with `--patch` when the profile disables the carrier. */
10
+ export const BROWSER_CARRIER_PATCH_FILE = 'browser-carrier.patch.yml';
11
+ /**
12
+ * The window shows the remote DSH *web* UI, so the `api-remotes` Remote-Event
13
+ * carrier must stay mounted. A profile bundle aimed at a native companion can
14
+ * disable that row (e.g. goldenpigeon's patch does), which leaves the browser
15
+ * client with `typert gateway: $events: forwarded Remote event source is
16
+ * unavailable` and a blank "failed to load plugins" page. Re-enable the row with
17
+ * a launch-only overlay instead of editing the user's profile.
18
+ */
19
+ const BROWSER_CARRIER_PATCH = `# Written by dsh-remote-go. The remote window is a browser client, so the
20
+ # Remote-Event carrier (api-remotes) must stay enabled even when a profile
21
+ # bundle disables it for a native-UI companion.
22
+ - id: api-remotes
23
+ disabled: false`;
24
+ export function buildStartCommand(plan, layout, options = {}) {
25
+ const profile = options.profile ?? plan.profile ?? DEFAULT_REMOTE_PROFILE;
26
+ const patch = options.patchPath ? `--patch ${shellQuote(options.patchPath)} ` : '';
27
+ const args = `${patch}--profile ${shellQuote(profile)} --no-open --port 0`;
28
+ const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
29
+ return `env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} ${args}`;
30
+ }
31
+ export function buildBrowserCarrierProbe(plan, layout, profile) {
32
+ const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
33
+ const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`);
34
+ const patchFile = shellQuote(`${layout.root}/${BROWSER_CARRIER_PATCH_FILE}`);
35
+ // The dump contains the profile's effective configuration: it is created 0600 and removed
36
+ // again before this script returns, on both the success and the failure path (M3).
37
+ return `set -u
38
+ umask 077
39
+ mkdir -p ${shellQuote(layout.root)}
40
+ DUMP=${dumpFile}
41
+ 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
42
+ echo "DUMP-FAILED"
43
+ rm -f "$DUMP"
44
+ exit 0
45
+ fi
46
+ if grep -A6 'id: api-remotes' "$DUMP" | grep -q 'disabled: true'; then
47
+ cat > ${patchFile} <<'DSH_REMOTE_GO_PATCH'
48
+ ${BROWSER_CARRIER_PATCH}
49
+ DSH_REMOTE_GO_PATCH
50
+ echo "PATCH"
51
+ else
52
+ echo "CLEAR"
53
+ fi
54
+ rm -f "$DUMP"`;
55
+ }
56
+ export async function ensureBrowserCarrier(ssh, options) {
57
+ try {
58
+ const result = await ssh.exec(buildBrowserCarrierProbe(options.plan, options.layout, options.profile), {
59
+ timeoutMs: 60_000,
60
+ maxBytes: 64_000,
61
+ });
62
+ if (result.code === 0 && result.stdout.includes('PATCH')) {
63
+ options.onLine?.('browser carrier: the profile disables api-remotes; re-enabling it for this launch');
64
+ return {
65
+ status: 'patched',
66
+ patchPath: `${options.layout.root}/${BROWSER_CARRIER_PATCH_FILE}`,
67
+ };
68
+ }
69
+ if (result.code === 0 && result.stdout.includes('CLEAR')) {
70
+ options.onLine?.('browser carrier: api-remotes is enabled by the profile');
71
+ return { status: 'clear', patchPath: null };
72
+ }
73
+ options.onLine?.(`browser carrier: profile probe failed (${headTail(result.stdout + result.stderr, 300)})`);
74
+ return { status: 'unknown', patchPath: null };
75
+ }
76
+ catch (error) {
77
+ // swallow-ok: probe failure — launching without the overlay keeps the start
78
+ // error (missing profile, npx failure) as the actionable one.
79
+ options.onLine?.(`browser carrier: probe failed (${messageOf(error)})`);
80
+ return { status: 'unknown', patchPath: null };
81
+ }
82
+ }
83
+ export function buildStartScript(startCommand, layout, options = {}) {
84
+ const waitSeconds = options.waitSeconds ?? Math.ceil(REMOTE_START_TIMEOUT_MS / 1000);
85
+ const version = normalizeVersion(options.version ?? '');
86
+ const profile = options.profile ?? DEFAULT_REMOTE_PROFILE;
87
+ const logFile = shellQuote(layout.logFile);
88
+ const runFile = shellQuote(layout.runFile);
89
+ const startedAtPlaceholder = '$(date -u +%Y-%m-%dT%H:%M:%SZ)';
90
+ // `umask 077` keeps the log (and the launch's state directory) private: the log carries the
91
+ // launch URL with its token, and the default umask used to leave it world-readable (M3).
92
+ // The run registry is written to a temp file and renamed, so a reader never sees a
93
+ // half-written record (M4).
94
+ return `set -eu
95
+ umask 077
96
+ mkdir -p ${shellQuote(layout.logsDir)} ${shellQuote(layout.runDir)} ${shellQuote(layout.stateHome)}
97
+ LOG=${logFile}
98
+ : > "$LOG"
99
+ chmod 600 "$LOG" 2>/dev/null || true
100
+ cd "$HOME"
101
+ setsid nohup bash -lc ${shellQuote(startCommand)} >> "$LOG" 2>&1 < /dev/null &
102
+ PID=$!
103
+ echo "PID:$PID"
104
+ i=0
105
+ while [ "$i" -lt ${waitSeconds} ]; do
106
+ if grep -q 'dsh web:' "$LOG" 2>/dev/null; then break; fi
107
+ if ! kill -0 "$PID" 2>/dev/null; then
108
+ echo "EXITED:$PID"
109
+ echo "---LOG---"
110
+ tail -n 60 "$LOG" 2>/dev/null || true
111
+ exit 3
112
+ fi
113
+ i=$((i+1))
114
+ sleep 1
115
+ done
116
+ LINE=$(grep -m1 'dsh web:' "$LOG" 2>/dev/null || true)
117
+ if [ -z "$LINE" ]; then
118
+ echo "TIMEOUT"
119
+ echo "---LOG---"
120
+ tail -n 60 "$LOG" 2>/dev/null || true
121
+ exit 4
122
+ fi
123
+ echo "LINE:$LINE"
124
+ PORT=$(printf '%s' "$LINE" | sed -n 's#.*127\\.0\\.0\\.1:\\([0-9][0-9]*\\)/.*#\\1#p')
125
+ if [ -z "$PORT" ]; then PORT=$(printf '%s' "$LINE" | sed -n 's#.*:\\([0-9][0-9]*\\)/.*#\\1#p'); fi
126
+ RUN=${runFile}
127
+ TMP="$RUN.tmp.$$"
128
+ 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"
129
+ mv -f "$TMP" "$RUN"
130
+ echo "DONE:$PID:$PORT"
131
+ `;
132
+ }
133
+ /** The pid the launch script announced, from `DONE:` or the earlier `PID:` line. */
134
+ export function parseLaunchedPid(text) {
135
+ const combined = String(text ?? '');
136
+ const done = /DONE:(\d+):(\d+)/.exec(combined);
137
+ if (done)
138
+ return { pid: Number(done[1]), port: Number(done[2]) };
139
+ const started = /(?:^|\n)PID:(\d+)\s*(?:\n|$)/.exec(combined);
140
+ if (started)
141
+ return { pid: Number(started[1]), port: 0 };
142
+ return { pid: 0, port: 0 };
143
+ }
144
+ /**
145
+ * Stop a launch that failed *after* it started: the detached process must not be left
146
+ * running on the remote just because its readiness line never parsed (M2).
147
+ *
148
+ * Only the pid this launch script printed is ours to stop. `run/web.json` may name another
149
+ * instance (a re-attached process, or a previous launch), so it is deliberately not used as
150
+ * a fallback here: killing that pid would be exactly the "a re-attached instance is not
151
+ * stopped" rule the connect pipeline enforces (review blocker 2).
152
+ */
153
+ async function stopFailedLaunch(ssh, layout, startedPid, onLine) {
154
+ if (!isPid(startedPid))
155
+ return { ok: false, pid: null };
156
+ let alive = false;
157
+ try {
158
+ alive = await remotePidAlive(ssh, startedPid);
159
+ }
160
+ catch {
161
+ // swallow-ok: an unreadable liveness check means "cannot prove it is ours", so no signal
162
+ return { ok: false, pid: null };
163
+ }
164
+ if (!alive)
165
+ return { ok: false, pid: null };
166
+ const stopped = await stopRemoteWeb(ssh, layout, { pid: startedPid });
167
+ onLine?.(`start failed after pid ${startedPid} was launched; ${stopped.ok === true ? 'it was stopped' : 'it could not be stopped'}`);
168
+ return { ok: stopped.ok === true, pid: startedPid, output: stopped.output };
169
+ }
170
+ export async function startRemoteWeb(ssh, options) {
171
+ const layout = options.layout ?? remoteLayout(options.home);
172
+ const profile = options.profile ?? options.plan.profile ?? DEFAULT_REMOTE_PROFILE;
173
+ const carrier = await ensureBrowserCarrier(ssh, { plan: options.plan, layout, profile, onLine: options.onLine });
174
+ const startCommand = buildStartCommand(options.plan, layout, { profile, patchPath: carrier.patchPath });
175
+ const script = buildStartScript(startCommand, layout, {
176
+ waitSeconds: Math.ceil((options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) / 1000),
177
+ version: options.plan.start.targetVersion,
178
+ profile,
179
+ });
180
+ const lines = [];
181
+ const result = await ssh.exec(script, {
182
+ timeoutMs: (options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) + 30_000,
183
+ maxBytes: 200_000,
184
+ onStdout: (chunk) => {
185
+ for (const line of chunk.split(/\r?\n/)) {
186
+ if (line !== '') {
187
+ lines.push(line);
188
+ options.onLine?.(line);
189
+ }
190
+ }
191
+ },
192
+ });
193
+ const combined = `${result.stdout}\n${result.stderr}`;
194
+ // The launch script prints its pid before it waits for the readiness line: keep it even
195
+ // when the wait itself fails, so a failure can stop what it started (M2).
196
+ const launched = parseLaunchedPid(combined);
197
+ const failed = async (error) => {
198
+ await stopFailedLaunch(ssh, layout, launched.pid, options.onLine);
199
+ return error;
200
+ };
201
+ if (result.code !== 0) {
202
+ throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
203
+ }
204
+ const parsed = parseWebLine(combined);
205
+ if (!parsed)
206
+ throw await failed(errors.remoteDshStartFailed(headTail(combined, 1500)));
207
+ if (!isLoopbackHost(parsed.host)) {
208
+ throw await failed(errors.remoteUiUnreachable({
209
+ zh: `远端 DSH 宣布的地址不是回环地址(${parsed.host}),无法安全地经 SSH 隧道访问。`,
210
+ en: `The remote DSH advertised a non-loopback host (${parsed.host}); it cannot be reached safely through the SSH tunnel.`,
211
+ }));
212
+ }
213
+ const pid = launched.pid;
214
+ const startedAt = new Date().toISOString();
215
+ return {
216
+ pid,
217
+ port: parsed.port,
218
+ token: parsed.token,
219
+ url: parsed.url,
220
+ logPath: layout.logFile,
221
+ startedAt,
222
+ rawLine: parsed.rawLine,
223
+ profile,
224
+ dshHome: layout.dshHome,
225
+ browserCarrier: carrier.status,
226
+ };
227
+ }
@@ -0,0 +1,93 @@
1
+ import { remotePortOwnerPid } from '../remote-proc.js';
2
+ import { isPid, messageOf, shellQuote } from '../util.js';
3
+ import { readRunRegistry } from './registry.js';
4
+ import { readWebLineFromLog } from './resolve.js';
5
+ /**
6
+ * The pid a readiness line in the log belongs to, as a last resort for a stop whose pid is
7
+ * unknown. The log only names the port; `/proc` proves which process listens on it (M4).
8
+ */
9
+ async function pidFromReadinessLine(ssh, layout) {
10
+ const line = await readWebLineFromLog(ssh, layout);
11
+ if (!line || !isPid(line.port))
12
+ return 0;
13
+ const owner = await remotePortOwnerPid(ssh, line.port);
14
+ return isPid(Number(owner)) ? Number(owner) : 0;
15
+ }
16
+ export async function stopRemoteWeb(ssh, layout, options = {}) {
17
+ let pid = Number(options.pid ?? 0);
18
+ if (!isPid(pid)) {
19
+ // The run registry is the primary record; a partially written one still names a pid, and
20
+ // the readiness line's port owner is the last resort (M4).
21
+ const registry = await readRunRegistry(ssh, layout);
22
+ pid = Number(registry?.pid ?? 0);
23
+ }
24
+ if (!isPid(pid))
25
+ pid = await pidFromReadinessLine(ssh, layout);
26
+ // The registry is removed only after the stop is confirmed: a failed stop must leave the
27
+ // record in place, otherwise the next connect adopts nothing and a second instance starts
28
+ // next to the surviving one (M4). It is also removed only when it names *this* pid: a
29
+ // record that belongs to another instance (a re-attach) is not ours to delete.
30
+ const script = `set -u
31
+ umask 077
32
+ RUN=${shellQuote(layout.runFile)}
33
+ PID=${isPid(pid) ? pid : 0}
34
+ if [ "$PID" -eq 0 ] && [ -f "$RUN" ]; then
35
+ PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$RUN" | head -n 1)
36
+ fi
37
+ PID="\${PID:-0}"
38
+ if [ "$PID" -eq 0 ]; then
39
+ echo "NO-TARGET"
40
+ exit 5
41
+ fi
42
+ drop_own_record() {
43
+ if [ ! -f "$RUN" ]; then return 0; fi
44
+ REC_PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$RUN" 2>/dev/null | head -n 1)
45
+ if [ "\${REC_PID:-}" = "$PID" ]; then rm -f "$RUN"; fi
46
+ }
47
+ if ! kill -0 "$PID" 2>/dev/null; then
48
+ echo "GONE:$PID"
49
+ drop_own_record
50
+ exit 0
51
+ fi
52
+ kill -TERM "-$PID" 2>/dev/null || kill -TERM "$PID" 2>/dev/null || true
53
+ n=0
54
+ while [ "$n" -lt 20 ]; do
55
+ kill -0 "$PID" 2>/dev/null || break
56
+ n=$((n+1))
57
+ sleep 0.5
58
+ done
59
+ if kill -0 "$PID" 2>/dev/null; then
60
+ kill -KILL "-$PID" 2>/dev/null || kill -KILL "$PID" 2>/dev/null || true
61
+ n=0
62
+ while [ "$n" -lt 10 ]; do
63
+ kill -0 "$PID" 2>/dev/null || break
64
+ n=$((n+1))
65
+ sleep 0.5
66
+ done
67
+ fi
68
+ if kill -0 "$PID" 2>/dev/null; then
69
+ echo "ALIVE:$PID"
70
+ exit 6
71
+ fi
72
+ drop_own_record
73
+ echo "STOPPED:$PID"
74
+ `;
75
+ try {
76
+ const result = await ssh.exec(script, { timeoutMs: 40_000 });
77
+ const output = result.stdout.trim();
78
+ // An explicit pid that is already gone means the same thing as no target at all: there
79
+ // is nothing left to signal (the caller can clear the stale registry).
80
+ if (output.includes('NO-TARGET'))
81
+ return { ok: false, reason: 'no-target', output };
82
+ if (output.includes('ALIVE:'))
83
+ return { ok: false, reason: 'alive', output };
84
+ if (result.code !== 0)
85
+ return { ok: false, reason: 'not-confirmed', output };
86
+ return { ok: true, output };
87
+ }
88
+ catch (error) {
89
+ // swallow-ok: a throw here is a transport failure, reported as an unconfirmed stop so the
90
+ // caller keeps the run registry instead of adopting nothing on the next connect
91
+ return { ok: false, reason: 'error', output: messageOf(error) };
92
+ }
93
+ }