dsh-ris-ide 1.7.3 → 1.8.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 (75) hide show
  1. package/README.md +21 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +284 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +609 -1178
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/proxybridge-health.js +206 -0
  11. package/lib/redirector.js +1615 -115
  12. package/lib/risd/build.js +91 -0
  13. package/lib/risd/debug.js +374 -0
  14. package/lib/risd/git.js +207 -0
  15. package/lib/risd/leases.js +124 -0
  16. package/lib/risd/lifecycle.js +148 -0
  17. package/lib/risd/log.js +59 -0
  18. package/lib/risd/ping.js +94 -0
  19. package/lib/risd/programs.js +348 -0
  20. package/lib/risd/server.js +1919 -0
  21. package/lib/risd/state.js +137 -0
  22. package/lib/risd/ui.js +1989 -0
  23. package/lib/risd/view.js +79 -0
  24. package/lib/risd-client.js +282 -0
  25. package/lib/standalone/window.html +14 -16
  26. package/lib/startup.js +114 -0
  27. package/package.json +4 -1
  28. package/test/client-build.test.mjs +113 -0
  29. package/test/client-viewer.test.mjs +279 -227
  30. package/test/dsh-origin.test.mjs +140 -0
  31. package/test/dsh-window-refresh.test.mjs +100 -0
  32. package/test/harness.test.mjs +9 -0
  33. package/test/host-noloop.test.mjs +74 -0
  34. package/test/host-tail.test.mjs +21 -4
  35. package/test/host-window.test.mjs +4 -4
  36. package/test/janitor.test.mjs +29 -1
  37. package/test/lifecycle.test.mjs +26 -5
  38. package/test/merge-owners.test.mjs +155 -0
  39. package/test/proxy-restart.test.mjs +39 -0
  40. package/test/proxy-window.test.mjs +45 -0
  41. package/test/proxy.test.mjs +41 -0
  42. package/test/proxybridge-bundle.test.mjs +687 -0
  43. package/test/proxybridge-health.test.mjs +116 -0
  44. package/test/redirector-bundle.test.mjs +391 -0
  45. package/test/redirector.test.mjs +413 -10
  46. package/test/risd-api.test.mjs +514 -0
  47. package/test/risd-bridge-degrade.test.mjs +101 -0
  48. package/test/risd-build.test.mjs +20 -0
  49. package/test/risd-cli-home.test.mjs +50 -0
  50. package/test/risd-client.test.mjs +130 -0
  51. package/test/risd-debug.test.mjs +261 -0
  52. package/test/risd-election.test.mjs +104 -0
  53. package/test/risd-engine.test.mjs +132 -0
  54. package/test/risd-entry.test.mjs +118 -0
  55. package/test/risd-git.test.mjs +109 -0
  56. package/test/risd-handoff.test.mjs +116 -0
  57. package/test/risd-heal.test.mjs +50 -0
  58. package/test/risd-helpers.mjs +108 -0
  59. package/test/risd-host-p2.test.mjs +147 -0
  60. package/test/risd-janitor-guard.test.mjs +46 -0
  61. package/test/risd-lease.test.mjs +83 -0
  62. package/test/risd-lifecycle.test.mjs +210 -0
  63. package/test/risd-log-follow.test.mjs +227 -0
  64. package/test/risd-mode.test.mjs +161 -0
  65. package/test/risd-ping.test.mjs +99 -0
  66. package/test/risd-programs.test.mjs +169 -0
  67. package/test/risd-restart.test.mjs +104 -0
  68. package/test/risd-review-p2.test.mjs +217 -0
  69. package/test/risd-shutdown.test.mjs +97 -0
  70. package/test/risd-teardown.test.mjs +87 -0
  71. package/test/risd-tools.test.mjs +211 -0
  72. package/test/risd-ui.test.mjs +607 -0
  73. package/test/risd-write.test.mjs +170 -0
  74. package/test/startup-reconcile.test.mjs +100 -0
  75. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,1919 @@
1
+ /**
2
+ * risd — the daemon itself (Phase 1a: single instance, token, leases, read-only view).
3
+ *
4
+ * Why a separate process at all: the proxy is a machine-level resource, but the
5
+ * dsh process that used to own it is a per-session, restartable thing. Moving
6
+ * ownership into a daemon decouples the two; the plugin then holds a lease
7
+ * instead of a process handle. Phase 1a deliberately stops at the read-only
8
+ * half: the engine is still started/stopped by the plugin, so nothing about
9
+ * today's behaviour changes until `daemonMode=auto` opts in.
10
+ *
11
+ * The only listener is 127.0.0.1. Every endpoint except `/v1/health` needs the
12
+ * token from `risd.json` AND the API version header — a stale plugin talking to
13
+ * a newer daemon gets a 409 it can explain, not a 404 or a silent mismatch.
14
+ *
15
+ * @module dsh-risd/server
16
+ */
17
+ import { spawn } from 'node:child_process'
18
+ import { createServer, request } from 'node:http'
19
+ import { existsSync, readFileSync, statSync } from 'node:fs'
20
+ import { isAbsolute, join, win32 } from 'node:path'
21
+ import { timingSafeEqual } from 'node:crypto'
22
+ import { fileURLToPath } from 'node:url'
23
+ import { DEFAULT_RISD_PORT, RISD_API_VERSION, newRisdToken, readRisdState, removeRisdState, writeRisdState } from './state.js'
24
+ import { createLeaseRegistry } from './leases.js'
25
+ import { injectionFor, mergeConfigs, pidAlive, proxyHomeDir, proxyLogPath, proxyPid, proxyStatus, readProxyConfig, readTail, startProxy, stopProxy, writeProxyConfig } from '../proxy.js'
26
+ import { BUNDLE_URLS, MAX_TGZ_BYTES, ensureBundle, installDir, installFromTgz, isInstalled, readManifest, resolveBundleUrls } from '../proxybridge-bundle.js'
27
+ // The digest helpers are part of the bundle module's contract for this release but
28
+ // arrive with the download/upload work; access them through the namespace so this
29
+ // module keeps loading (and verification stays disabled) if they are absent.
30
+ import * as bundleApi from '../proxybridge-bundle.js'
31
+ import { armJanitor, disarmJanitor, janitorStatus, markJanitorHandoff } from '../janitor.js'
32
+ import { bundledBundleDir, posixToWindowsPath, readElevationState, REDIRECTOR_PID_FILENAMES, REDIRECTOR_PID_FILENAME, redirectorCommand, redirectorHome, redirectorProfilePath, redirectorStatusAsync, redirectorStatusCached, reloadRedirectorsWithProfile, startRedirectors, stopRedirector, windowsBundleDir, writeHeartbeat } from '../redirector.js'
33
+ import { risdConfigRevision, risdProxyView } from './view.js'
34
+ import { clearGitProxy, readGitProxyState, reconcileGitProxy, syncGitProxy } from './git.js'
35
+ import { findProgram, listPrograms, readProgramLog, restartProgramByKey, startLogFollow, startProgramByKey, stopProgramByKey } from './programs.js'
36
+ import { reconcileStartupLeftovers } from '../startup.js'
37
+ import { createDebugEngine } from './debug.js'
38
+ import { mergeLifecycle, readLifecycle, writeLifecycle } from './lifecycle.js'
39
+ import { risdUiHtml } from './ui.js'
40
+ import { pingSocks } from './ping.js'
41
+ import { buildStamp } from './build.js'
42
+ import { DebugError, debugErrorStatus } from '../debug/engine.js'
43
+ import { createHealthCache } from '../proxybridge-health.js'
44
+
45
+ /** Request bodies are tiny JSON objects; anything bigger is a bug or an attack. */
46
+ export const RISD_MAX_BODY_BYTES = 64 * 1024
47
+ /**
48
+ * A streamed body (only the bundle upload does this) may not hold the request open
49
+ * forever: a stalled upload used to keep a handler alive until the socket died.
50
+ */
51
+ export const RISD_BODY_TIMEOUT_MS = 15_000
52
+ /** How long a would-be second instance waits for the incumbent's health answer. */
53
+ export const START_PROBE_TIMEOUT_MS = 500
54
+ /** Header the plugin sends on every authenticated call. */
55
+ export const API_VERSION_HEADER = 'x-risd-api-version'
56
+
57
+ /** Where the plugin reports its own origin + current sessionId (see /v1/dsh). */
58
+ export const DSH_WINDOW_FILENAME = 'dsh-window.json'
59
+ /** A window with an entry younger than this is marked live in the page. */
60
+ const DSH_WINDOW_LIVE_MS = 5 * 60_000
61
+ /** Remembered windows older than this are pruned; between the two they show as
62
+ * "未活跃" but stay selectable (m08268: clicking one may still open the IDE). */
63
+ const DSH_WINDOW_RETAIN_MS = 7 * 24 * 60 * 60_000
64
+
65
+ /** The daemon's own page is only for the local browser (no DNS rebinding). */
66
+ export function isLoopbackHost(req) {
67
+ const raw = String(req.headers.host ?? '')
68
+ const host = raw.replace(/^\[/, '').replace(/\](?::\d+)?$/, '')
69
+ if (host === '::1') return true
70
+ const name = host.split(':')[0]
71
+ return name === '127.0.0.1' || name === 'localhost'
72
+ }
73
+
74
+ /** True for an `Origin` header that points at this machine (the page's own origin). */
75
+ export function isLoopbackOrigin(origin) {
76
+ try {
77
+ const url = new URL(origin)
78
+ const name = url.hostname.replace(/^\[/, '').replace(/\]$/, '')
79
+ return name === '127.0.0.1' || name === 'localhost' || name === '::1'
80
+ } catch {
81
+ return false
82
+ }
83
+ }
84
+
85
+ function json(res, status, payload) {
86
+ const body = `${JSON.stringify(payload)}\n`
87
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
88
+ res.end(body)
89
+ }
90
+
91
+ function fail(res, status, code, message) {
92
+ json(res, status, { ok: false, code, message })
93
+ }
94
+
95
+ function readBody(req) {
96
+ return new Promise((resolve, reject) => {
97
+ const chunks = []
98
+ let size = 0
99
+ let settled = false
100
+ const settle = (fn, value) => { if (!settled) { settled = true; fn(value) } }
101
+ req.on('data', (chunk) => {
102
+ if (settled) return
103
+ size += chunk.length
104
+ if (size > RISD_MAX_BODY_BYTES) {
105
+ // Keep draining instead of destroying the socket here: destroying it made
106
+ // the client see "socket hang up" rather than the 413 the handler writes
107
+ // (review A-P2-6).
108
+ chunks.length = 0
109
+ settle(reject, Object.assign(new Error('body too large'), { code: 'too-large' }))
110
+ req.resume()
111
+ return
112
+ }
113
+ chunks.push(chunk)
114
+ })
115
+ req.on('end', () => settle(resolve, Buffer.concat(chunks).toString('utf8')))
116
+ req.on('error', (error) => settle(reject, error))
117
+ })
118
+ }
119
+
120
+ /**
121
+ * Raw bodies are only used by the bundle upload, which is a .tgz and therefore
122
+ * exceeds the JSON limit. The cap comes from the bundle module, so a body that
123
+ * could not possibly be a valid bundle is rejected before it is buffered whole.
124
+ */
125
+ function readBodyBytes(req, limit, timeoutMs = RISD_BODY_TIMEOUT_MS) {
126
+ return new Promise((resolve, reject) => {
127
+ const chunks = []
128
+ let size = 0
129
+ let settled = false
130
+ const timer = setTimeout(() => {
131
+ chunks.length = 0
132
+ settle(reject, Object.assign(new Error('body read timed out'), { code: 'timeout' }))
133
+ req.resume()
134
+ }, timeoutMs)
135
+ timer.unref?.()
136
+ const settle = (fn, value) => { if (!settled) { settled = true; clearTimeout(timer); fn(value) } }
137
+ req.on('data', (chunk) => {
138
+ if (settled) return
139
+ size += chunk.length
140
+ if (size > limit) {
141
+ chunks.length = 0
142
+ settle(reject, Object.assign(new Error('body too large'), { code: 'too-large' }))
143
+ req.resume()
144
+ return
145
+ }
146
+ chunks.push(chunk)
147
+ })
148
+ req.on('end', () => settle(resolve, Buffer.concat(chunks)))
149
+ req.on('error', (error) => settle(reject, error))
150
+ })
151
+ }
152
+
153
+ /**
154
+ * True when this Linux is WSL with Windows interop: the only case where a Windows
155
+ * bridge side exists (m12029). `/proc/sys/kernel/osrelease` carries "microsoft"
156
+ * under WSL2; a native kernel never does.
157
+ */
158
+ function isWslHost() {
159
+ if (process.platform !== 'linux') return false
160
+ try {
161
+ return readFileSync('/proc/sys/kernel/osrelease', 'utf8').toLowerCase().includes('microsoft')
162
+ } catch {
163
+ return false
164
+ }
165
+ }
166
+
167
+ /** One download at a time; the page polls GET /v1/proxybridge for the outcome. */
168
+ let bundleDownload = null
169
+ let bundleDownloadResult = null
170
+
171
+ /**
172
+ * The digest this machine expects the bundle to have. `''` means "do not verify,
173
+ * just record" (the module's own convention); the value can come from the env or
174
+ * the machine settings so an internal mirror can pin its own archive.
175
+ */
176
+ function bundleExpectedSha256(settings = readBundleSettings()) {
177
+ try {
178
+ if (typeof bundleApi.resolveBundleSha256 === 'function') {
179
+ return String(bundleApi.resolveBundleSha256({ env: process.env, settings }) ?? '')
180
+ }
181
+ } catch { /* fall through to the compiled-in digest */ }
182
+ return typeof bundleApi.BUNDLE_SHA256 === 'string' ? bundleApi.BUNDLE_SHA256 : ''
183
+ }
184
+
185
+ function proxyBridgeStatus() {
186
+ const dir = installDir(proxyHomeDir())
187
+ const installed = isInstalled(dir)
188
+ const manifest = installed ? readManifest(dir) : null
189
+ const settings = readBundleSettings()
190
+ // A bad override (typo'd settings.proxybridgeUrl) must not take the status route
191
+ // down with it: the safe resolver reports the error and falls back to the mirrors.
192
+ const resolved = typeof bundleApi.resolveBundleUrlsSafe === 'function'
193
+ ? bundleApi.resolveBundleUrlsSafe({ env: process.env, settings })
194
+ : { urls: resolveBundleUrls({ env: process.env, settings }), error: '' }
195
+ const urls = resolved.urls
196
+ const urlError = resolved.error === '' ? null : resolved.error
197
+ const sha256 = bundleExpectedSha256(settings)
198
+ const actual = manifest === null ? null : manifest.sha256 ?? null
199
+ return {
200
+ ok: true,
201
+ installed,
202
+ dir,
203
+ // Gitee first, GitHub second: both carry the release asset.
204
+ urls,
205
+ url: urls[0] ?? BUNDLE_URLS[0],
206
+ urlError,
207
+ // What an upload/download MUST hash to, and whether the installed copy does.
208
+ sha256,
209
+ actualSha256: actual,
210
+ verified: installed === true && (sha256 === '' || actual === sha256),
211
+ downloading: bundleDownload !== null,
212
+ result: bundleDownloadResult,
213
+ files: manifest === null ? [] : Object.keys(manifest.files),
214
+ installedAt: manifest === null ? null : manifest.installedAt,
215
+ }
216
+ }
217
+
218
+ /** `proxybridgeUrl` from the machine settings file, if a user set one. */
219
+ function readBundleSettings() {
220
+ try {
221
+ const path = join(proxyHomeDir(), 'settings.json')
222
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
223
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
224
+ } catch {
225
+ return {}
226
+ }
227
+ }
228
+
229
+ function startBundleDownload(force = false) {
230
+ if (bundleDownload !== null) return
231
+ const settings = readBundleSettings()
232
+ const expectedSha256 = bundleExpectedSha256(settings)
233
+ // `force` re-fetches even when a verified copy is cached; the maintenance page's
234
+ // 「重新下载」 button sends it (review C3-P2-6).
235
+ bundleDownload = ensureBundle({ home: proxyHomeDir(), settings, expectedSha256, force: force === true })
236
+ .then((result) => {
237
+ bundleDownloadResult = {
238
+ ok: result.ok,
239
+ code: result.ok === true ? null : result.code ?? 'install-failed',
240
+ fromCache: result.fromCache === true,
241
+ error: result.error ?? null,
242
+ expected: result.expected ?? expectedSha256,
243
+ actual: result.actual ?? null,
244
+ sha256: result.sha256 ?? null,
245
+ at: new Date().toISOString(),
246
+ }
247
+ return result
248
+ })
249
+ .catch((error) => {
250
+ bundleDownloadResult = {
251
+ ok: false,
252
+ code: error?.code ?? 'download-failed',
253
+ error: error instanceof Error ? error.message : String(error),
254
+ expected: error?.expected ?? expectedSha256,
255
+ actual: error?.actual ?? null,
256
+ at: new Date().toISOString(),
257
+ }
258
+ return null
259
+ })
260
+ .finally(() => { bundleDownload = null })
261
+ }
262
+
263
+ function parseJson(text) {
264
+ if (text.trim() === '') return {}
265
+ try {
266
+ const value = JSON.parse(text)
267
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined
268
+ } catch {
269
+ return undefined
270
+ }
271
+ }
272
+
273
+ function tokenMatches(expected, header) {
274
+ const prefix = 'bearer '
275
+ if (typeof header !== 'string' || !header.toLowerCase().startsWith(prefix)) return false
276
+ const given = header.slice(prefix.length).trim()
277
+ const a = Buffer.from(expected, 'utf8')
278
+ const b = Buffer.from(given, 'utf8')
279
+ return a.length === b.length && timingSafeEqual(a, b)
280
+ }
281
+
282
+ /**
283
+ * Absolute on this platform or on Windows. `path.isAbsolute` is platform-specific,
284
+ * so a POSIX daemon still has to recognise `C:\work` in a shared table; callers
285
+ * additionally require the directory to exist (review A-P1-3).
286
+ */
287
+ export function looksAbsolutePath(value) {
288
+ return typeof value === 'string' && value !== '' && (isAbsolute(value) || win32.isAbsolute(value))
289
+ }
290
+
291
+ function absoluteCwd(value) {
292
+ return looksAbsolutePath(value) ? value : null
293
+ }
294
+
295
+ /**
296
+ * Ask an existing daemon at `port` how it is doing. Used by the election path:
297
+ * EADDRINUSE alone cannot tell "same daemon" from "something else on 11082".
298
+ * @returns `{ ok, body }` or null.
299
+ */
300
+ export function probeRisdHealth(port, timeoutMs = START_PROBE_TIMEOUT_MS) {
301
+ return new Promise((resolve) => {
302
+ let settled = false
303
+ const finish = (value) => {
304
+ if (settled) return
305
+ settled = true
306
+ clearTimeout(timer)
307
+ resolve(value)
308
+ }
309
+ const call = request({ host: '127.0.0.1', port, path: '/v1/health', method: 'GET', timeout: timeoutMs }, (res) => {
310
+ const chunks = []
311
+ res.on('data', (chunk) => chunks.push(chunk))
312
+ res.on('end', () => {
313
+ try {
314
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
315
+ finish({ ok: res.statusCode === 200 && body?.ok === true, body })
316
+ } catch {
317
+ finish(null)
318
+ }
319
+ })
320
+ })
321
+ call.on('error', () => finish(null))
322
+ call.on('timeout', () => {
323
+ call.destroy()
324
+ finish(null)
325
+ })
326
+ const timer = setTimeout(() => {
327
+ call.destroy()
328
+ finish(null)
329
+ }, timeoutMs)
330
+ timer.unref?.()
331
+ call.end()
332
+ })
333
+ }
334
+
335
+ // A restart is requested at most once per process (m11421): a second POST while
336
+ // the first successor is being spawned must not start another daemon.
337
+ let restarting = false
338
+
339
+ /** The CLI entry of this package: `bin/risd.mjs` (server.js lives in lib/risd/). */
340
+ const RISD_CLI_PATH = fileURLToPath(new URL('../../bin/risd.mjs', import.meta.url))
341
+
342
+ /**
343
+ * Linux process start time — field 22 of `/proc/<pid>/stat`, an opaque tick count.
344
+ *
345
+ * A pid alone is not an identity: after a restart the OS may hand the same number
346
+ * to an unrelated process, and `kill(pid, 0)` would then wait on the wrong one
347
+ * (review A4-P2-5). The start time is the cheap identity check the kernel offers.
348
+ *
349
+ * @param {number|string} pid - process id to inspect.
350
+ * @returns {string} decimal ticks, or '' when `/proc` is unavailable (non-Linux).
351
+ */
352
+ export function readStartTime(pid) {
353
+ try {
354
+ const stat = readFileSync(`/proc/${Number(pid)}/stat`, 'utf8')
355
+ // `comm` is in parentheses and may itself contain spaces/parentheses.
356
+ const close = stat.lastIndexOf(')')
357
+ if (close < 0) return ''
358
+ const token = stat.slice(close + 2).split(' ')[19]
359
+ return typeof token === 'string' && /^\d+$/.test(token) ? token : ''
360
+ } catch {
361
+ return ''
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Resolve once `pid` is gone, or once its start time proves the pid was reused.
367
+ *
368
+ * Never throws: a successor must not die because the predecessor's pid file or
369
+ * `/proc` vanished mid-wait. `timedOut` tells the caller whether the deadline (not
370
+ * the exit) ended the wait so it can log that the handover raced the shutdown.
371
+ *
372
+ * @param {number} pid - predecessor pid.
373
+ * @param {number} timeoutMs - upper bound on the wait.
374
+ * @param {string} [expectedStartTime] - predecessor start time; '' = no identity check.
375
+ * @returns {Promise<{ok: boolean, timedOut: boolean}>} outcome, never a rejection.
376
+ */
377
+ export function waitForPidExit(pid, timeoutMs, expectedStartTime = '') {
378
+ const expected = typeof expectedStartTime === 'string' ? expectedStartTime : ''
379
+ const deadline = Date.now() + timeoutMs
380
+ return new Promise((resolve) => {
381
+ const tick = () => {
382
+ let alive = true
383
+ try { process.kill(pid, 0) } catch (error) { alive = error.code === 'EPERM' }
384
+ // A live pid with a different start time is somebody else: the process we
385
+ // care about has exited (review A4-P2-5).
386
+ if (alive === true && expected !== '') {
387
+ const current = readStartTime(pid)
388
+ if (current !== '' && current !== expected) alive = false
389
+ }
390
+ if (alive !== true) { resolve({ ok: true, timedOut: false }); return }
391
+ if (Date.now() > deadline) { resolve({ ok: false, timedOut: true }); return }
392
+ setTimeout(tick, 100)
393
+ }
394
+ tick()
395
+ })
396
+ }
397
+
398
+ /**
399
+ * Arguments for the successor CLI spawned by `POST /v1/restart`.
400
+ *
401
+ * Exported for the restart test: a successor without `--port` would bind the
402
+ * default port even when this daemon was started elsewhere, and the page polls
403
+ * the original origin forever (review A4-P2-6). `--wait-start` carries this
404
+ * process's identity so the successor does not wait on a reused pid (A4-P2-5).
405
+ *
406
+ * @param {{pid?: number, port?: number, startTime?: string}} [options] - predecessor identity.
407
+ * @returns {string[]} argv tail (`bin/risd.mjs serve …`).
408
+ */
409
+ export function successorArgs({ pid = process.pid, port = 0, startTime = '' } = {}) {
410
+ const args = [RISD_CLI_PATH, 'serve', '--wait-pid', String(pid)]
411
+ // The actual bound port, not the requested one: `--port 0` asks the OS to pick.
412
+ if (Number.isInteger(port) && port > 0) args.push('--port', String(port))
413
+ if (typeof startTime === 'string' && /^\d+$/.test(startTime)) args.push('--wait-start', startTime)
414
+ return args
415
+ }
416
+
417
+ /**
418
+ * Spawn the successor that takes over after this process exits. Detached+unref'd
419
+ * so it outlives the HTTP server, and `--wait-pid` keeps it from racing us for the
420
+ * port.
421
+ *
422
+ * `restarting` is reset when the spawn itself fails or the child dies before it
423
+ * takes over (review A4-P2-7): otherwise every later POST would answer 200 and do
424
+ * nothing, and the only symptom would be the page's 30 s timeout.
425
+ *
426
+ * @param {number} [port] - port this daemon actually bound (A4-P2-6).
427
+ * @returns {import('node:child_process').ChildProcess|null} the child, or null.
428
+ */
429
+ /** Test hook (see `__test`): how the successor is spawned. */
430
+ const restartHooks = { spawn }
431
+
432
+ function spawnRestartSuccessor(port = 0) {
433
+ let child = null
434
+ try {
435
+ child = restartHooks.spawn(process.execPath, successorArgs({ pid: process.pid, port, startTime: readStartTime(process.pid) }), {
436
+ detached: true,
437
+ stdio: 'ignore',
438
+ env: process.env,
439
+ cwd: process.cwd(),
440
+ })
441
+ child.unref()
442
+ } catch (error) {
443
+ restarting = false
444
+ try { process.stderr.write(`[dsh-ris-ide] 重启失败:无法启动后继进程(${error?.message ?? error})\n`) } catch { /* ignore */ }
445
+ return null
446
+ }
447
+ child.once('error', (error) => {
448
+ restarting = false
449
+ try { process.stderr.write(`[dsh-ris-ide] 重启失败:后继进程出错(${error?.message ?? error})\n`) } catch { /* ignore */ }
450
+ })
451
+ child.once('exit', (code, signal) => {
452
+ restarting = false
453
+ if (signal === null && code !== 0) {
454
+ try { process.stderr.write(`[dsh-ris-ide] 重启后继进程提前退出(code ${code});请手动重启或重试\n`) } catch { /* ignore */ }
455
+ }
456
+ })
457
+ return child
458
+ }
459
+
460
+ /**
461
+ * Test seams for the restart path (same idea as redirector's `probeHooks`): the
462
+ * route itself cannot be exercised without spawning a real successor, so the spawn
463
+ * and the `restarting` flag are exposed here and never touched by production code.
464
+ */
465
+ export const __test = {
466
+ restartHooks,
467
+ setRestarting(value) { restarting = value === true },
468
+ isRestarting() { return restarting === true },
469
+ spawnRestartSuccessor,
470
+ }
471
+
472
+ /**
473
+ * Start the daemon.
474
+ *
475
+ * Never throws for the three expected outcomes of a race — the caller maps them
476
+ * to exit codes: `already-running` (0), `api-mismatch` (3), `port-busy` (4).
477
+ *
478
+ * @param options - `{ home, port, version, onShutdown }`.
479
+ * @returns `{ ok, code?, server?, port?, state?, stop? }`.
480
+ */
481
+ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0.0', onShutdown = null, teardownTimeoutMs = 5000, teardown = null } = {}) {
482
+ // A predecessor may have shut down handing the network over (Phase 1b P6). Read
483
+ // its note before this daemon writes its own state file on top of it.
484
+ const previousState = readRisdState(home)
485
+ // Session policy: when the last lease disappears the network has no consumer, so
486
+ // the owner (this daemon) tears it down — in the documented order git → bridge →
487
+ // engine. Phase 1b P2 only owns the engine; git/bridge teardown lands with their
488
+ // ownership (P5), and until then those steps are the plugin's.
489
+ const TEARDOWN_DELAY_MS = 300
490
+ let teardownTimer = null
491
+ /**
492
+ * Take the network down in the documented order: git entry → system-level
493
+ * bridge → engine. Each step is best-effort and idempotent; the point is that a
494
+ * half step never leaves a client pointing at a listener that is already gone.
495
+ */
496
+ async function teardownNetwork(cwd) {
497
+ try { await clearGitProxy() } catch { /* best effort */ }
498
+ // Only a bridge this proxy home recorded is ours to stop. Without a pid file the
499
+ // probe spawns PowerShell (seconds on WSL) and delays `risd stop` for an
500
+ // interception that cannot exist here (fixture daemons, plugin-only runs).
501
+ if (hasBridgePidFiles() === true) {
502
+ try { await serializeBridge(() => stopRedirector()) } catch { /* best effort */ }
503
+ // Nothing is intercepting anymore: drop the last start report so the card does
504
+ // not show a component that is gone (review A4-P2-8).
505
+ lastBridgeStart = null
506
+ }
507
+ if (cwd !== null) {
508
+ try { await stopProxy(cwd) } catch { /* best effort */ }
509
+ }
510
+ }
511
+ function scheduleTeardown() {
512
+ if (leases.count() > 0) return
513
+ if (engineCwd === null && heartbeat === null) return
514
+ if (teardownTimer !== null) return
515
+ teardownTimer = setTimeout(() => {
516
+ teardownTimer = null
517
+ void (async () => {
518
+ if (leases.count() > 0) return // someone came back
519
+ // Per-resource policy: "follow dsh" stops it with the last window; the
520
+ // daemon-owned ones stay until the daemon itself stops (or forever).
521
+ if (lifecycle.debug.followDsh === true) await debug.stopAll().catch(() => {})
522
+ if (lifecycle.programs.followDsh === true) await stopAllPrograms()
523
+ const cwd = engineCwd
524
+ if (lifecycle.proxy.followDsh === true) {
525
+ await teardownNetwork(cwd)
526
+ if (engineCwd === cwd) engineCwd = null
527
+ }
528
+ // Idle exit (not an immediate one): a window may release its lease and
529
+ // re-take it a moment later; the daemon only retires after the configured
530
+ // idle window with nothing left to serve.
531
+ if (leases.count() === 0 && engineCwd === null) scheduleIdleExit()
532
+ })()
533
+ }, TEARDOWN_DELAY_MS)
534
+ teardownTimer.unref?.()
535
+ }
536
+ const leases = createLeaseRegistry({ onGone: () => scheduleTeardown() })
537
+ // JDWP sessions live here too (Phase 2-lite P3): a single socket to one JVM, so a
538
+ // dsh restart must not drop it and a second window must not attach over it.
539
+ const debug = createDebugEngine({ home })
540
+ // Workspaces the daemon has served at least one request for. The own page has no
541
+ // dsh session to ask, so it offers these as shortcuts (in memory: a restart
542
+ // simply starts the list over).
543
+ const workspaces = new Set()
544
+ /** Remember one workspace for the maintenance page (cap keeps the page honest). */
545
+ function rememberWorkspace(cwd) {
546
+ if (typeof cwd !== 'string' || !cwd.startsWith('/')) return
547
+ if (workspaces.has(cwd)) return
548
+ workspaces.add(cwd)
549
+ while (workspaces.size > 8) workspaces.delete(workspaces.values().next().value)
550
+ }
551
+ // One debug action at a time: attach/detach and stepping share the JDWP socket.
552
+ let debugOp = Promise.resolve()
553
+ /** Queue a debug action behind the previous one (order matters for stepping). */
554
+ function serializeDebug(task) {
555
+ const run = debugOp.then(task, task)
556
+ debugOp = run.then(() => undefined, () => undefined)
557
+ return run
558
+ }
559
+ const IDLE_EXIT_MS = 10 * 60 * 1000
560
+ // Which resources follow a dsh session, and which follow this daemon. Read at
561
+ // start, updated by POST /v1/config; the rules below are the only readers.
562
+ const lifecycleRead = readLifecycle(home)
563
+ let lifecycle = lifecycleRead.value
564
+ // A lifecycle file the daemon could not parse is not fatal: defaults run, and
565
+ // GET /v1/config reports the parse errors (read fresh on every GET so a hand
566
+ // edit shows up without a restart).
567
+ let idleTimer = null
568
+ function cancelIdleExit() {
569
+ if (idleTimer === null) return
570
+ clearTimeout(idleTimer)
571
+ idleTimer = null
572
+ }
573
+ function scheduleIdleExit() {
574
+ // "daemon follows dsh = false" means: stay up until someone stops me.
575
+ if (lifecycle.daemon.followDsh !== true) return
576
+ if (idleTimer !== null) return
577
+ idleTimer = setTimeout(() => {
578
+ idleTimer = null
579
+ // A daemon opened from the maintenance page has no lease at all, yet may be
580
+ // supervising programs or a debug session: idling out would kill them.
581
+ void hasActiveWork().then((active) => {
582
+ // An owned engine means the network is a service (proxy.followDsh=false) or
583
+ // somebody is using it without a lease: retiring would tear it down, which
584
+ // is exactly what "follow daemon" promised not to do (review A2-P2-3).
585
+ if (!active && engineCwd === null) return stop()
586
+ scheduleIdleExit()
587
+ return undefined
588
+ })
589
+ }, IDLE_EXIT_MS)
590
+ idleTimer.unref?.()
591
+ }
592
+
593
+ /** Anything a "stop the daemon" would have to kill: running programs or JDWP. */
594
+ async function hasActiveWork() {
595
+ if (debug.size > 0) return true
596
+ for (const cwd of workspaces) {
597
+ if (!existsSync(cwd)) continue
598
+ try {
599
+ const listed = await listPrograms(cwd, {})
600
+ if (listed.programs.some((row) => row.running !== null && row.running !== undefined && row.running.alive === true)) return true
601
+ } catch { /* an unreadable workspace cannot be running anything we know */ }
602
+ }
603
+ return false
604
+ }
605
+
606
+ /**
607
+ * Stop every program this daemon supervises (the ones with a live `<log>.pid`).
608
+ * Called only for a real shutdown, never for a handoff: a successor keeps them.
609
+ */
610
+ async function stopAllPrograms() {
611
+ const cwds = new Set(workspaces)
612
+ if (typeof engineCwd === 'string' && engineCwd !== '') cwds.add(engineCwd)
613
+ for (const cwd of cwds) {
614
+ if (!existsSync(cwd)) continue
615
+ try {
616
+ const listed = await listPrograms(cwd, {})
617
+ for (const row of listed.programs) {
618
+ if (row.running === null || row.running === undefined || row.running.alive !== true) continue
619
+ try { await stopProgramByKey(cwd, row.id, { dir: listed.dir }) } catch { /* keep going: one stuck program must not block the rest */ }
620
+ }
621
+ } catch { /* the workspace may have vanished */ }
622
+ }
623
+ }
624
+ const startedAt = new Date().toISOString()
625
+ // The daemon code the page will render: captured NOW, because Node caches the
626
+ // module graph for the life of the process (see build.js).
627
+ const uiBuildLoaded = buildStamp()
628
+ const token = newRisdToken()
629
+ // The workspace the engine was last started for. Kept in memory on purpose: it
630
+ // is ownership evidence for this daemon instance, not durable configuration
631
+ // (a restart re-discovers the engine by pidfile and reports owned:false until
632
+ // someone starts/stops it again).
633
+ let engineCwd = null
634
+ // Last background enforcement reload (POST /v1/proxy hands the slow part off, so a
635
+ // save returns in milliseconds instead of waiting ~8s for two PowerShell probes).
636
+ let bridgeReloadState = { at: 0, ok: true, note: '' }
637
+ // The daemon is the heartbeat writer once it owns the bridge: the elevated
638
+ // watchdog tears the bridge down when the file is older than 20 s, and a plugin
639
+ // that is closing (Ctrl+C) must no longer be the one keeping it alive.
640
+ let heartbeat = null
641
+ // Engine operations are serialized: two windows pressing 启动 must not race the
642
+ // pidfile (startProxy is idempotent, but stop-after-start must stay ordered).
643
+ let engineOp = Promise.resolve()
644
+ /**
645
+ * Queue one engine operation behind the previous one. A rejected task must not
646
+ * poison the chain: without `then(task, task)` one start failure turned every
647
+ * later engine control into an immediate 500 (review A-P1-1).
648
+ * @param {Function} task - async work.
649
+ * @returns {Promise<any>} the task's own result.
650
+ */
651
+ function serializeEngine(task) {
652
+ const run = engineOp.then(task, task)
653
+ engineOp = run.then(() => undefined, () => undefined)
654
+ return run
655
+ }
656
+ // Program start/stop share one queue so two clicks cannot spawn the same row twice.
657
+ let programOp = Promise.resolve()
658
+ // Bridge (ProxyBridge) operations are serialized too (E8): a rule reload and a
659
+ // stop are two single-file handshakes with the elevated watchdog, and running
660
+ // them concurrently can reload a profile the other side is already tearing down.
661
+ let bridgeOp = Promise.resolve()
662
+ /**
663
+ * Queue one bridge operation behind the previous one.
664
+ * @param {Function} task - async work; may throw, the queue keeps going.
665
+ * @returns {Promise<any>} the task's own result.
666
+ */
667
+ function serializeBridge(task) {
668
+ const run = bridgeOp.then(task, task)
669
+ bridgeOp = run.then(() => undefined, () => undefined)
670
+ return run
671
+ }
672
+
673
+ const handler = async (req, res) => {
674
+ try {
675
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
676
+ const path = url.pathname
677
+ const method = req.method ?? 'GET'
678
+
679
+ // Machine-local API: no CORS support at all. Refuse a request addressed to
680
+ // another host name (DNS rebinding) and one carrying a foreign Origin (a web
681
+ // page probing localhost). Without this, a rebound page could read the token
682
+ // from /ui and drive the daemon (review A-P1-4).
683
+ if (!isLoopbackHost(req)) return fail(res, 403, 'forbidden', 'this API answers loopback requests only')
684
+ if (typeof req.headers.origin === 'string' && req.headers.origin !== '' && !isLoopbackOrigin(req.headers.origin)) {
685
+ return fail(res, 403, 'forbidden', 'cross-origin requests are not allowed')
686
+ }
687
+
688
+ if (path === '/v1/health') {
689
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET only')
690
+ return json(res, 200, {
691
+ ok: true,
692
+ apiVersion: RISD_API_VERSION,
693
+ version,
694
+ pid: process.pid,
695
+ startedAt,
696
+ // Identifies THIS daemon process to a page that embedded the value at
697
+ // /ui load time. A restart (new process, new token) always changes it, so
698
+ // the page can reload itself instead of answering 401 forever (review A3-P1-1).
699
+ instance: startedAt,
700
+ uptimeMs: Date.now() - Date.parse(startedAt),
701
+ state: 'ready',
702
+ side: process.platform,
703
+ port: server.address()?.port ?? port,
704
+ home,
705
+ leases: { count: leases.count() },
706
+ engine: engineSummary(),
707
+ ui: '/ui',
708
+ // `loaded` names the code this process runs, `disk` the code a restart
709
+ // would load; the page reloads itself when they diverge in the first way
710
+ // and nudges for a restart in the second (review m09693).
711
+ uiBuild: { loaded: uiBuildLoaded, disk: buildStamp() },
712
+ heartbeat: heartbeat !== null,
713
+ janitor: { armed: janitorStatus().running === true, ownerPid: process.pid },
714
+ })
715
+ }
716
+
717
+ if ((path === '/ui' || path === '/ui/') && method === 'GET') {
718
+ // The only unauthenticated page: served to a local browser only, with the
719
+ // token inlined. Anything able to load it can read risd.json anyway.
720
+ if (!isLoopbackHost(req)) return fail(res, 403, 'forbidden', 'this page answers loopback requests only')
721
+ const html = risdUiHtml({ token, version, home, apiVersion: RISD_API_VERSION, uiBuild: { loaded: uiBuildLoaded }, uiInstance: startedAt })
722
+ res.writeHead(200, {
723
+ 'content-type': 'text/html; charset=utf-8',
724
+ 'cache-control': 'no-store',
725
+ 'content-length': Buffer.byteLength(html),
726
+ // Loopback page holding the daemon token: never frame it, never let it
727
+ // load anything but loopback (the IDE tab embeds dsh) (review C-P2-5).
728
+ 'x-frame-options': 'DENY',
729
+ 'x-content-type-options': 'nosniff',
730
+ // The IDE tab embeds the dsh host in a frame; without this the frame's
731
+ // navigator.clipboard.writeText is rejected by permissions policy and a
732
+ // 「复制文件路径」 would surface as a background-task error (m09396 ③).
733
+ 'permissions-policy': 'clipboard-write=*, clipboard-read=*',
734
+ 'referrer-policy': 'no-referrer',
735
+ 'content-security-policy': [
736
+ "default-src 'none'",
737
+ "script-src 'unsafe-inline'",
738
+ "style-src 'unsafe-inline'",
739
+ 'img-src data:',
740
+ 'connect-src http://127.0.0.1:* http://localhost:*',
741
+ 'frame-src http://127.0.0.1:* http://localhost:*',
742
+ "base-uri 'none'",
743
+ "form-action 'none'",
744
+ "frame-ancestors 'none'",
745
+ ].join('; '),
746
+ })
747
+ res.end(html)
748
+ return undefined
749
+ }
750
+
751
+ if (!tokenMatches(token, req.headers.authorization)) {
752
+ return fail(res, 401, 'unauthorized', 'missing or invalid bearer token (read risd.json)')
753
+ }
754
+ if (String(req.headers[API_VERSION_HEADER] ?? '') !== String(RISD_API_VERSION)) {
755
+ return fail(res, 409, 'api-mismatch', `client speaks apiVersion ${req.headers[API_VERSION_HEADER] ?? 'none'}, daemon speaks ${RISD_API_VERSION}`)
756
+ }
757
+
758
+ if (path === '/v1/workspaces' && method === 'GET') {
759
+ return json(res, 200, { ok: true, workspaces: [...workspaces] })
760
+ }
761
+
762
+ if (path === '/v1/dsh' && method === 'GET') {
763
+ // Which workspaces have a live dsh window? The plugin keeps dsh-window.json
764
+ // as an upserted list (origin + sessionId per workspace), so one daemon page
765
+ // can switch between workspaces' IDE instead of opening one page per cwd.
766
+ let windows = []
767
+ try {
768
+ const parsed = JSON.parse(readFileSync(join(home, DSH_WINDOW_FILENAME), 'utf8'))
769
+ if (Array.isArray(parsed?.windows)) windows = parsed.windows
770
+ } catch { /* absent or rotated away: no dsh */ }
771
+ const now = Date.now()
772
+ let droppedAt = 0
773
+ const live = windows
774
+ .filter((row) => row !== null && typeof row === 'object' && typeof row.url === 'string' && row.url !== '')
775
+ // The page hands this URL to window.open(); anything but a loopback
776
+ // http(s) origin would let a crafted dsh-window.json point the IDE tab
777
+ // somewhere else (review A-P2-10).
778
+ .filter((row) => /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|$)/i.test(row.url))
779
+ .map((row) => {
780
+ const at = Date.parse(String(row.at ?? ''))
781
+ // A timestamp far in the future made `now - at` clamp to 0, so the row
782
+ // stayed "live" for as long as the clock skew lasted (review A2-P2-15);
783
+ // non-finite rows were pruned before anyone could see them (A2-P2-16).
784
+ // Both are treated as junk rather than as fresh.
785
+ const future = Number.isFinite(at) && at > now + 5 * 60_000
786
+ // A numeric `at` (epoch ms is not what the writer stores) and a missing
787
+ // or unparsable one are all junk for the same reason: they cannot be
788
+ // ordered against now. Count them so a caller can tell "no dsh" from
789
+ // "dsh wrote something unusable" (review A3-P2-6).
790
+ if (!Number.isFinite(at) || future) droppedAt += 1
791
+ return {
792
+ cwd: typeof row.cwd === 'string' ? row.cwd : '',
793
+ sessionId: typeof row.sessionId === 'string' ? row.sessionId : '',
794
+ url: row.url,
795
+ ageMs: Number.isFinite(at) && !future ? Math.max(0, now - at) : DSH_WINDOW_RETAIN_MS + 1,
796
+ }
797
+ })
798
+ .map((row) => Object.assign(row, { live: row.ageMs <= DSH_WINDOW_LIVE_MS }))
799
+ .filter((row) => row.ageMs <= DSH_WINDOW_RETAIN_MS)
800
+ // Live entries first, then most-recently-seen: the first row is the one an
801
+ // iframe deep link opens by default.
802
+ .sort((a, b) => (a.live === b.live ? a.ageMs - b.ageMs : a.live ? -1 : 1))
803
+ if (live.length === 0) {
804
+ return json(res, 200, { ok: true, available: false, windows: [], dropped: droppedAt, reason: 'dsh 未运行(没有记住的工作区窗口)' })
805
+ }
806
+ const newest = live[0]
807
+ return json(res, 200, {
808
+ ok: true,
809
+ available: true,
810
+ url: newest.url,
811
+ sessionId: newest.sessionId,
812
+ cwd: newest.cwd,
813
+ windows: live,
814
+ dropped: droppedAt,
815
+ })
816
+ }
817
+
818
+ if (path === '/v1/proxy/ping' && method === 'GET') {
819
+ // Reachability of the configured SOCKS upstream, for the status chip on the
820
+ // proxy tab. Query overrides let the page test an edited-but-unsaved value.
821
+ const stored = readProxyConfig(url.searchParams.get('cwd') ?? home).socks
822
+ const host = url.searchParams.get('host') ?? stored.host
823
+ const rawPort = url.searchParams.get('port')
824
+ const port = rawPort === null ? stored.port : Number(rawPort)
825
+ const result = await pingSocks({ host, port })
826
+ return json(res, 200, result)
827
+ }
828
+
829
+ if (path === '/v1/proxybridge' && method === 'GET') {
830
+ return json(res, 200, proxyBridgeStatus())
831
+ }
832
+
833
+ if (path === '/v1/proxybridge/health' && method === 'GET') {
834
+ const summary = engineSummary()
835
+ // Only a *known* stopped engine may skip the component check. `unknown` means
836
+ // the pidfile could not be read — not that nothing is running (review A4-P2-9).
837
+ const engineStopped = summary.state === 'stopped'
838
+ const engineRunning = summary.state === 'running'
839
+ const bridge = await redirectorStatusAsync()
840
+ const interception = { linux: bridge.runningLocal === true, windows: bridge.runningWindows === true }
841
+ // m11863: engine stopped + interception running is a misconfiguration, not a
842
+ // health result — nothing would answer the redirected connections.
843
+ const stray = { linux: engineStopped === true && interception.linux, windows: engineStopped === true && interception.windows }
844
+ if (engineStopped === true) {
845
+ // m11838: a stopped engine means nobody is using the component, so probing
846
+ // binaries (and spawning PowerShell) would only produce red noise. This
847
+ // route stays read-only: starting/stopping the component is the reconciler's
848
+ // single decision (review A4-P2-7), so a health poll cannot race a teardown
849
+ // or spin an elevation prompt of its own.
850
+ return json(res, 200, { ok: null, checked: false, engineRunning: false, engineState: summary.state, interception, elevations: elevationState(), stray, lastStart: lastBridgeStart, commands: bridgeCommands(), degrade: bridgeDegrade(), at: new Date().toISOString() })
851
+ }
852
+ // Probe the copy Windows actually runs (%LOCALAPPDATA%), not the Linux cache:
853
+ // Windows cannot launch an exe from the Linux filesystem (m11828).
854
+ let windowsExe = ''
855
+ let windowsApplicable = false
856
+ let windowsPrepared = false
857
+ try {
858
+ if (process.platform === 'win32') {
859
+ // Native Windows runs the bundle in place (review A4-P1-1): there is no
860
+ // Linux cache to copy from and no materialisation step at all.
861
+ const exe = join(bundleApi.installDir(home), 'windows', 'ProxyBridge_CLI.exe')
862
+ windowsApplicable = true
863
+ windowsPrepared = existsSync(exe)
864
+ if (windowsPrepared === true) windowsExe = exe
865
+ } else if (isWslHost() === true) {
866
+ // WSL is the only non-Windows host that can run the Windows bridge; the
867
+ // copy Windows actually executes lives under %LOCALAPPDATA% (m11828).
868
+ const dir = windowsBundleDir()
869
+ if (typeof dir === 'string' && dir !== '') {
870
+ windowsApplicable = true
871
+ windowsPrepared = existsSync(join(dir, 'ProxyBridge_CLI.exe'))
872
+ if (windowsPrepared === true) windowsExe = posixToWindowsPath(join(dir, 'ProxyBridge_CLI.exe'))
873
+ }
874
+ }
875
+ } catch { /* the card then says "本机没有 Windows 侧" instead of a wrong failure */ }
876
+ const health = await bridgeHealth.get({
877
+ home,
878
+ // `unknown` is not "not running": only claim an engine state we know
879
+ // (review A4-P2-9).
880
+ engineRunning: engineRunning === true,
881
+ force: url.searchParams.get('force') === '1',
882
+ windowsExe,
883
+ windowsApplicable,
884
+ windowsPrepared,
885
+ linuxApplicable: process.platform !== 'win32',
886
+ })
887
+ return json(res, 200, Object.assign({}, health, { engineState: summary.state, interception, elevations: elevationState(), stray, lastStart: lastBridgeStart, commands: bridgeCommands(), degrade: bridgeDegrade() }))
888
+ }
889
+
890
+ if (path === '/v1/proxybridge/download' && method === 'POST') {
891
+ // Fetching/installing the component is user-visible work: keep the daemon
892
+ // from idling out from under the page while it runs (review A3-P2-3).
893
+ cancelIdleExit()
894
+ // The archive is ~1 MB and installs atomically; answering immediately and
895
+ // letting the page poll keeps a slow mirror from holding the request open.
896
+ // A body is optional here: `{force:true}` re-fetches even when the cached
897
+ // copy still verifies, which is what 「重新下载」 needs.
898
+ const forceBody = await readBody(req).catch(() => '')
899
+ let force = false
900
+ if (typeof forceBody === 'string' && forceBody.trim() !== '') {
901
+ try {
902
+ const parsed = JSON.parse(forceBody)
903
+ force = parsed !== null && typeof parsed === 'object' && parsed.force === true
904
+ } catch { force = false }
905
+ }
906
+ startBundleDownload(force)
907
+ return json(res, 200, proxyBridgeStatus())
908
+ }
909
+
910
+ if (path === '/v1/proxybridge/upload' && method === 'POST') {
911
+ cancelIdleExit()
912
+ let bytes
913
+ try {
914
+ bytes = await readBodyBytes(req, MAX_TGZ_BYTES)
915
+ } catch (error) {
916
+ if (error !== null && typeof error === 'object' && error.code === 'too-large') {
917
+ return fail(res, 413, 'too-large', `压缩包超过 ${MAX_TGZ_BYTES} 字节上限`)
918
+ }
919
+ if (error !== null && typeof error === 'object' && error.code === 'timeout') {
920
+ return fail(res, 408, 'timeout', '上传超时:15 秒内没有收完压缩包')
921
+ }
922
+ return fail(res, 400, 'bad-request', error instanceof Error ? error.message : String(error))
923
+ }
924
+ const settings = readBundleSettings()
925
+ const expectedSha256 = bundleExpectedSha256(settings)
926
+ let result
927
+ try {
928
+ result = installFromTgz({ home: proxyHomeDir(), bytes, expectedSha256 })
929
+ } catch (error) {
930
+ // A digest mismatch is a different repair instruction than a malformed
931
+ // archive: the caller must see which digest was expected (review A3-P2-7).
932
+ if (error !== null && typeof error === 'object' && error.code === 'hash-mismatch') {
933
+ return json(res, 400, {
934
+ ok: false,
935
+ code: 'hash-mismatch',
936
+ message: error instanceof Error ? error.message : String(error),
937
+ expected: error.expected ?? expectedSha256,
938
+ actual: error.actual ?? null,
939
+ })
940
+ }
941
+ return json(res, 400, { ok: false, code: 'bad-bundle', message: error instanceof Error ? error.message : String(error), hint: '需要一个包含 8 个 ProxyBridge 文件的 .tgz' })
942
+ }
943
+ if (result.ok !== true) {
944
+ return json(res, 400, {
945
+ ok: false,
946
+ code: result.code ?? 'bad-bundle',
947
+ message: result.error,
948
+ hint: result.hint,
949
+ expected: result.expected ?? expectedSha256,
950
+ actual: result.actual ?? null,
951
+ })
952
+ }
953
+ const uploadedFiles = Array.isArray(result.files) ? result.files : []
954
+ return json(res, 200, {
955
+ ok: true,
956
+ installed: true,
957
+ dir: result.dir,
958
+ files: uploadedFiles,
959
+ fileCount: uploadedFiles.length,
960
+ sha256: result.sha256 ?? null,
961
+ expectedSha256,
962
+ verified: expectedSha256 === '' || result.sha256 === expectedSha256,
963
+ })
964
+ }
965
+
966
+ if (path === '/v1/proxy/log' && method === 'GET') {
967
+ const bytes = Math.min(Math.max(Number(url.searchParams.get('bytes') ?? 40960) || 40960, 1024), 256 * 1024)
968
+ const logPath = proxyLogPath()
969
+ return json(res, 200, { ok: true, path: logPath, text: readTail(logPath, bytes) })
970
+ }
971
+
972
+ if (path === '/v1/debug' && method === 'POST') {
973
+ const parsed = parseJson(await readBody(req))
974
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
975
+ const action = String(parsed.action ?? '')
976
+ const needsCwd = action !== 'sessions' && action !== 'detach' && action !== 'events'
977
+ if (needsCwd) {
978
+ const cwd = absoluteCwd(parsed.cwd)
979
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
980
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
981
+ rememberWorkspace(cwd)
982
+ parsed.cwd = cwd
983
+ }
984
+ if (action === 'start') cancelIdleExit()
985
+ const result = await serializeDebug(() => debug.run(parsed))
986
+ return json(res, 200, Object.assign({ ok: true }, result))
987
+ }
988
+
989
+ if (path === '/v1/proxy' && method === 'POST') {
990
+ // The write half moved here in Phase 1b P4: the daemon is the only writer
991
+ // of the machine-wide table, so two windows (or a window and the CLI) can no
992
+ // longer interleave a read-modify-write and silently drop rows.
993
+ const parsed = parseJson(await readBody(req))
994
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
995
+ const cwd = parsed.cwd === undefined || parsed.cwd === null ? home : absoluteCwd(parsed.cwd)
996
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
997
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
998
+ const incoming = parsed.config !== null && typeof parsed.config === 'object' ? parsed.config : {}
999
+ const stored = readProxyConfig(cwd)
1000
+ const currentRevision = risdConfigRevision(stored)
1001
+ const baseRevision = typeof parsed.revision === 'string' ? parsed.revision.trim() : ''
1002
+ if (baseRevision !== '' && baseRevision !== currentRevision) {
1003
+ return json(res, 409, {
1004
+ ok: false,
1005
+ conflict: true,
1006
+ code: 'conflict',
1007
+ message: '规则表已在别处被修改,本次改动未写入',
1008
+ revision: currentRevision,
1009
+ // The design promises the losing writer a fresh view so a direct API
1010
+ // client can merge without a second round trip (review A-P2-1).
1011
+ view: await risdProxyView(cwd),
1012
+ })
1013
+ }
1014
+ const rows = Array.isArray(incoming.rules)
1015
+ ? incoming.rules
1016
+ .filter((rule) => rule !== null && typeof rule === 'object')
1017
+ .map((rule) => Object.assign({}, rule, { workspace: rule.workspace ?? cwd }))
1018
+ : []
1019
+ const keptIds = new Set(rows.map((rule) => String(rule.id ?? '')))
1020
+ // One machine-wide table, and this payload IS the table: a row the caller did
1021
+ // not send is gone (m10585). The old protocol let a client declare which
1022
+ // sources it spoke for, which kept rows alive that no UI could show — the
1023
+ // 「别的工作区还配着」 state the user asked us to drop. Callers that only own
1024
+ // a slice of the table (yds) therefore read first and PUT the complete set.
1025
+ //
1026
+ // `replaceRulesFrom` is kept as a one-release compatibility shim: an older
1027
+ // dsh-ris-yds sends only its own rows, and treating that as a complete table
1028
+ // would delete the user's rows. New callers omit it; the panel never sends it.
1029
+ let legacySource = null
1030
+ if (parsed.replaceRulesFrom !== undefined) {
1031
+ const sources = Array.isArray(parsed.replaceRulesFrom) ? parsed.replaceRulesFrom : []
1032
+ if (sources.length > 0 && sources.every((source) => source === 'yds')) legacySource = 'yds'
1033
+ }
1034
+ const retired = new Set(
1035
+ stored.rules
1036
+ .filter((rule) => {
1037
+ if (keptIds.has(String(rule.id ?? ''))) return false
1038
+ return legacySource === null ? true : rule.source === legacySource
1039
+ })
1040
+ .map((rule) => rule.id),
1041
+ )
1042
+ const written = mergeConfigs(
1043
+ Object.assign({}, stored, { rules: stored.rules.filter((rule) => !retired.has(rule.id)) }),
1044
+ { socks: incoming.socks, listenPort: incoming.listenPort, rules: rows, workspace: cwd },
1045
+ )
1046
+ writeProxyConfig(cwd, written)
1047
+ // Clean up what the OLD table applied before the new one takes effect. The
1048
+ // git entry is host-scoped and nothing else rewrites it on save, so a changed
1049
+ // or deleted git rule used to leave terminals pointed at a dead tunnel.
1050
+ const git = await serializeBridge(() => reconcileGitProxy({ cwd, host: typeof parsed.gitHost === 'string' ? parsed.gitHost : '' }))
1051
+ // Revoke the previous enforcement as part of the switch: ProxyBridge parses
1052
+ // its profile only at start, so a reload that fails would otherwise keep the
1053
+ // OLD rules intercepting while the dialog claims the save worked. The wait is
1054
+ // real (two synchronous PowerShell probes on WSL ≈ 8s), so the save returns
1055
+ // first and the switch runs right after it; the page reads the outcome from
1056
+ // `bridge` on its next load (m10585). Saves are serialized by serializeBridge,
1057
+ // and each reload re-reads the file, so a burst of edits still lands on the
1058
+ // last table.
1059
+ const revoke = async (reason) => {
1060
+ const stopped = await serializeBridge(() => stopRedirector())
1061
+ return `${reason};${stopped.stopped === true
1062
+ ? '已停止系统层拦截,避免继续按旧规则代理'
1063
+ : `未能停止系统层拦截(${stopped.reason ?? '未知原因'}),旧规则可能仍在生效`}`
1064
+ }
1065
+ const switchEnforcement = async () => {
1066
+ try {
1067
+ if (redirectorStatusCached().running !== true) {
1068
+ bridgeReloadState = { at: Date.now(), ok: true, note: '' }
1069
+ return
1070
+ }
1071
+ // On Windows only the `windows` side exists; asking for `local` produced a
1072
+ // permanent "skipped" note and a misleading sudo hint (review A2-P2-14).
1073
+ const reloadSides = process.platform === 'win32' ? ['windows'] : ['windows', 'local']
1074
+ const reload = await serializeBridge(() => reloadRedirectorsWithProfile(cwd, { sides: reloadSides }))
1075
+ const done = Array.isArray(reload.reloaded) ? reload.reloaded : []
1076
+ const skipped = Array.isArray(reload.skipped) ? reload.skipped : []
1077
+ if (done.length > 0) {
1078
+ bridgeReloadState = { at: Date.now(), ok: true, note: '系统层拦截已按新规则自动重启' }
1079
+ return
1080
+ }
1081
+ const note = await revoke(`系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`)
1082
+ bridgeReloadState = { at: Date.now(), ok: false, note }
1083
+ } catch (error) {
1084
+ const note = await revoke(`系统层拦截未重载:${error?.message ?? error}`)
1085
+ bridgeReloadState = { at: Date.now(), ok: false, note }
1086
+ }
1087
+ }
1088
+ setImmediate(() => { switchEnforcement().catch(() => {}) })
1089
+ return json(res, 200, {
1090
+ ok: true,
1091
+ revision: risdConfigRevision(written),
1092
+ reloadNote: '规则已保存;系统层拦截正在后台按新规则重启',
1093
+ git,
1094
+ })
1095
+ }
1096
+
1097
+ if (path === '/v1/action' && method === 'POST') {
1098
+ const parsed = parseJson(await readBody(req))
1099
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1100
+ const cwd = absoluteCwd(parsed.cwd)
1101
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1102
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1103
+ const action = typeof parsed.action === 'string' ? parsed.action : 'status'
1104
+ const gitHost = typeof parsed.gitHost === 'string' ? parsed.gitHost : undefined
1105
+ let result
1106
+ if (action === 'start') {
1107
+ result = await serializeEngine(async () => {
1108
+ const engine = await startProxy(cwd)
1109
+ const redirector = await serializeBridge(() => startRedirectors({ interactive: true }))
1110
+ noteBridgeStart(redirector)
1111
+ const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
1112
+ if (engine.ok === true) {
1113
+ engineCwd = cwd
1114
+ cancelIdleExit()
1115
+ }
1116
+ return Object.assign({}, engine, { redirector, git })
1117
+ })
1118
+ } else if (action === 'stop') {
1119
+ result = await serializeEngine(async () => {
1120
+ const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
1121
+ const redirector = await serializeBridge(() => stopRedirector())
1122
+ // The card must not keep describing a component we just stopped
1123
+ // (review A4-P2-8).
1124
+ lastBridgeStart = null
1125
+ const stopped = await stopProxy(cwd)
1126
+ if (stopped.ok === true) {
1127
+ engineCwd = null
1128
+ // Nothing holds the daemon open after an explicit 停止; without this
1129
+ // it stayed resident until the next lease event even though the page
1130
+ // was the only owner (review A3-P2-4).
1131
+ if (leases.count() === 0) scheduleIdleExit()
1132
+ }
1133
+ return Object.assign({}, stopped, { redirector, git })
1134
+ })
1135
+ } else if (action === 'status') {
1136
+ result = { engine: engineSummary(), redirector: redirectorStatusCached() }
1137
+ } else if (action === 'git-on' || action === 'git-off') {
1138
+ // The git table changes the machine config through exactly one helper,
1139
+ // syncGitProxy, which records key+value so cleanup only removes our own
1140
+ // entry. Direct runGitConfig calls here left no bookkeeping and could
1141
+ // unset a key the current table no longer calculates (review B-P2-5).
1142
+ result = await syncGitProxy({ cwd, host: gitHost, enabled: action === 'git-on' })
1143
+ } else if (action === 'redirector-sync' || action === 'redirector-start') {
1144
+ const { syncRedirector } = await import('../redirector.js')
1145
+ result = await serializeBridge(() => syncRedirector(cwd, { start: action === 'redirector-start' }))
1146
+ } else if (action === 'redirector-stop') {
1147
+ result = await serializeBridge(() => stopRedirector())
1148
+ lastBridgeStart = null
1149
+ } else if (action === 'redirector-restart') {
1150
+ // Stop first so nothing keeps intercepting with the parsed-at-start profile,
1151
+ // then start again from the profile written by the save that requested this.
1152
+ result = await serializeBridge(async () => {
1153
+ const stopped = await stopRedirector()
1154
+ await new Promise((resolve) => setTimeout(resolve, 300))
1155
+ const started = await startRedirectors({ interactive: true })
1156
+ noteBridgeStart(started)
1157
+ return {
1158
+ stopped,
1159
+ started: started.started ?? [],
1160
+ skipped: started.skipped ?? [],
1161
+ running: started.running === true,
1162
+ }
1163
+ })
1164
+ } else {
1165
+ return fail(res, 400, 'bad-request', `unknown proxy action "${action}"`)
1166
+ }
1167
+ return json(res, 200, { ok: true, action, result })
1168
+ }
1169
+
1170
+ if (path === '/v1/injection' && method === 'GET') {
1171
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
1172
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1173
+ const program = String(url.searchParams.get('program') ?? '')
1174
+ if (program === '') return fail(res, 400, 'bad-request', 'program is required')
1175
+ return json(res, 200, { ok: true, cwd, program, injection: injectionFor(program, readProxyConfig(cwd)) })
1176
+ }
1177
+
1178
+ if (path === '/v1/programs') {
1179
+ if (method === 'GET') {
1180
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
1181
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1182
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1183
+ rememberWorkspace(cwd)
1184
+ const dir = String(url.searchParams.get('dir') ?? '')
1185
+ const refreshRaw = url.searchParams.get('refresh')
1186
+ const refresh = refreshRaw === '1' || refreshRaw === 'true'
1187
+ const listed = await listPrograms(cwd, { dir, refresh })
1188
+ return json(res, 200, { ok: true, cwd, dir: listed.dir, programs: listed.programs })
1189
+ }
1190
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1191
+ const parsed = parseJson(await readBody(req))
1192
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1193
+ const cwd = absoluteCwd(parsed.cwd)
1194
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1195
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1196
+ // Every cwd a program is started in becomes a workspace this daemon
1197
+ // supervises: "stop the daemon" walks that set and stops those programs.
1198
+ rememberWorkspace(cwd)
1199
+ const action = parsed.action
1200
+ if (action !== 'start' && action !== 'stop' && action !== 'restart') {
1201
+ return fail(res, 400, 'bad-request', 'action must be start, stop or restart')
1202
+ }
1203
+ const key = String(parsed.id ?? parsed.program ?? '')
1204
+ if (key === '') return fail(res, 400, 'bad-request', 'id is required')
1205
+ if (action !== 'stop') cancelIdleExit()
1206
+ const dir = typeof parsed.dir === 'string' ? parsed.dir : ''
1207
+ let result
1208
+ try {
1209
+ result = await (programOp = programOp.then(
1210
+ async () => (action === 'start'
1211
+ ? startProgramByKey(cwd, key, { dir })
1212
+ : action === 'stop'
1213
+ ? stopProgramByKey(cwd, key, { dir })
1214
+ : restartProgramByKey(cwd, key, { dir })),
1215
+ () => ({ ok: false, code: 'program-failed', message: 'previous program operation failed', status: 500 }),
1216
+ ))
1217
+ } catch (error) {
1218
+ return fail(res, error?.status ?? 500, error?.code ?? 'program-failed', error?.message ?? String(error))
1219
+ }
1220
+ if (result.ok !== true) return fail(res, result.status ?? 500, result.code ?? 'program-failed', result.message ?? 'program operation failed')
1221
+ return json(res, 200, Object.assign({ ok: true, action }, result))
1222
+ }
1223
+
1224
+ if (path === '/v1/programs/log') {
1225
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET only')
1226
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
1227
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1228
+ const key = String(url.searchParams.get('id') ?? '')
1229
+ if (key === '') return fail(res, 400, 'bad-request', 'id is required')
1230
+ const dir = String(url.searchParams.get('dir') ?? '')
1231
+ const offsetRaw = url.searchParams.get('offset')
1232
+ const offset = offsetRaw === null || offsetRaw === '' ? null : Number(offsetRaw)
1233
+ const bytesRaw = Number(url.searchParams.get('bytes') ?? '')
1234
+ const result = await readProgramLog(cwd, key, {
1235
+ dir,
1236
+ offset: Number.isFinite(offset) ? offset : null,
1237
+ bytes: Number.isFinite(bytesRaw) && bytesRaw > 0 ? bytesRaw : undefined,
1238
+ })
1239
+ if (result.ok !== true) return fail(res, result.status ?? 500, result.code ?? 'log-failed', result.message ?? 'log read failed')
1240
+ return json(res, 200, result)
1241
+ }
1242
+
1243
+ if (path === '/v1/programs/log/stream') {
1244
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET only')
1245
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
1246
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1247
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1248
+ const key = String(url.searchParams.get('id') ?? '')
1249
+ if (key === '') return fail(res, 400, 'bad-request', 'id is required')
1250
+ const dir = String(url.searchParams.get('dir') ?? '')
1251
+ const listed = await listPrograms(cwd, { dir })
1252
+ const program = findProgram(listed.programs, key)
1253
+ if (program === null) return fail(res, 404, 'no-program', `未找到程序「${key}」`)
1254
+ const offsetRaw = url.searchParams.get('offset')
1255
+ const offset = offsetRaw === null || offsetRaw === '' ? null : Number(offsetRaw)
1256
+ const bytesRaw = Number(url.searchParams.get('bytes') ?? '')
1257
+ res.writeHead(200, {
1258
+ 'content-type': 'text/event-stream; charset=utf-8',
1259
+ 'cache-control': 'no-cache, no-transform',
1260
+ connection: 'keep-alive',
1261
+ 'x-accel-buffering': 'no',
1262
+ })
1263
+ let follow = null
1264
+ follow = startLogFollow(program, {
1265
+ offset: Number.isFinite(offset) ? offset : null,
1266
+ bytes: Number.isFinite(bytesRaw) && bytesRaw > 0 ? bytesRaw : undefined,
1267
+ }, (frame) => {
1268
+ if (frame.type === 'ping') { res.write(': ping\n\n'); return }
1269
+ res.write(`event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`)
1270
+ if (frame.type === 'end') {
1271
+ follow?.stop()
1272
+ res.end()
1273
+ }
1274
+ })
1275
+ req.on('close', () => follow.stop())
1276
+ return
1277
+ }
1278
+
1279
+ if (path === '/v1/status' || path === '/v1/proxy') {
1280
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1281
+ // The rule table is machine-wide, so the page may omit cwd; a workspace is
1282
+ // only a label kept on rows, and the daemon's home is a valid stand-in.
1283
+ const rawCwd = url.searchParams.get('cwd')
1284
+ const asked = rawCwd === null ? null : absoluteCwd(rawCwd)
1285
+ if (rawCwd !== null && asked === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1286
+ // /v1/proxy is machine-wide (the page's rule editor omits cwd); /v1/status
1287
+ // still needs to know whose programs to report, so it stays strict.
1288
+ if (path === '/v1/status' && asked === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1289
+ const cwd = asked ?? home
1290
+ if (asked !== null) rememberWorkspace(asked)
1291
+ const view = await risdProxyView(cwd)
1292
+ // `bridge` is the outcome of the background reload a save kicked off, so the
1293
+ // page can report a failed switch without the save having to wait for it.
1294
+ return json(res, 200, Object.assign({}, view, { daemon: daemonSummary(), bridge: bridgeReloadState }))
1295
+ }
1296
+
1297
+ if (path === '/v1/engine') {
1298
+ if (method === 'GET') {
1299
+ const cwd = absoluteCwd(url.searchParams.get('cwd')) ?? engineCwd
1300
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1301
+ const status = await proxyStatus(cwd)
1302
+ return json(res, 200, {
1303
+ ok: true,
1304
+ cwd,
1305
+ engine: {
1306
+ owned: engineCwd !== null,
1307
+ running: status.running,
1308
+ pid: status.pid,
1309
+ listen: status.listen,
1310
+ logPath: status.logPath,
1311
+ socksUrl: status.socksUrl,
1312
+ },
1313
+ })
1314
+ }
1315
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1316
+ const parsed = parseJson(await readBody(req))
1317
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1318
+ // The maintenance page has no dsh session, so it may start/stop without a
1319
+ // workspace: the engine is machine-scoped and only needs an existing cwd
1320
+ // for the pidfile, so the daemon home is a fine stand-in.
1321
+ const cwd = parsed.cwd === undefined || parsed.cwd === null ? home : absoluteCwd(parsed.cwd)
1322
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1323
+ const action = parsed.action
1324
+ if (action !== 'start' && action !== 'stop') return fail(res, 400, 'bad-request', 'action must be start or stop')
1325
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1326
+ const result = await serializeEngine(async () => {
1327
+ if (action === 'start') {
1328
+ const started = await startProxy(cwd)
1329
+ if (started.ok === true) engineCwd = cwd
1330
+ return started
1331
+ }
1332
+ const stopped = await stopProxy(cwd)
1333
+ if (stopped.ok === true) engineCwd = null
1334
+ return stopped
1335
+ })
1336
+ return json(res, 200, { ok: true, cwd, action, result })
1337
+ }
1338
+
1339
+ if (path === '/v1/leases') {
1340
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'POST only')
1341
+ const parsed = parseJson(await readBody(req))
1342
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1343
+ const ownerPid = Number(parsed.ownerPid)
1344
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0) return fail(res, 400, 'bad-request', 'ownerPid must be a positive integer')
1345
+ // null is the client's way of saying "no workspace" (a plugin that did not
1346
+ // have a cwd at mount time); only a wrong TYPE is a bad request.
1347
+ const cwd = parsed.cwd === undefined || parsed.cwd === null ? null : absoluteCwd(parsed.cwd)
1348
+ if (parsed.cwd !== undefined && parsed.cwd !== null && cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1349
+ const sessionId = parsed.sessionId === undefined ? null : String(parsed.sessionId)
1350
+ cancelIdleExit()
1351
+ const lease = leases.acquire({ ownerPid, sessionId, cwd })
1352
+ return json(res, 200, { ok: true, lease })
1353
+ }
1354
+
1355
+ const leaseMatch = /^\/v1\/leases\/([^/]+)$/.exec(path)
1356
+ if (leaseMatch !== null) {
1357
+ if (method !== 'DELETE') return fail(res, 405, 'method-not-allowed', 'DELETE only')
1358
+ const released = leases.release(decodeURIComponent(leaseMatch[1]))
1359
+ if (released) {
1360
+ // The window that owned debug sessions is gone. Drop its ownership so the
1361
+ // next window is not locked out of every mutating debug action
1362
+ // (review B-P1-1).
1363
+ if (leases.count() === 0) { try { debug.releaseOwners() } catch { /* ignore */ } }
1364
+ scheduleTeardown()
1365
+ }
1366
+ return json(res, 200, { ok: true, released })
1367
+ }
1368
+
1369
+ if (path === '/v1/config') {
1370
+ if (method === 'POST') {
1371
+ const parsed = parseJson(await readBody(req))
1372
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1373
+ if (parsed.lifecycle === undefined) return fail(res, 400, 'bad-request', 'lifecycle is required')
1374
+ // `null`/`[]` used to be written back as the defaults, i.e. a request with
1375
+ // no usable value silently reset the policy (review A2-P2-2).
1376
+ if (parsed.lifecycle === null || Array.isArray(parsed.lifecycle) || typeof parsed.lifecycle !== 'object') {
1377
+ return fail(res, 400, 'bad-request', 'lifecycle 必须是对象')
1378
+ }
1379
+ // Merge over what is on DISK, not over the copy this process loaded:
1380
+ // otherwise a hand edit made while the daemon runs is overwritten by the
1381
+ // in-memory copy on the next checkbox save (review A3-P2-6). The strict
1382
+ // merge copies unknown resources/keys through so normalizeLifecycle is
1383
+ // the one place that rejects them (review A3-P1-2).
1384
+ const disk = readLifecycle(home)
1385
+ const written = writeLifecycle(home, mergeLifecycle(disk.value, parsed.lifecycle))
1386
+ if (written.errors.length > 0) return fail(res, 400, 'bad-request', written.errors.join('; '))
1387
+ lifecycle = written.value
1388
+ // Re-arm the idle timer with the new policy: turning "follow dsh" off
1389
+ // must not leave a timer armed from before the change.
1390
+ if (lifecycle.daemon.followDsh !== true) cancelIdleExit()
1391
+ else if (leases.count() === 0 && engineCwd === null) scheduleIdleExit()
1392
+ return json(res, 200, { ok: true, lifecycle, configPath: join(home, 'risd-lifecycle.json') })
1393
+ }
1394
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1395
+ return json(res, 200, {
1396
+ ok: true,
1397
+ apiVersion: RISD_API_VERSION,
1398
+ keepPolicy: 'session',
1399
+ // Report the constant the timers actually use; the old literal was a
1400
+ // second source of truth and `engineRestart` described nothing that
1401
+ // exists in the daemon (review A-P2-3).
1402
+ idleExitMs: IDLE_EXIT_MS,
1403
+ lifecycle,
1404
+ lifecycleErrors: readLifecycle(home).errors ?? [],
1405
+ })
1406
+ }
1407
+
1408
+ // m11421: 维护页源码比进程新时,页面上的按钮是「重启并刷新」——光刷新救不了
1409
+ // 旧代码(模块图在进程内存里)。这里让 daemon 自己交接:先起一个带 --wait-pid
1410
+ // 的后继(等本进程退出后才 bind 端口,避免 already-running),再走 handoff 的
1411
+ // stop 路径(保留代理引擎/桥接,由后继收养)。
1412
+ if (path === '/v1/restart') {
1413
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'POST only')
1414
+ const already = restarting
1415
+ restarting = true
1416
+ json(res, 200, { ok: true, restarting: true, pid: process.pid })
1417
+ if (!already) {
1418
+ setImmediate(() => {
1419
+ spawnRestartSuccessor(actualPort)
1420
+ if (onShutdown !== null) onShutdown(true)
1421
+ })
1422
+ }
1423
+ return undefined
1424
+ }
1425
+
1426
+ if (path === '/v1/shutdown') {
1427
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'POST only')
1428
+ const parsed = parseJson(await readBody(req)) ?? {}
1429
+ const handoff = parsed.handoff === true
1430
+ json(res, 200, { ok: true, draining: true, handoff })
1431
+ if (onShutdown !== null) setImmediate(() => onShutdown(handoff === true))
1432
+ return undefined
1433
+ }
1434
+
1435
+ return fail(res, 404, 'not-found', `no such endpoint: ${method} ${path}`)
1436
+ } catch (error) {
1437
+ if (error instanceof DebugError) {
1438
+ const code = String(error.code ?? 'debug-failed')
1439
+ // `debug-owned` / `not-startable` are the daemon's own codes; the rest map
1440
+ // through the engine so the plugin sees the same status as before P3.
1441
+ const status = code === 'debug-owned' ? 409
1442
+ : code === 'not-startable' ? 400
1443
+ : debugErrorStatus(code)
1444
+ return fail(res, status, code, String(error.message ?? error))
1445
+ }
1446
+ const code = String(error?.code ?? '')
1447
+ const status = code === 'too-large' ? 413 : code === 'timeout' ? 408 : 500
1448
+ const reason = status === 413 ? 'too-large' : status === 408 ? 'timeout' : 'internal'
1449
+ return fail(res, status, reason, String(error?.message ?? error))
1450
+ }
1451
+ }
1452
+
1453
+ const server = createServer(handler)
1454
+ // Keep-alive sockets from a dead plugin must not delay shutdown: idle them out
1455
+ // after 1s instead of Node's 5s default.
1456
+ server.keepAliveTimeout = 1000
1457
+
1458
+ let engineInherited = false
1459
+ // Component health probes spawn a process per side: cache the snapshot for 30 s
1460
+ // and let the card's「重新检查」force it (m11828).
1461
+ const bridgeHealth = createHealthCache()
1462
+ // Minimum gap between automatic start/stop attempts (m12046/m12053): a missing
1463
+ // elevation must not retry on every poll, and the supervisor is only a safety net.
1464
+ const BRIDGE_PULL_INTERVAL_MS = 60_000
1465
+ /** How often the supervisor re-checks the engine ⇔ component pairing (m12060). */
1466
+ const BRIDGE_RECONCILE_MS = 15_000
1467
+ let lastBridgePullAt = 0
1468
+ let lastBridgeStopAt = 0
1469
+ let reconciling = false
1470
+ // m12359: when a side cannot start (Linux needs root), the CLI prints the exact
1471
+ // command to paste. Remember the last attempt so the health card can show it.
1472
+ let lastBridgeStart = null
1473
+ /**
1474
+ * The exact command a user can paste to start a side by hand.
1475
+ *
1476
+ * The health card needs it even when this process never attempted a start (the
1477
+ * bridge may already be running on one side, so no attempt was made): without it
1478
+ * the panel just says 「需要提权」 and never tells the user what to run (m12359).
1479
+ * @returns {{linux?: string, windows?: string}} display commands, empty when unknown.
1480
+ */
1481
+ /**
1482
+ * Whether the elevation terminal for each side is still open. The helper script
1483
+ * owns a state file for exactly that lifetime (m12923).
1484
+ * @returns {{linux: object, windows: object}} per-side state.
1485
+ */
1486
+ function elevationState() {
1487
+ return {
1488
+ linux: readElevationState('local', { home }),
1489
+ windows: readElevationState('windows', { home }),
1490
+ }
1491
+ }
1492
+
1493
+ function bridgeCommands() {
1494
+ try {
1495
+ const base = bundledBundleDir()
1496
+ const profilePath = redirectorProfilePath()
1497
+ return {
1498
+ linux: redirectorCommand({ cliPath: join(base, 'linux', 'ProxyBridge'), profilePath }).display,
1499
+ }
1500
+ } catch { return {} }
1501
+ }
1502
+ /**
1503
+ * The degraded path used when the OS-level component cannot run (m12486).
1504
+ *
1505
+ * Without root the Linux side cannot intercept; launchers can still give a program
1506
+ * the local CONNECT listener through env vars and JVM args. Programs that cannot be
1507
+ * told a proxy address (JDBC drivers, Navicat…) only work through an interception
1508
+ * layer, so the same payload carries the command to start one.
1509
+ * @returns {{httpProxyUrl: string, jvmArgs: string[], env: Record<string,string>, note: string}} degraded plan.
1510
+ */
1511
+ function bridgeDegrade() {
1512
+ let listenPort = 11081
1513
+ try {
1514
+ const stored = readProxyConfig(home)
1515
+ if (Number.isInteger(stored.listenPort) && stored.listenPort > 0) listenPort = stored.listenPort
1516
+ } catch { /* default */ }
1517
+ const url = `http://127.0.0.1:${listenPort}`
1518
+ let command = ''
1519
+ try {
1520
+ command = redirectorCommand({ cliPath: join(bundledBundleDir(), 'linux', 'ProxyBridge'), profilePath: redirectorProfilePath() }).display
1521
+ } catch { /* the card then only shows the degraded plan */ }
1522
+ // git is the third degraded path (m12567): the daemon writes the global
1523
+ // `http.<host>.proxy` entry itself, so git/maven/npm-style clients that honour it
1524
+ // keep working without the OS-level component.
1525
+ let socksUrl = ''
1526
+ try {
1527
+ const socks = readProxyConfig(home).socks
1528
+ if (socks.host !== '' && socks.port > 0) socksUrl = `socks5h://${socks.host}:${socks.port}`
1529
+ } catch { /* keep it empty */ }
1530
+ let git = null
1531
+ try {
1532
+ const state = readGitProxyState()
1533
+ if (state.host !== '' && state.value !== '') git = { host: state.host, key: state.key, value: state.value }
1534
+ } catch { /* no git proxy written yet */ }
1535
+ return {
1536
+ httpProxyUrl: url,
1537
+ command,
1538
+ jvmArgs: [
1539
+ '-Dhttp.proxyHost=127.0.0.1',
1540
+ `-Dhttp.proxyPort=${listenPort}`,
1541
+ '-Dhttps.proxyHost=127.0.0.1',
1542
+ `-Dhttps.proxyPort=${listenPort}`,
1543
+ '-Dhttp.nonProxyHosts=localhost|127.*|[::1]',
1544
+ ],
1545
+ env: { ALL_PROXY: url, HTTP_PROXY: url, HTTPS_PROXY: url, NO_PROXY: 'localhost,127.0.0.1,::1' },
1546
+ socksUrl,
1547
+ git,
1548
+ note: '降级:JVM 程序用下面的 -D 参数、能读环境变量的程序用 ALL_PROXY;JDBC/Navicat 这类无法注入代理的程序只能靠系统层拦截',
1549
+ }
1550
+ }
1551
+ /**
1552
+ * Remember one bridge start attempt for the health card.
1553
+ * @param {{started?: object[], skipped?: object[], running?: boolean}} started - `startRedirectors()` outcome.
1554
+ */
1555
+ function noteBridgeStart(started) {
1556
+ if (!started || typeof started !== 'object') return
1557
+ lastBridgeStart = {
1558
+ at: new Date().toISOString(),
1559
+ started: Array.isArray(started.started) ? started.started.map((item) => ({ side: item.side, pid: item.pid })) : [],
1560
+ skipped: Array.isArray(started.skipped)
1561
+ ? started.skipped.map((item) => ({ side: item.side, reason: item.reason, command: item.command }))
1562
+ : [],
1563
+ running: started.running === true,
1564
+ }
1565
+ }
1566
+
1567
+ function engineSummary() {
1568
+ // `owned` means "this daemon has started the engine during its lifetime"; a
1569
+ // pidfile found at startup is reported as owned:false so the plugin can still
1570
+ // show the inherited banner and offer to stop it (Phase 1a behaviour).
1571
+ try {
1572
+ const pid = proxyPid()
1573
+ return { owned: engineCwd !== null, inherited: engineInherited, pid: pid ?? 0, state: pid === null ? 'stopped' : 'running', cwd: engineCwd }
1574
+ } catch {
1575
+ return { owned: false, inherited: engineInherited, pid: 0, state: 'unknown', cwd: engineCwd }
1576
+ }
1577
+ }
1578
+
1579
+ function daemonSummary() {
1580
+ return { pid: process.pid, version, apiVersion: RISD_API_VERSION, leases: leases.count() }
1581
+ }
1582
+
1583
+ const listenResult = await new Promise((resolve) => {
1584
+ const onError = (error) => {
1585
+ server.removeListener('listening', onListening)
1586
+ resolve({ ok: false, error })
1587
+ }
1588
+ const onListening = () => {
1589
+ server.removeListener('error', onError)
1590
+ resolve({ ok: true })
1591
+ }
1592
+ server.once('error', onError)
1593
+ server.once('listening', onListening)
1594
+ server.listen(port, '127.0.0.1')
1595
+ })
1596
+
1597
+ if (!listenResult.ok) {
1598
+ const error = listenResult.error
1599
+ if (error?.code === 'EADDRINUSE') {
1600
+ const probe = await probeRisdHealth(port)
1601
+ if (probe?.ok === true && Number(probe.body?.apiVersion) === RISD_API_VERSION) {
1602
+ // Same port, different home: the other daemon is healthy but its state file
1603
+ // lives elsewhere, so two daemons would overwrite each other's token/port
1604
+ // and the plugin would talk to whichever wrote last (review A-P2-9).
1605
+ if (typeof probe.body?.home === 'string' && probe.body.home !== '' && probe.body.home !== home) {
1606
+ return { ok: false, code: 'home-mismatch', found: String(probe.body.home), home, port }
1607
+ }
1608
+ return { ok: false, code: 'already-running', pid: Number(probe.body?.pid) || 0, port }
1609
+ }
1610
+ if (probe?.ok === true) {
1611
+ return { ok: false, code: 'api-mismatch', found: Number(probe.body?.apiVersion) || 0, port }
1612
+ }
1613
+ return { ok: false, code: 'port-busy', port }
1614
+ }
1615
+ return { ok: false, code: 'listen-failed', error }
1616
+ }
1617
+
1618
+ const actualPort = server.address()?.port ?? port
1619
+ const state = {
1620
+ apiVersion: RISD_API_VERSION,
1621
+ version,
1622
+ pid: process.pid,
1623
+ port: actualPort,
1624
+ token,
1625
+ home,
1626
+ startedAt,
1627
+ url: `http://127.0.0.1:${actualPort}`,
1628
+ }
1629
+
1630
+ try {
1631
+ writeRisdState(state, home)
1632
+ } catch (error) {
1633
+ server.close()
1634
+ return { ok: false, code: 'state-write-failed', error }
1635
+ }
1636
+
1637
+ // Phase 1b P6 (handoff): the predecessor wrote down what it owned. If that engine
1638
+ // is still the one in the pidfile, adopt it instead of reporting owned:false —
1639
+ // that is the whole point of handing over: no teardown, no restart, no dropped
1640
+ // connection while the plugin restarts the daemon.
1641
+ try {
1642
+ const handoff = previousState?.handoff
1643
+ if (handoff !== null && handoff !== undefined && typeof handoff.cwd === 'string' && handoff.cwd !== '') {
1644
+ const pid = proxyPid()
1645
+ if (pid !== null && Number(handoff.enginePid) === pid) {
1646
+ engineCwd = handoff.cwd
1647
+ engineInherited = true
1648
+ }
1649
+ }
1650
+ } catch { /* adoption is best effort: the pidfile decides ownership anyway */ }
1651
+
1652
+ leases.start()
1653
+
1654
+ // Phase 1b P3: the daemon owns the bridge heartbeat and the janitor from the
1655
+ // moment it is ready. The plugin no longer writes either while it forwards.
1656
+ try {
1657
+ writeHeartbeat()
1658
+ heartbeat = setInterval(() => {
1659
+ try { writeHeartbeat() } catch { /* the watchdog decides; log is best effort */ }
1660
+ }, 3000)
1661
+ heartbeat.unref?.()
1662
+ } catch {
1663
+ heartbeat = null
1664
+ }
1665
+ try {
1666
+ armJanitor({ ownerPid: process.pid })
1667
+ } catch { /* a janitor failure must not keep the daemon from serving */ }
1668
+
1669
+ // A daemon opened from the maintenance page (or by ⧉ before the plugin has taken a
1670
+ // lease) owns nothing yet. Without arming here it never armed the idle timer at
1671
+ // all — `scheduleIdleExit` is only reached from lease teardown and POST /v1/config
1672
+ // — so every click left one more resident node process (review C2-P1-1). A lease
1673
+ // arriving right after cancels this timer again.
1674
+ if (engineCwd === null && leases.count() === 0) scheduleIdleExit()
1675
+
1676
+ // We are the machine-level owner now, so reconcile what the previous run left:
1677
+ // git entries for a dead engine, a bridge parked by us, stale pid/state files.
1678
+ // Run the startup reconcile through the engine queue: it touches the engine
1679
+ // pidfile and a user's /v1/action may already be in flight. Own pid is passed so
1680
+ // the reconcile can never delete the state file of this very daemon.
1681
+ /**
1682
+ * True when some ProxyBridge side left a pid file in this proxy home: the only
1683
+ * situation where a stopped engine can still have a live component (m12053).
1684
+ * Pure filesystem checks — no probing.
1685
+ */
1686
+ function hasBridgePidFiles() {
1687
+ try {
1688
+ const names = [REDIRECTOR_PID_FILENAME, REDIRECTOR_PID_FILENAMES.local, REDIRECTOR_PID_FILENAMES.windows]
1689
+ return names.some((name) => existsSync(join(redirectorHome(), name)))
1690
+ } catch {
1691
+ return false
1692
+ }
1693
+ }
1694
+
1695
+ /**
1696
+ * Component sides this host can actually run (review A4-P2-7).
1697
+ *
1698
+ * Native Windows runs only the Windows CLI, Linux only the Linux one, and WSL can
1699
+ * run both — the Windows side only when the bundle has a Windows-addressable
1700
+ * target (%LOCALAPPDATA%). Used to decide *which* side is missing instead of the
1701
+ * old "both sides down" test, which left a half-started bridge alone forever.
1702
+ *
1703
+ * @returns {Array<'local'|'windows'>} side names, in start order.
1704
+ */
1705
+ function bridgeApplicableSides() {
1706
+ try {
1707
+ if (process.platform === 'win32') return ['windows']
1708
+ const sides = ['local']
1709
+ if (isWslHost() === true && String(windowsBundleDir() ?? '') !== '') sides.push('windows')
1710
+ return sides
1711
+ } catch {
1712
+ return ['local']
1713
+ }
1714
+ }
1715
+
1716
+ /**
1717
+ * Keep the engine and the system-layer component consistent (m12060).
1718
+ *
1719
+ * One place decides both directions, because the pairs that otherwise drift are
1720
+ * many: an inherited engine after a dsh crash, a CLI that died while the engine
1721
+ * kept running, a manual stop of either side, a crash of the engine itself. Start
1722
+ * and stop stay serialized through serializeBridge, and an elevation failure is
1723
+ * retried at most once per minute so a page left open cannot spin UAC prompts.
1724
+ *
1725
+ * @param {string} reason - where the reconcile came from (log/debug only).
1726
+ * @returns {Promise<void>} resolves when the attempt is over (best effort).
1727
+ */
1728
+ async function reconcileEngineBridge(reason) {
1729
+ if (reconciling === true) return
1730
+ if (stopping === true) return
1731
+ reconciling = true
1732
+ try {
1733
+ const engine = engineSummary()
1734
+ // `unknown` means the pidfile could not be read — not that nothing is running
1735
+ // (review A4-P2-9): doing nothing is the only safe answer.
1736
+ if (engine.state === 'unknown') return
1737
+ const engineRunning = engine.state === 'running'
1738
+ const engineStopped = engine.state === 'stopped'
1739
+ // Cheap gate first: probing the bridge (WSL: PowerShell, ~3 s) must not run on
1740
+ // every startup/poll when there is nothing to reconcile. A pid file is the
1741
+ // evidence that a component may be left behind after a crash (m12046/m12053).
1742
+ if (engineStopped === true && hasBridgePidFiles() !== true) return
1743
+ // Async probe: a spawnSync here would block the whole daemon (and every request
1744
+ // queued behind it) for the duration of the Windows PowerShell probe.
1745
+ const bridge = await redirectorStatusAsync()
1746
+ // Stopping may have begun while the probe ran: do not start/stop a bridge the
1747
+ // teardown is about to handle.
1748
+ if (stopping === true) return
1749
+ if (engineRunning === true) {
1750
+ // Only the sides this host can run matter; a half-started bridge (one side
1751
+ // up, one skipped) must still be completed (review A4-P2-7).
1752
+ const missing = bridgeApplicableSides().filter((side) => (side === 'windows' ? bridge.runningWindows !== true : bridge.runningLocal !== true))
1753
+ if (missing.length === 0) return
1754
+ if (Date.now() - lastBridgePullAt < BRIDGE_PULL_INTERVAL_MS) return
1755
+ lastBridgePullAt = Date.now()
1756
+ // Never prompt for elevation from a background pass: the page owns that.
1757
+ const started = await serializeBridge(() => startRedirectors({ sides: missing, interactive: false }))
1758
+ noteBridgeStart(started)
1759
+ const failed = (Array.isArray(started?.skipped) ? started.skipped : []).filter((item) => missing.includes(item.side))
1760
+ if (failed.length > 0) {
1761
+ const why = failed.map((item) => `${item.side}:${item.reason}`).join(';')
1762
+ process.stdout.write(`[dsh-ris-ide] 代理引擎已运行但系统层拦截未启动(${reason}):${why}\n`)
1763
+ }
1764
+ } else if (engineStopped === true && bridge.running === true) {
1765
+ if (Date.now() - lastBridgeStopAt < BRIDGE_PULL_INTERVAL_MS) return
1766
+ lastBridgeStopAt = Date.now()
1767
+ process.stdout.write(`[dsh-ris-ide] 代理引擎未运行:停止系统层拦截(${reason}),避免把连接转发到已关闭的端口\n`)
1768
+ await serializeBridge(() => stopRedirector())
1769
+ lastBridgeStart = null
1770
+ }
1771
+ } catch { /* elevation missing: the page shows the reason; the timer retries later */ } finally {
1772
+ reconciling = false
1773
+ }
1774
+ }
1775
+ const bridgeSupervisor = setInterval(() => { void reconcileEngineBridge('timer') }, BRIDGE_RECONCILE_MS)
1776
+ bridgeSupervisor.unref?.()
1777
+
1778
+ void serializeEngine(async () => {
1779
+ await reconcileStartupLeftovers({
1780
+ ownPid: process.pid,
1781
+ log: (message) => { try { process.stdout.write(`${message}\n`) } catch { /* ignore */ } },
1782
+ })
1783
+ // m12046/m12053/m12060: one invariant, enforced from one place — the engine and
1784
+ // the component run together. Startup, health polling and the supervisor all call
1785
+ // this, so "engine up ⇒ component up" and "engine down ⇒ component down" cannot
1786
+ // drift apart (an inherited engine, a crashed CLI, a manual stop all converge).
1787
+ // Deliberately not awaited: probing the bridge costs seconds on WSL (PowerShell)
1788
+ // and `/ready` must not wait for a component that is usually absent. The
1789
+ // supervisor re-checks in 15 s, so a missed first pass self-heals.
1790
+ setImmediate(() => { void reconcileEngineBridge('startup') })
1791
+
1792
+ // Invariant (m11863): the component must not keep intercepting once the proxy
1793
+ // engine is gone — every redirected connection would be sent to a dead listener
1794
+ // and fail in a way that looks like the network broke. The engine can be absent
1795
+ // at startup (previous dsh stopped it, plugin fallback never ran); the bridge
1796
+ // may still be alive from an earlier session, so reap it here.
1797
+ // Only a bridge this proxy home recorded is ours to reap: a machine-wide CLI with
1798
+ // another profile (or a fixture daemon with an empty home) is not. And never block
1799
+ // `/ready` on the probe — on WSL it spawns PowerShell.
1800
+ // Serialized with every other bridge mutation so a user's start/stop cannot be
1801
+ // interleaved with this reap, and guarded by `stopping` so a shutdown that began
1802
+ // meanwhile is not undone by a late stop (review A4-P2-7 / startup-reap).
1803
+ setImmediate(() => {
1804
+ void serializeBridge(async () => {
1805
+ if (stopping === true) return
1806
+ if (proxyPid() !== null) return
1807
+ if (hasBridgePidFiles() !== true) return
1808
+ try {
1809
+ if ((await redirectorStatusAsync()).running !== true) return
1810
+ process.stdout.write('[dsh-ris-ide] 代理引擎未运行:停止系统层拦截,避免把连接转发到已关闭的端口\n')
1811
+ await stopRedirector()
1812
+ lastBridgeStart = null
1813
+ } catch { /* best effort: the next stop click retries with elevation */ }
1814
+ })
1815
+ })
1816
+ }).catch(() => {})
1817
+
1818
+ let stopping = false
1819
+ /**
1820
+ * Stop serving.
1821
+ * @param {{handoff?: boolean}} [options] - `handoff` = a successor will take over:
1822
+ * leave the engine, bridge, heartbeat file, janitor and state note in place.
1823
+ */
1824
+ async function stop(options = {}) {
1825
+ if (stopping) return
1826
+ stopping = true
1827
+ const handoff = options?.handoff === true
1828
+ cancelIdleExit()
1829
+ clearInterval(bridgeSupervisor)
1830
+ if (heartbeat !== null) {
1831
+ clearInterval(heartbeat)
1832
+ heartbeat = null
1833
+ }
1834
+ leases.stop()
1835
+ // JDWP sockets are process-local: detach before closing so a VM paused on a
1836
+ // breakpoint is resumed instead of being left frozen for the next daemon.
1837
+ // Following the daemon is not configurable (m07741): stop everything we supervise.
1838
+ await debug.stopAll().catch(() => {})
1839
+ if (handoff) {
1840
+ // Hand the network over: the successor adopts the engine pid, the bridge
1841
+ // watchdog keeps its heartbeat (20 s window), and the state note is what it
1842
+ // reads to know the engine is its own. Deliberately no teardown/disarm.
1843
+ try {
1844
+ writeRisdState(Object.assign({}, state, {
1845
+ handoff: { cwd: engineCwd, enginePid: proxyPid() ?? 0, at: new Date().toISOString() },
1846
+ }), home)
1847
+ } catch { /* best effort: the successor can still adopt by pidfile */ }
1848
+ // Keep the armed watcher from tearing the network down in the gap between
1849
+ // our exit and the successor's registration (it reads this stamp).
1850
+ try { markJanitorHandoff() } catch { /* no armed watcher: nothing to tell */ }
1851
+ server.closeIdleConnections?.()
1852
+ await new Promise((resolve) => {
1853
+ const timer = setTimeout(() => {
1854
+ server.closeAllConnections?.()
1855
+ resolve(undefined)
1856
+ }, 1500)
1857
+ timer.unref?.()
1858
+ server.close(() => {
1859
+ clearTimeout(timer)
1860
+ resolve(undefined)
1861
+ })
1862
+ })
1863
+ return
1864
+ }
1865
+ // "Stop the daemon" means stop what it supervises: JVMs first (JDWP sockets
1866
+ // were detached above), then the network layers below. A handoff skips all of
1867
+ // this — the successor adopts them.
1868
+ await stopAllPrograms()
1869
+ // Drain in-flight operations first: a start that was already running would
1870
+ // otherwise spawn an engine after teardown and leave an orphan (review A-P1-2).
1871
+ await engineOp.catch(() => {})
1872
+ await bridgeOp.catch(() => {})
1873
+ // Only remove the state file if it is still ours: a newer daemon that
1874
+ // replaced us must keep its own file.
1875
+ const current = readRisdState(home)
1876
+ if (current !== null && current.pid === process.pid) removeRisdState(home)
1877
+ // Graceful exit takes the network with it (only what THIS daemon owns: an
1878
+ // engine found in the pidfile at startup belongs to someone else and is left
1879
+ // alone). Bounded: a slow bridge probe on a WSL `/mnt/c` mount must not keep
1880
+ // `risd stop` — or the next spawn — waiting. If the bound hits, the armed
1881
+ // janitor finishes the job after this process is gone — which is why the
1882
+ // watcher is only disarmed when the teardown actually completed. Unconditional
1883
+ // disarm after a timed-out race would leave the engine/pidfile/port behind with
1884
+ // nothing left to clean them up (review A-P0-2).
1885
+ let tornDown = false
1886
+ // Following the daemon is not configurable (m07741): the proxy always goes with
1887
+ // it. Keeping a resource alive past its supervisor used to require a detached
1888
+ // heartbeat writer (D3) and would have left the machine with no page to stop it.
1889
+ await Promise.race([
1890
+ (typeof teardown === 'function' ? teardown(engineCwd) : teardownNetwork(engineCwd)).then(() => { tornDown = true }),
1891
+ new Promise((resolve) => { const timer = setTimeout(resolve, teardownTimeoutMs); timer.unref?.() }),
1892
+ ])
1893
+ engineCwd = null
1894
+ // Nothing is supervised anymore; the card must not keep a stale start report
1895
+ // (review A4-P2-8). This is also the fallback when teardown was skipped.
1896
+ lastBridgeStart = null
1897
+ server.closeIdleConnections?.()
1898
+ await new Promise((resolve) => {
1899
+ const timer = setTimeout(() => {
1900
+ server.closeAllConnections?.()
1901
+ resolve(undefined)
1902
+ }, 1500)
1903
+ timer.unref?.()
1904
+ server.close(() => {
1905
+ clearTimeout(timer)
1906
+ resolve(undefined)
1907
+ })
1908
+ })
1909
+ if (tornDown) {
1910
+ try { disarmJanitor() } catch { /* janitor may not be armed */ }
1911
+ } else {
1912
+ // The armed watcher outlives us on purpose: it retries the cleanup once the
1913
+ // process is gone (same effect the exit hook used to provide).
1914
+ try { process.stderr.write('risd: teardown did not finish within 5s; leaving the janitor armed\n') } catch { /* detached stdio */ }
1915
+ }
1916
+ }
1917
+
1918
+ return { ok: true, server, port: actualPort, state, leases, stop }
1919
+ }