dsh-ris-ide 1.7.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +43 -4
  2. package/bin/check-listing.mjs +247 -0
  3. package/bin/proxy-janitor.mjs +183 -0
  4. package/bin/risd.mjs +287 -0
  5. package/bin/run-with-log.ps1 +43 -5
  6. package/lib/client-codemirror.js +92 -66
  7. package/lib/client.js +774 -89
  8. package/lib/index.js +2256 -21
  9. package/lib/janitor.js +377 -0
  10. package/lib/proxy.js +1577 -0
  11. package/lib/proxybridge-bundle.js +798 -0
  12. package/lib/redirector.js +2558 -0
  13. package/lib/risd/build.js +91 -0
  14. package/lib/risd/debug.js +374 -0
  15. package/lib/risd/git.js +207 -0
  16. package/lib/risd/leases.js +124 -0
  17. package/lib/risd/lifecycle.js +148 -0
  18. package/lib/risd/log.js +59 -0
  19. package/lib/risd/ping.js +94 -0
  20. package/lib/risd/programs.js +348 -0
  21. package/lib/risd/server.js +1478 -0
  22. package/lib/risd/state.js +137 -0
  23. package/lib/risd/ui.js +1705 -0
  24. package/lib/risd/view.js +79 -0
  25. package/lib/risd-client.js +282 -0
  26. package/lib/standalone/window.html +14 -16
  27. package/lib/startup.js +114 -0
  28. package/package.json +7 -2
  29. package/skills/dsh-ris-ide-debug/SKILL.md +37 -2
  30. package/test/client-build.test.mjs +113 -0
  31. package/test/client-viewer.test.mjs +314 -20
  32. package/test/companion.test.mjs +65 -0
  33. package/test/dsh-origin.test.mjs +140 -0
  34. package/test/dsh-window-refresh.test.mjs +100 -0
  35. package/test/harness.test.mjs +9 -0
  36. package/test/host-noloop.test.mjs +74 -0
  37. package/test/host-tail.test.mjs +54 -5
  38. package/test/host-window.test.mjs +4 -4
  39. package/test/inherit-engine.test.mjs +175 -0
  40. package/test/install-phase.test.mjs +36 -0
  41. package/test/janitor.test.mjs +172 -0
  42. package/test/lifecycle.test.mjs +109 -0
  43. package/test/merge-owners.test.mjs +155 -0
  44. package/test/proxy-restart.test.mjs +37 -0
  45. package/test/proxy-route.test.mjs +599 -0
  46. package/test/proxy-window.test.mjs +45 -0
  47. package/test/proxy.test.mjs +914 -0
  48. package/test/proxybridge-bundle.test.mjs +687 -0
  49. package/test/redirector-bundle.test.mjs +391 -0
  50. package/test/redirector.test.mjs +571 -0
  51. package/test/risd-api.test.mjs +470 -0
  52. package/test/risd-bridge-degrade.test.mjs +101 -0
  53. package/test/risd-build.test.mjs +20 -0
  54. package/test/risd-cli-home.test.mjs +50 -0
  55. package/test/risd-client.test.mjs +130 -0
  56. package/test/risd-debug.test.mjs +261 -0
  57. package/test/risd-election.test.mjs +104 -0
  58. package/test/risd-engine.test.mjs +132 -0
  59. package/test/risd-entry.test.mjs +118 -0
  60. package/test/risd-git.test.mjs +109 -0
  61. package/test/risd-handoff.test.mjs +116 -0
  62. package/test/risd-heal.test.mjs +50 -0
  63. package/test/risd-helpers.mjs +108 -0
  64. package/test/risd-host-p2.test.mjs +147 -0
  65. package/test/risd-janitor-guard.test.mjs +46 -0
  66. package/test/risd-lease.test.mjs +83 -0
  67. package/test/risd-lifecycle.test.mjs +210 -0
  68. package/test/risd-log-follow.test.mjs +227 -0
  69. package/test/risd-mode.test.mjs +161 -0
  70. package/test/risd-ping.test.mjs +99 -0
  71. package/test/risd-programs.test.mjs +169 -0
  72. package/test/risd-review-p2.test.mjs +217 -0
  73. package/test/risd-shutdown.test.mjs +97 -0
  74. package/test/risd-teardown.test.mjs +87 -0
  75. package/test/risd-tools.test.mjs +211 -0
  76. package/test/risd-ui.test.mjs +445 -0
  77. package/test/risd-write.test.mjs +170 -0
  78. package/test/startup-reconcile.test.mjs +100 -0
  79. package/test/windows.test.mjs +37 -2
@@ -0,0 +1,1478 @@
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 { reloadRedirectorsWithProfile, redirectorStatusCached, startRedirectors, stopRedirector, writeHeartbeat } from '../redirector.js'
33
+ import { risdConfigRevision, risdProxyView } from './view.js'
34
+ import { clearGitProxy, 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
+
44
+ /** Request bodies are tiny JSON objects; anything bigger is a bug or an attack. */
45
+ export const RISD_MAX_BODY_BYTES = 64 * 1024
46
+ /**
47
+ * A streamed body (only the bundle upload does this) may not hold the request open
48
+ * forever: a stalled upload used to keep a handler alive until the socket died.
49
+ */
50
+ export const RISD_BODY_TIMEOUT_MS = 15_000
51
+ /** How long a would-be second instance waits for the incumbent's health answer. */
52
+ export const START_PROBE_TIMEOUT_MS = 500
53
+ /** Header the plugin sends on every authenticated call. */
54
+ export const API_VERSION_HEADER = 'x-risd-api-version'
55
+
56
+ /** Where the plugin reports its own origin + current sessionId (see /v1/dsh). */
57
+ export const DSH_WINDOW_FILENAME = 'dsh-window.json'
58
+ /** A window with an entry younger than this is marked live in the page. */
59
+ const DSH_WINDOW_LIVE_MS = 5 * 60_000
60
+ /** Remembered windows older than this are pruned; between the two they show as
61
+ * "未活跃" but stay selectable (m08268: clicking one may still open the IDE). */
62
+ const DSH_WINDOW_RETAIN_MS = 7 * 24 * 60 * 60_000
63
+
64
+ /** The daemon's own page is only for the local browser (no DNS rebinding). */
65
+ export function isLoopbackHost(req) {
66
+ const raw = String(req.headers.host ?? '')
67
+ const host = raw.replace(/^\[/, '').replace(/\](?::\d+)?$/, '')
68
+ if (host === '::1') return true
69
+ const name = host.split(':')[0]
70
+ return name === '127.0.0.1' || name === 'localhost'
71
+ }
72
+
73
+ /** True for an `Origin` header that points at this machine (the page's own origin). */
74
+ export function isLoopbackOrigin(origin) {
75
+ try {
76
+ const url = new URL(origin)
77
+ const name = url.hostname.replace(/^\[/, '').replace(/\]$/, '')
78
+ return name === '127.0.0.1' || name === 'localhost' || name === '::1'
79
+ } catch {
80
+ return false
81
+ }
82
+ }
83
+
84
+ function json(res, status, payload) {
85
+ const body = `${JSON.stringify(payload)}\n`
86
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
87
+ res.end(body)
88
+ }
89
+
90
+ function fail(res, status, code, message) {
91
+ json(res, status, { ok: false, code, message })
92
+ }
93
+
94
+ function readBody(req) {
95
+ return new Promise((resolve, reject) => {
96
+ const chunks = []
97
+ let size = 0
98
+ let settled = false
99
+ const settle = (fn, value) => { if (!settled) { settled = true; fn(value) } }
100
+ req.on('data', (chunk) => {
101
+ if (settled) return
102
+ size += chunk.length
103
+ if (size > RISD_MAX_BODY_BYTES) {
104
+ // Keep draining instead of destroying the socket here: destroying it made
105
+ // the client see "socket hang up" rather than the 413 the handler writes
106
+ // (review A-P2-6).
107
+ chunks.length = 0
108
+ settle(reject, Object.assign(new Error('body too large'), { code: 'too-large' }))
109
+ req.resume()
110
+ return
111
+ }
112
+ chunks.push(chunk)
113
+ })
114
+ req.on('end', () => settle(resolve, Buffer.concat(chunks).toString('utf8')))
115
+ req.on('error', (error) => settle(reject, error))
116
+ })
117
+ }
118
+
119
+ /**
120
+ * Raw bodies are only used by the bundle upload, which is a .tgz and therefore
121
+ * exceeds the JSON limit. The cap comes from the bundle module, so a body that
122
+ * could not possibly be a valid bundle is rejected before it is buffered whole.
123
+ */
124
+ function readBodyBytes(req, limit, timeoutMs = RISD_BODY_TIMEOUT_MS) {
125
+ return new Promise((resolve, reject) => {
126
+ const chunks = []
127
+ let size = 0
128
+ let settled = false
129
+ const timer = setTimeout(() => {
130
+ chunks.length = 0
131
+ settle(reject, Object.assign(new Error('body read timed out'), { code: 'timeout' }))
132
+ req.resume()
133
+ }, timeoutMs)
134
+ timer.unref?.()
135
+ const settle = (fn, value) => { if (!settled) { settled = true; clearTimeout(timer); fn(value) } }
136
+ req.on('data', (chunk) => {
137
+ if (settled) return
138
+ size += chunk.length
139
+ if (size > limit) {
140
+ chunks.length = 0
141
+ settle(reject, Object.assign(new Error('body too large'), { code: 'too-large' }))
142
+ req.resume()
143
+ return
144
+ }
145
+ chunks.push(chunk)
146
+ })
147
+ req.on('end', () => settle(resolve, Buffer.concat(chunks)))
148
+ req.on('error', (error) => settle(reject, error))
149
+ })
150
+ }
151
+
152
+ /** One download at a time; the page polls GET /v1/proxybridge for the outcome. */
153
+ let bundleDownload = null
154
+ let bundleDownloadResult = null
155
+
156
+ /**
157
+ * The digest this machine expects the bundle to have. `''` means "do not verify,
158
+ * just record" (the module's own convention); the value can come from the env or
159
+ * the machine settings so an internal mirror can pin its own archive.
160
+ */
161
+ function bundleExpectedSha256(settings = readBundleSettings()) {
162
+ try {
163
+ if (typeof bundleApi.resolveBundleSha256 === 'function') {
164
+ return String(bundleApi.resolveBundleSha256({ env: process.env, settings }) ?? '')
165
+ }
166
+ } catch { /* fall through to the compiled-in digest */ }
167
+ return typeof bundleApi.BUNDLE_SHA256 === 'string' ? bundleApi.BUNDLE_SHA256 : ''
168
+ }
169
+
170
+ function proxyBridgeStatus() {
171
+ const dir = installDir(proxyHomeDir())
172
+ const installed = isInstalled(dir)
173
+ const manifest = installed ? readManifest(dir) : null
174
+ const settings = readBundleSettings()
175
+ // A bad override (typo'd settings.proxybridgeUrl) must not take the status route
176
+ // down with it: the safe resolver reports the error and falls back to the mirrors.
177
+ const resolved = typeof bundleApi.resolveBundleUrlsSafe === 'function'
178
+ ? bundleApi.resolveBundleUrlsSafe({ env: process.env, settings })
179
+ : { urls: resolveBundleUrls({ env: process.env, settings }), error: '' }
180
+ const urls = resolved.urls
181
+ const urlError = resolved.error === '' ? null : resolved.error
182
+ const sha256 = bundleExpectedSha256(settings)
183
+ const actual = manifest === null ? null : manifest.sha256 ?? null
184
+ return {
185
+ ok: true,
186
+ installed,
187
+ dir,
188
+ // Gitee first, GitHub second: both carry the release asset.
189
+ urls,
190
+ url: urls[0] ?? BUNDLE_URLS[0],
191
+ urlError,
192
+ // What an upload/download MUST hash to, and whether the installed copy does.
193
+ sha256,
194
+ actualSha256: actual,
195
+ verified: installed === true && (sha256 === '' || actual === sha256),
196
+ downloading: bundleDownload !== null,
197
+ result: bundleDownloadResult,
198
+ files: manifest === null ? [] : Object.keys(manifest.files),
199
+ installedAt: manifest === null ? null : manifest.installedAt,
200
+ }
201
+ }
202
+
203
+ /** `proxybridgeUrl` from the machine settings file, if a user set one. */
204
+ function readBundleSettings() {
205
+ try {
206
+ const path = join(proxyHomeDir(), 'settings.json')
207
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
208
+ return parsed !== null && typeof parsed === 'object' ? parsed : {}
209
+ } catch {
210
+ return {}
211
+ }
212
+ }
213
+
214
+ function startBundleDownload(force = false) {
215
+ if (bundleDownload !== null) return
216
+ const settings = readBundleSettings()
217
+ const expectedSha256 = bundleExpectedSha256(settings)
218
+ // `force` re-fetches even when a verified copy is cached; the maintenance page's
219
+ // 「重新下载」 button sends it (review C3-P2-6).
220
+ bundleDownload = ensureBundle({ home: proxyHomeDir(), settings, expectedSha256, force: force === true })
221
+ .then((result) => {
222
+ bundleDownloadResult = {
223
+ ok: result.ok,
224
+ code: result.ok === true ? null : result.code ?? 'install-failed',
225
+ fromCache: result.fromCache === true,
226
+ error: result.error ?? null,
227
+ expected: result.expected ?? expectedSha256,
228
+ actual: result.actual ?? null,
229
+ sha256: result.sha256 ?? null,
230
+ at: new Date().toISOString(),
231
+ }
232
+ return result
233
+ })
234
+ .catch((error) => {
235
+ bundleDownloadResult = {
236
+ ok: false,
237
+ code: error?.code ?? 'download-failed',
238
+ error: error instanceof Error ? error.message : String(error),
239
+ expected: error?.expected ?? expectedSha256,
240
+ actual: error?.actual ?? null,
241
+ at: new Date().toISOString(),
242
+ }
243
+ return null
244
+ })
245
+ .finally(() => { bundleDownload = null })
246
+ }
247
+
248
+ function parseJson(text) {
249
+ if (text.trim() === '') return {}
250
+ try {
251
+ const value = JSON.parse(text)
252
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined
253
+ } catch {
254
+ return undefined
255
+ }
256
+ }
257
+
258
+ function tokenMatches(expected, header) {
259
+ const prefix = 'bearer '
260
+ if (typeof header !== 'string' || !header.toLowerCase().startsWith(prefix)) return false
261
+ const given = header.slice(prefix.length).trim()
262
+ const a = Buffer.from(expected, 'utf8')
263
+ const b = Buffer.from(given, 'utf8')
264
+ return a.length === b.length && timingSafeEqual(a, b)
265
+ }
266
+
267
+ /**
268
+ * Absolute on this platform or on Windows. `path.isAbsolute` is platform-specific,
269
+ * so a POSIX daemon still has to recognise `C:\work` in a shared table; callers
270
+ * additionally require the directory to exist (review A-P1-3).
271
+ */
272
+ export function looksAbsolutePath(value) {
273
+ return typeof value === 'string' && value !== '' && (isAbsolute(value) || win32.isAbsolute(value))
274
+ }
275
+
276
+ function absoluteCwd(value) {
277
+ return looksAbsolutePath(value) ? value : null
278
+ }
279
+
280
+ /**
281
+ * Ask an existing daemon at `port` how it is doing. Used by the election path:
282
+ * EADDRINUSE alone cannot tell "same daemon" from "something else on 11082".
283
+ * @returns `{ ok, body }` or null.
284
+ */
285
+ export function probeRisdHealth(port, timeoutMs = START_PROBE_TIMEOUT_MS) {
286
+ return new Promise((resolve) => {
287
+ let settled = false
288
+ const finish = (value) => {
289
+ if (settled) return
290
+ settled = true
291
+ clearTimeout(timer)
292
+ resolve(value)
293
+ }
294
+ const call = request({ host: '127.0.0.1', port, path: '/v1/health', method: 'GET', timeout: timeoutMs }, (res) => {
295
+ const chunks = []
296
+ res.on('data', (chunk) => chunks.push(chunk))
297
+ res.on('end', () => {
298
+ try {
299
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
300
+ finish({ ok: res.statusCode === 200 && body?.ok === true, body })
301
+ } catch {
302
+ finish(null)
303
+ }
304
+ })
305
+ })
306
+ call.on('error', () => finish(null))
307
+ call.on('timeout', () => {
308
+ call.destroy()
309
+ finish(null)
310
+ })
311
+ const timer = setTimeout(() => {
312
+ call.destroy()
313
+ finish(null)
314
+ }, timeoutMs)
315
+ timer.unref?.()
316
+ call.end()
317
+ })
318
+ }
319
+
320
+ // A restart is requested at most once per process (m11421): a second POST while
321
+ // the first successor is being spawned must not start another daemon.
322
+ let restarting = false
323
+
324
+ /** The CLI entry of this package: `bin/risd.mjs` (server.js lives in lib/risd/). */
325
+ const RISD_CLI_PATH = fileURLToPath(new URL('../../bin/risd.mjs', import.meta.url))
326
+
327
+ /**
328
+ * Spawn the successor that takes over after this process exits. Detached+unref'd
329
+ * so it outlives the HTTP server, and `--wait-pid` keeps it from racing us for the
330
+ * port. A failure here is deliberately silent: the page's health poll times out
331
+ * and tells the user to restart by hand.
332
+ */
333
+ function spawnRestartSuccessor() {
334
+ try {
335
+ const child = spawn(process.execPath, [RISD_CLI_PATH, 'serve', '--wait-pid', String(process.pid)], {
336
+ detached: true,
337
+ stdio: 'ignore',
338
+ env: process.env,
339
+ cwd: process.cwd(),
340
+ })
341
+ child.unref()
342
+ } catch { /* the page reports the timeout */ }
343
+ }
344
+
345
+ /**
346
+ * Start the daemon.
347
+ *
348
+ * Never throws for the three expected outcomes of a race — the caller maps them
349
+ * to exit codes: `already-running` (0), `api-mismatch` (3), `port-busy` (4).
350
+ *
351
+ * @param options - `{ home, port, version, onShutdown }`.
352
+ * @returns `{ ok, code?, server?, port?, state?, stop? }`.
353
+ */
354
+ export async function startRisd({ home, port = DEFAULT_RISD_PORT, version = '0.0.0', onShutdown = null, teardownTimeoutMs = 5000, teardown = null } = {}) {
355
+ // A predecessor may have shut down handing the network over (Phase 1b P6). Read
356
+ // its note before this daemon writes its own state file on top of it.
357
+ const previousState = readRisdState(home)
358
+ // Session policy: when the last lease disappears the network has no consumer, so
359
+ // the owner (this daemon) tears it down — in the documented order git → bridge →
360
+ // engine. Phase 1b P2 only owns the engine; git/bridge teardown lands with their
361
+ // ownership (P5), and until then those steps are the plugin's.
362
+ const TEARDOWN_DELAY_MS = 300
363
+ let teardownTimer = null
364
+ /**
365
+ * Take the network down in the documented order: git entry → system-level
366
+ * bridge → engine. Each step is best-effort and idempotent; the point is that a
367
+ * half step never leaves a client pointing at a listener that is already gone.
368
+ */
369
+ async function teardownNetwork(cwd) {
370
+ try { await clearGitProxy() } catch { /* best effort */ }
371
+ try { await serializeBridge(() => stopRedirector()) } catch { /* best effort */ }
372
+ if (cwd !== null) {
373
+ try { await stopProxy(cwd) } catch { /* best effort */ }
374
+ }
375
+ }
376
+ function scheduleTeardown() {
377
+ if (leases.count() > 0) return
378
+ if (engineCwd === null && heartbeat === null) return
379
+ if (teardownTimer !== null) return
380
+ teardownTimer = setTimeout(() => {
381
+ teardownTimer = null
382
+ void (async () => {
383
+ if (leases.count() > 0) return // someone came back
384
+ // Per-resource policy: "follow dsh" stops it with the last window; the
385
+ // daemon-owned ones stay until the daemon itself stops (or forever).
386
+ if (lifecycle.debug.followDsh === true) await debug.stopAll().catch(() => {})
387
+ if (lifecycle.programs.followDsh === true) await stopAllPrograms()
388
+ const cwd = engineCwd
389
+ if (lifecycle.proxy.followDsh === true) {
390
+ await teardownNetwork(cwd)
391
+ if (engineCwd === cwd) engineCwd = null
392
+ }
393
+ // Idle exit (not an immediate one): a window may release its lease and
394
+ // re-take it a moment later; the daemon only retires after the configured
395
+ // idle window with nothing left to serve.
396
+ if (leases.count() === 0 && engineCwd === null) scheduleIdleExit()
397
+ })()
398
+ }, TEARDOWN_DELAY_MS)
399
+ teardownTimer.unref?.()
400
+ }
401
+ const leases = createLeaseRegistry({ onGone: () => scheduleTeardown() })
402
+ // JDWP sessions live here too (Phase 2-lite P3): a single socket to one JVM, so a
403
+ // dsh restart must not drop it and a second window must not attach over it.
404
+ const debug = createDebugEngine({ home })
405
+ // Workspaces the daemon has served at least one request for. The own page has no
406
+ // dsh session to ask, so it offers these as shortcuts (in memory: a restart
407
+ // simply starts the list over).
408
+ const workspaces = new Set()
409
+ /** Remember one workspace for the maintenance page (cap keeps the page honest). */
410
+ function rememberWorkspace(cwd) {
411
+ if (typeof cwd !== 'string' || !cwd.startsWith('/')) return
412
+ if (workspaces.has(cwd)) return
413
+ workspaces.add(cwd)
414
+ while (workspaces.size > 8) workspaces.delete(workspaces.values().next().value)
415
+ }
416
+ // One debug action at a time: attach/detach and stepping share the JDWP socket.
417
+ let debugOp = Promise.resolve()
418
+ /** Queue a debug action behind the previous one (order matters for stepping). */
419
+ function serializeDebug(task) {
420
+ const run = debugOp.then(task, task)
421
+ debugOp = run.then(() => undefined, () => undefined)
422
+ return run
423
+ }
424
+ const IDLE_EXIT_MS = 10 * 60 * 1000
425
+ // Which resources follow a dsh session, and which follow this daemon. Read at
426
+ // start, updated by POST /v1/config; the rules below are the only readers.
427
+ const lifecycleRead = readLifecycle(home)
428
+ let lifecycle = lifecycleRead.value
429
+ // A lifecycle file the daemon could not parse is not fatal: defaults run, and
430
+ // GET /v1/config reports the parse errors (read fresh on every GET so a hand
431
+ // edit shows up without a restart).
432
+ let idleTimer = null
433
+ function cancelIdleExit() {
434
+ if (idleTimer === null) return
435
+ clearTimeout(idleTimer)
436
+ idleTimer = null
437
+ }
438
+ function scheduleIdleExit() {
439
+ // "daemon follows dsh = false" means: stay up until someone stops me.
440
+ if (lifecycle.daemon.followDsh !== true) return
441
+ if (idleTimer !== null) return
442
+ idleTimer = setTimeout(() => {
443
+ idleTimer = null
444
+ // A daemon opened from the maintenance page has no lease at all, yet may be
445
+ // supervising programs or a debug session: idling out would kill them.
446
+ void hasActiveWork().then((active) => {
447
+ // An owned engine means the network is a service (proxy.followDsh=false) or
448
+ // somebody is using it without a lease: retiring would tear it down, which
449
+ // is exactly what "follow daemon" promised not to do (review A2-P2-3).
450
+ if (!active && engineCwd === null) return stop()
451
+ scheduleIdleExit()
452
+ return undefined
453
+ })
454
+ }, IDLE_EXIT_MS)
455
+ idleTimer.unref?.()
456
+ }
457
+
458
+ /** Anything a "stop the daemon" would have to kill: running programs or JDWP. */
459
+ async function hasActiveWork() {
460
+ if (debug.size > 0) return true
461
+ for (const cwd of workspaces) {
462
+ if (!existsSync(cwd)) continue
463
+ try {
464
+ const listed = await listPrograms(cwd, {})
465
+ if (listed.programs.some((row) => row.running !== null && row.running !== undefined && row.running.alive === true)) return true
466
+ } catch { /* an unreadable workspace cannot be running anything we know */ }
467
+ }
468
+ return false
469
+ }
470
+
471
+ /**
472
+ * Stop every program this daemon supervises (the ones with a live `<log>.pid`).
473
+ * Called only for a real shutdown, never for a handoff: a successor keeps them.
474
+ */
475
+ async function stopAllPrograms() {
476
+ const cwds = new Set(workspaces)
477
+ if (typeof engineCwd === 'string' && engineCwd !== '') cwds.add(engineCwd)
478
+ for (const cwd of cwds) {
479
+ if (!existsSync(cwd)) continue
480
+ try {
481
+ const listed = await listPrograms(cwd, {})
482
+ for (const row of listed.programs) {
483
+ if (row.running === null || row.running === undefined || row.running.alive !== true) continue
484
+ try { await stopProgramByKey(cwd, row.id, { dir: listed.dir }) } catch { /* keep going: one stuck program must not block the rest */ }
485
+ }
486
+ } catch { /* the workspace may have vanished */ }
487
+ }
488
+ }
489
+ const startedAt = new Date().toISOString()
490
+ // The daemon code the page will render: captured NOW, because Node caches the
491
+ // module graph for the life of the process (see build.js).
492
+ const uiBuildLoaded = buildStamp()
493
+ const token = newRisdToken()
494
+ // The workspace the engine was last started for. Kept in memory on purpose: it
495
+ // is ownership evidence for this daemon instance, not durable configuration
496
+ // (a restart re-discovers the engine by pidfile and reports owned:false until
497
+ // someone starts/stops it again).
498
+ let engineCwd = null
499
+ // Last background enforcement reload (POST /v1/proxy hands the slow part off, so a
500
+ // save returns in milliseconds instead of waiting ~8s for two PowerShell probes).
501
+ let bridgeReloadState = { at: 0, ok: true, note: '' }
502
+ // The daemon is the heartbeat writer once it owns the bridge: the elevated
503
+ // watchdog tears the bridge down when the file is older than 20 s, and a plugin
504
+ // that is closing (Ctrl+C) must no longer be the one keeping it alive.
505
+ let heartbeat = null
506
+ // Engine operations are serialized: two windows pressing 启动 must not race the
507
+ // pidfile (startProxy is idempotent, but stop-after-start must stay ordered).
508
+ let engineOp = Promise.resolve()
509
+ /**
510
+ * Queue one engine operation behind the previous one. A rejected task must not
511
+ * poison the chain: without `then(task, task)` one start failure turned every
512
+ * later engine control into an immediate 500 (review A-P1-1).
513
+ * @param {Function} task - async work.
514
+ * @returns {Promise<any>} the task's own result.
515
+ */
516
+ function serializeEngine(task) {
517
+ const run = engineOp.then(task, task)
518
+ engineOp = run.then(() => undefined, () => undefined)
519
+ return run
520
+ }
521
+ // Program start/stop share one queue so two clicks cannot spawn the same row twice.
522
+ let programOp = Promise.resolve()
523
+ // Bridge (ProxyBridge) operations are serialized too (E8): a rule reload and a
524
+ // stop are two single-file handshakes with the elevated watchdog, and running
525
+ // them concurrently can reload a profile the other side is already tearing down.
526
+ let bridgeOp = Promise.resolve()
527
+ /**
528
+ * Queue one bridge operation behind the previous one.
529
+ * @param {Function} task - async work; may throw, the queue keeps going.
530
+ * @returns {Promise<any>} the task's own result.
531
+ */
532
+ function serializeBridge(task) {
533
+ const run = bridgeOp.then(task, task)
534
+ bridgeOp = run.then(() => undefined, () => undefined)
535
+ return run
536
+ }
537
+
538
+ const handler = async (req, res) => {
539
+ try {
540
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
541
+ const path = url.pathname
542
+ const method = req.method ?? 'GET'
543
+
544
+ // Machine-local API: no CORS support at all. Refuse a request addressed to
545
+ // another host name (DNS rebinding) and one carrying a foreign Origin (a web
546
+ // page probing localhost). Without this, a rebound page could read the token
547
+ // from /ui and drive the daemon (review A-P1-4).
548
+ if (!isLoopbackHost(req)) return fail(res, 403, 'forbidden', 'this API answers loopback requests only')
549
+ if (typeof req.headers.origin === 'string' && req.headers.origin !== '' && !isLoopbackOrigin(req.headers.origin)) {
550
+ return fail(res, 403, 'forbidden', 'cross-origin requests are not allowed')
551
+ }
552
+
553
+ if (path === '/v1/health') {
554
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET only')
555
+ return json(res, 200, {
556
+ ok: true,
557
+ apiVersion: RISD_API_VERSION,
558
+ version,
559
+ pid: process.pid,
560
+ startedAt,
561
+ // Identifies THIS daemon process to a page that embedded the value at
562
+ // /ui load time. A restart (new process, new token) always changes it, so
563
+ // the page can reload itself instead of answering 401 forever (review A3-P1-1).
564
+ instance: startedAt,
565
+ uptimeMs: Date.now() - Date.parse(startedAt),
566
+ state: 'ready',
567
+ side: process.platform,
568
+ port: server.address()?.port ?? port,
569
+ home,
570
+ leases: { count: leases.count() },
571
+ engine: engineSummary(),
572
+ ui: '/ui',
573
+ // `loaded` names the code this process runs, `disk` the code a restart
574
+ // would load; the page reloads itself when they diverge in the first way
575
+ // and nudges for a restart in the second (review m09693).
576
+ uiBuild: { loaded: uiBuildLoaded, disk: buildStamp() },
577
+ heartbeat: heartbeat !== null,
578
+ janitor: { armed: janitorStatus().running === true, ownerPid: process.pid },
579
+ })
580
+ }
581
+
582
+ if ((path === '/ui' || path === '/ui/') && method === 'GET') {
583
+ // The only unauthenticated page: served to a local browser only, with the
584
+ // token inlined. Anything able to load it can read risd.json anyway.
585
+ if (!isLoopbackHost(req)) return fail(res, 403, 'forbidden', 'this page answers loopback requests only')
586
+ const html = risdUiHtml({ token, version, home, apiVersion: RISD_API_VERSION, uiBuild: { loaded: uiBuildLoaded }, uiInstance: startedAt })
587
+ res.writeHead(200, {
588
+ 'content-type': 'text/html; charset=utf-8',
589
+ 'cache-control': 'no-store',
590
+ 'content-length': Buffer.byteLength(html),
591
+ // Loopback page holding the daemon token: never frame it, never let it
592
+ // load anything but loopback (the IDE tab embeds dsh) (review C-P2-5).
593
+ 'x-frame-options': 'DENY',
594
+ 'x-content-type-options': 'nosniff',
595
+ // The IDE tab embeds the dsh host in a frame; without this the frame's
596
+ // navigator.clipboard.writeText is rejected by permissions policy and a
597
+ // 「复制文件路径」 would surface as a background-task error (m09396 ③).
598
+ 'permissions-policy': 'clipboard-write=*, clipboard-read=*',
599
+ 'referrer-policy': 'no-referrer',
600
+ 'content-security-policy': [
601
+ "default-src 'none'",
602
+ "script-src 'unsafe-inline'",
603
+ "style-src 'unsafe-inline'",
604
+ 'img-src data:',
605
+ 'connect-src http://127.0.0.1:* http://localhost:*',
606
+ 'frame-src http://127.0.0.1:* http://localhost:*',
607
+ "base-uri 'none'",
608
+ "form-action 'none'",
609
+ "frame-ancestors 'none'",
610
+ ].join('; '),
611
+ })
612
+ res.end(html)
613
+ return undefined
614
+ }
615
+
616
+ if (!tokenMatches(token, req.headers.authorization)) {
617
+ return fail(res, 401, 'unauthorized', 'missing or invalid bearer token (read risd.json)')
618
+ }
619
+ if (String(req.headers[API_VERSION_HEADER] ?? '') !== String(RISD_API_VERSION)) {
620
+ return fail(res, 409, 'api-mismatch', `client speaks apiVersion ${req.headers[API_VERSION_HEADER] ?? 'none'}, daemon speaks ${RISD_API_VERSION}`)
621
+ }
622
+
623
+ if (path === '/v1/workspaces' && method === 'GET') {
624
+ return json(res, 200, { ok: true, workspaces: [...workspaces] })
625
+ }
626
+
627
+ if (path === '/v1/dsh' && method === 'GET') {
628
+ // Which workspaces have a live dsh window? The plugin keeps dsh-window.json
629
+ // as an upserted list (origin + sessionId per workspace), so one daemon page
630
+ // can switch between workspaces' IDE instead of opening one page per cwd.
631
+ let windows = []
632
+ try {
633
+ const parsed = JSON.parse(readFileSync(join(home, DSH_WINDOW_FILENAME), 'utf8'))
634
+ if (Array.isArray(parsed?.windows)) windows = parsed.windows
635
+ } catch { /* absent or rotated away: no dsh */ }
636
+ const now = Date.now()
637
+ let droppedAt = 0
638
+ const live = windows
639
+ .filter((row) => row !== null && typeof row === 'object' && typeof row.url === 'string' && row.url !== '')
640
+ // The page hands this URL to window.open(); anything but a loopback
641
+ // http(s) origin would let a crafted dsh-window.json point the IDE tab
642
+ // somewhere else (review A-P2-10).
643
+ .filter((row) => /^https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|$)/i.test(row.url))
644
+ .map((row) => {
645
+ const at = Date.parse(String(row.at ?? ''))
646
+ // A timestamp far in the future made `now - at` clamp to 0, so the row
647
+ // stayed "live" for as long as the clock skew lasted (review A2-P2-15);
648
+ // non-finite rows were pruned before anyone could see them (A2-P2-16).
649
+ // Both are treated as junk rather than as fresh.
650
+ const future = Number.isFinite(at) && at > now + 5 * 60_000
651
+ // A numeric `at` (epoch ms is not what the writer stores) and a missing
652
+ // or unparsable one are all junk for the same reason: they cannot be
653
+ // ordered against now. Count them so a caller can tell "no dsh" from
654
+ // "dsh wrote something unusable" (review A3-P2-6).
655
+ if (!Number.isFinite(at) || future) droppedAt += 1
656
+ return {
657
+ cwd: typeof row.cwd === 'string' ? row.cwd : '',
658
+ sessionId: typeof row.sessionId === 'string' ? row.sessionId : '',
659
+ url: row.url,
660
+ ageMs: Number.isFinite(at) && !future ? Math.max(0, now - at) : DSH_WINDOW_RETAIN_MS + 1,
661
+ }
662
+ })
663
+ .map((row) => Object.assign(row, { live: row.ageMs <= DSH_WINDOW_LIVE_MS }))
664
+ .filter((row) => row.ageMs <= DSH_WINDOW_RETAIN_MS)
665
+ // Live entries first, then most-recently-seen: the first row is the one an
666
+ // iframe deep link opens by default.
667
+ .sort((a, b) => (a.live === b.live ? a.ageMs - b.ageMs : a.live ? -1 : 1))
668
+ if (live.length === 0) {
669
+ return json(res, 200, { ok: true, available: false, windows: [], dropped: droppedAt, reason: 'dsh 未运行(没有记住的工作区窗口)' })
670
+ }
671
+ const newest = live[0]
672
+ return json(res, 200, {
673
+ ok: true,
674
+ available: true,
675
+ url: newest.url,
676
+ sessionId: newest.sessionId,
677
+ cwd: newest.cwd,
678
+ windows: live,
679
+ dropped: droppedAt,
680
+ })
681
+ }
682
+
683
+ if (path === '/v1/proxy/ping' && method === 'GET') {
684
+ // Reachability of the configured SOCKS upstream, for the status chip on the
685
+ // proxy tab. Query overrides let the page test an edited-but-unsaved value.
686
+ const stored = readProxyConfig(url.searchParams.get('cwd') ?? home).socks
687
+ const host = url.searchParams.get('host') ?? stored.host
688
+ const rawPort = url.searchParams.get('port')
689
+ const port = rawPort === null ? stored.port : Number(rawPort)
690
+ const result = await pingSocks({ host, port })
691
+ return json(res, 200, result)
692
+ }
693
+
694
+ if (path === '/v1/proxybridge' && method === 'GET') {
695
+ return json(res, 200, proxyBridgeStatus())
696
+ }
697
+
698
+ if (path === '/v1/proxybridge/download' && method === 'POST') {
699
+ // Fetching/installing the component is user-visible work: keep the daemon
700
+ // from idling out from under the page while it runs (review A3-P2-3).
701
+ cancelIdleExit()
702
+ // The archive is ~1 MB and installs atomically; answering immediately and
703
+ // letting the page poll keeps a slow mirror from holding the request open.
704
+ // A body is optional here: `{force:true}` re-fetches even when the cached
705
+ // copy still verifies, which is what 「重新下载」 needs.
706
+ const forceBody = await readBody(req).catch(() => '')
707
+ let force = false
708
+ if (typeof forceBody === 'string' && forceBody.trim() !== '') {
709
+ try {
710
+ const parsed = JSON.parse(forceBody)
711
+ force = parsed !== null && typeof parsed === 'object' && parsed.force === true
712
+ } catch { force = false }
713
+ }
714
+ startBundleDownload(force)
715
+ return json(res, 200, proxyBridgeStatus())
716
+ }
717
+
718
+ if (path === '/v1/proxybridge/upload' && method === 'POST') {
719
+ cancelIdleExit()
720
+ let bytes
721
+ try {
722
+ bytes = await readBodyBytes(req, MAX_TGZ_BYTES)
723
+ } catch (error) {
724
+ if (error !== null && typeof error === 'object' && error.code === 'too-large') {
725
+ return fail(res, 413, 'too-large', `压缩包超过 ${MAX_TGZ_BYTES} 字节上限`)
726
+ }
727
+ if (error !== null && typeof error === 'object' && error.code === 'timeout') {
728
+ return fail(res, 408, 'timeout', '上传超时:15 秒内没有收完压缩包')
729
+ }
730
+ return fail(res, 400, 'bad-request', error instanceof Error ? error.message : String(error))
731
+ }
732
+ const settings = readBundleSettings()
733
+ const expectedSha256 = bundleExpectedSha256(settings)
734
+ let result
735
+ try {
736
+ result = installFromTgz({ home: proxyHomeDir(), bytes, expectedSha256 })
737
+ } catch (error) {
738
+ // A digest mismatch is a different repair instruction than a malformed
739
+ // archive: the caller must see which digest was expected (review A3-P2-7).
740
+ if (error !== null && typeof error === 'object' && error.code === 'hash-mismatch') {
741
+ return json(res, 400, {
742
+ ok: false,
743
+ code: 'hash-mismatch',
744
+ message: error instanceof Error ? error.message : String(error),
745
+ expected: error.expected ?? expectedSha256,
746
+ actual: error.actual ?? null,
747
+ })
748
+ }
749
+ return json(res, 400, { ok: false, code: 'bad-bundle', message: error instanceof Error ? error.message : String(error), hint: '需要一个包含 8 个 ProxyBridge 文件的 .tgz' })
750
+ }
751
+ if (result.ok !== true) {
752
+ return json(res, 400, {
753
+ ok: false,
754
+ code: result.code ?? 'bad-bundle',
755
+ message: result.error,
756
+ hint: result.hint,
757
+ expected: result.expected ?? expectedSha256,
758
+ actual: result.actual ?? null,
759
+ })
760
+ }
761
+ const uploadedFiles = Array.isArray(result.files) ? result.files : []
762
+ return json(res, 200, {
763
+ ok: true,
764
+ installed: true,
765
+ dir: result.dir,
766
+ files: uploadedFiles,
767
+ fileCount: uploadedFiles.length,
768
+ sha256: result.sha256 ?? null,
769
+ expectedSha256,
770
+ verified: expectedSha256 === '' || result.sha256 === expectedSha256,
771
+ })
772
+ }
773
+
774
+ if (path === '/v1/proxy/log' && method === 'GET') {
775
+ const bytes = Math.min(Math.max(Number(url.searchParams.get('bytes') ?? 40960) || 40960, 1024), 256 * 1024)
776
+ const logPath = proxyLogPath()
777
+ return json(res, 200, { ok: true, path: logPath, text: readTail(logPath, bytes) })
778
+ }
779
+
780
+ if (path === '/v1/debug' && method === 'POST') {
781
+ const parsed = parseJson(await readBody(req))
782
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
783
+ const action = String(parsed.action ?? '')
784
+ const needsCwd = action !== 'sessions' && action !== 'detach' && action !== 'events'
785
+ if (needsCwd) {
786
+ const cwd = absoluteCwd(parsed.cwd)
787
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
788
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
789
+ rememberWorkspace(cwd)
790
+ parsed.cwd = cwd
791
+ }
792
+ if (action === 'start') cancelIdleExit()
793
+ const result = await serializeDebug(() => debug.run(parsed))
794
+ return json(res, 200, Object.assign({ ok: true }, result))
795
+ }
796
+
797
+ if (path === '/v1/proxy' && method === 'POST') {
798
+ // The write half moved here in Phase 1b P4: the daemon is the only writer
799
+ // of the machine-wide table, so two windows (or a window and the CLI) can no
800
+ // longer interleave a read-modify-write and silently drop rows.
801
+ const parsed = parseJson(await readBody(req))
802
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
803
+ const cwd = parsed.cwd === undefined || parsed.cwd === null ? home : absoluteCwd(parsed.cwd)
804
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
805
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
806
+ const incoming = parsed.config !== null && typeof parsed.config === 'object' ? parsed.config : {}
807
+ const stored = readProxyConfig(cwd)
808
+ const currentRevision = risdConfigRevision(stored)
809
+ const baseRevision = typeof parsed.revision === 'string' ? parsed.revision.trim() : ''
810
+ if (baseRevision !== '' && baseRevision !== currentRevision) {
811
+ return json(res, 409, {
812
+ ok: false,
813
+ conflict: true,
814
+ code: 'conflict',
815
+ message: '规则表已在别处被修改,本次改动未写入',
816
+ revision: currentRevision,
817
+ // The design promises the losing writer a fresh view so a direct API
818
+ // client can merge without a second round trip (review A-P2-1).
819
+ view: await risdProxyView(cwd),
820
+ })
821
+ }
822
+ const rows = Array.isArray(incoming.rules)
823
+ ? incoming.rules
824
+ .filter((rule) => rule !== null && typeof rule === 'object')
825
+ .map((rule) => Object.assign({}, rule, { workspace: rule.workspace ?? cwd }))
826
+ : []
827
+ const keptIds = new Set(rows.map((rule) => String(rule.id ?? '')))
828
+ // One machine-wide table, and this payload IS the table: a row the caller did
829
+ // not send is gone (m10585). The old protocol let a client declare which
830
+ // sources it spoke for, which kept rows alive that no UI could show — the
831
+ // 「别的工作区还配着」 state the user asked us to drop. Callers that only own
832
+ // a slice of the table (yds) therefore read first and PUT the complete set.
833
+ //
834
+ // `replaceRulesFrom` is kept as a one-release compatibility shim: an older
835
+ // dsh-ris-yds sends only its own rows, and treating that as a complete table
836
+ // would delete the user's rows. New callers omit it; the panel never sends it.
837
+ let legacySource = null
838
+ if (parsed.replaceRulesFrom !== undefined) {
839
+ const sources = Array.isArray(parsed.replaceRulesFrom) ? parsed.replaceRulesFrom : []
840
+ if (sources.length > 0 && sources.every((source) => source === 'yds')) legacySource = 'yds'
841
+ }
842
+ const retired = new Set(
843
+ stored.rules
844
+ .filter((rule) => {
845
+ if (keptIds.has(String(rule.id ?? ''))) return false
846
+ return legacySource === null ? true : rule.source === legacySource
847
+ })
848
+ .map((rule) => rule.id),
849
+ )
850
+ const written = mergeConfigs(
851
+ Object.assign({}, stored, { rules: stored.rules.filter((rule) => !retired.has(rule.id)) }),
852
+ { socks: incoming.socks, listenPort: incoming.listenPort, rules: rows, workspace: cwd },
853
+ )
854
+ writeProxyConfig(cwd, written)
855
+ // Clean up what the OLD table applied before the new one takes effect. The
856
+ // git entry is host-scoped and nothing else rewrites it on save, so a changed
857
+ // or deleted git rule used to leave terminals pointed at a dead tunnel.
858
+ const git = await serializeBridge(() => reconcileGitProxy({ cwd, host: typeof parsed.gitHost === 'string' ? parsed.gitHost : '' }))
859
+ // Revoke the previous enforcement as part of the switch: ProxyBridge parses
860
+ // its profile only at start, so a reload that fails would otherwise keep the
861
+ // OLD rules intercepting while the dialog claims the save worked. The wait is
862
+ // real (two synchronous PowerShell probes on WSL ≈ 8s), so the save returns
863
+ // first and the switch runs right after it; the page reads the outcome from
864
+ // `bridge` on its next load (m10585). Saves are serialized by serializeBridge,
865
+ // and each reload re-reads the file, so a burst of edits still lands on the
866
+ // last table.
867
+ const revoke = async (reason) => {
868
+ const stopped = await serializeBridge(() => stopRedirector())
869
+ return `${reason};${stopped.stopped === true
870
+ ? '已停止系统层拦截,避免继续按旧规则代理'
871
+ : `未能停止系统层拦截(${stopped.reason ?? '未知原因'}),旧规则可能仍在生效`}`
872
+ }
873
+ const switchEnforcement = async () => {
874
+ try {
875
+ if (redirectorStatusCached().running !== true) {
876
+ bridgeReloadState = { at: Date.now(), ok: true, note: '' }
877
+ return
878
+ }
879
+ // On Windows only the `windows` side exists; asking for `local` produced a
880
+ // permanent "skipped" note and a misleading sudo hint (review A2-P2-14).
881
+ const reloadSides = process.platform === 'win32' ? ['windows'] : ['windows', 'local']
882
+ const reload = await serializeBridge(() => reloadRedirectorsWithProfile(cwd, { sides: reloadSides }))
883
+ const done = Array.isArray(reload.reloaded) ? reload.reloaded : []
884
+ const skipped = Array.isArray(reload.skipped) ? reload.skipped : []
885
+ if (done.length > 0) {
886
+ bridgeReloadState = { at: Date.now(), ok: true, note: '系统层拦截已按新规则自动重启' }
887
+ return
888
+ }
889
+ const note = await revoke(`系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`)
890
+ bridgeReloadState = { at: Date.now(), ok: false, note }
891
+ } catch (error) {
892
+ const note = await revoke(`系统层拦截未重载:${error?.message ?? error}`)
893
+ bridgeReloadState = { at: Date.now(), ok: false, note }
894
+ }
895
+ }
896
+ setImmediate(() => { switchEnforcement().catch(() => {}) })
897
+ return json(res, 200, {
898
+ ok: true,
899
+ revision: risdConfigRevision(written),
900
+ reloadNote: '规则已保存;系统层拦截正在后台按新规则重启',
901
+ git,
902
+ })
903
+ }
904
+
905
+ if (path === '/v1/action' && method === 'POST') {
906
+ const parsed = parseJson(await readBody(req))
907
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
908
+ const cwd = absoluteCwd(parsed.cwd)
909
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
910
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
911
+ const action = typeof parsed.action === 'string' ? parsed.action : 'status'
912
+ const gitHost = typeof parsed.gitHost === 'string' ? parsed.gitHost : undefined
913
+ let result
914
+ if (action === 'start') {
915
+ result = await serializeEngine(async () => {
916
+ const engine = await startProxy(cwd)
917
+ const redirector = await serializeBridge(() => startRedirectors())
918
+ const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
919
+ if (engine.ok === true) {
920
+ engineCwd = cwd
921
+ cancelIdleExit()
922
+ }
923
+ return Object.assign({}, engine, { redirector, git })
924
+ })
925
+ } else if (action === 'stop') {
926
+ result = await serializeEngine(async () => {
927
+ const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
928
+ const redirector = await serializeBridge(() => stopRedirector())
929
+ const stopped = await stopProxy(cwd)
930
+ if (stopped.ok === true) {
931
+ engineCwd = null
932
+ // Nothing holds the daemon open after an explicit 停止; without this
933
+ // it stayed resident until the next lease event even though the page
934
+ // was the only owner (review A3-P2-4).
935
+ if (leases.count() === 0) scheduleIdleExit()
936
+ }
937
+ return Object.assign({}, stopped, { redirector, git })
938
+ })
939
+ } else if (action === 'status') {
940
+ result = { engine: engineSummary(), redirector: redirectorStatusCached() }
941
+ } else if (action === 'git-on' || action === 'git-off') {
942
+ // The git table changes the machine config through exactly one helper,
943
+ // syncGitProxy, which records key+value so cleanup only removes our own
944
+ // entry. Direct runGitConfig calls here left no bookkeeping and could
945
+ // unset a key the current table no longer calculates (review B-P2-5).
946
+ result = await syncGitProxy({ cwd, host: gitHost, enabled: action === 'git-on' })
947
+ } else if (action === 'redirector-sync' || action === 'redirector-start') {
948
+ const { syncRedirector } = await import('../redirector.js')
949
+ result = await serializeBridge(() => syncRedirector(cwd, { start: action === 'redirector-start' }))
950
+ } else if (action === 'redirector-stop') {
951
+ result = await serializeBridge(() => stopRedirector())
952
+ } else if (action === 'redirector-restart') {
953
+ // Stop first so nothing keeps intercepting with the parsed-at-start profile,
954
+ // then start again from the profile written by the save that requested this.
955
+ result = await serializeBridge(async () => {
956
+ const stopped = await stopRedirector()
957
+ await new Promise((resolve) => setTimeout(resolve, 300))
958
+ const started = await startRedirectors()
959
+ return {
960
+ stopped,
961
+ started: started.started ?? [],
962
+ skipped: started.skipped ?? [],
963
+ running: started.running === true,
964
+ }
965
+ })
966
+ } else {
967
+ return fail(res, 400, 'bad-request', `unknown proxy action "${action}"`)
968
+ }
969
+ return json(res, 200, { ok: true, action, result })
970
+ }
971
+
972
+ if (path === '/v1/injection' && method === 'GET') {
973
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
974
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
975
+ const program = String(url.searchParams.get('program') ?? '')
976
+ if (program === '') return fail(res, 400, 'bad-request', 'program is required')
977
+ return json(res, 200, { ok: true, cwd, program, injection: injectionFor(program, readProxyConfig(cwd)) })
978
+ }
979
+
980
+ if (path === '/v1/programs') {
981
+ if (method === 'GET') {
982
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
983
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
984
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
985
+ rememberWorkspace(cwd)
986
+ const dir = String(url.searchParams.get('dir') ?? '')
987
+ const refreshRaw = url.searchParams.get('refresh')
988
+ const refresh = refreshRaw === '1' || refreshRaw === 'true'
989
+ const listed = await listPrograms(cwd, { dir, refresh })
990
+ return json(res, 200, { ok: true, cwd, dir: listed.dir, programs: listed.programs })
991
+ }
992
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'GET or POST')
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 = 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
+ // Every cwd a program is started in becomes a workspace this daemon
999
+ // supervises: "stop the daemon" walks that set and stops those programs.
1000
+ rememberWorkspace(cwd)
1001
+ const action = parsed.action
1002
+ if (action !== 'start' && action !== 'stop' && action !== 'restart') {
1003
+ return fail(res, 400, 'bad-request', 'action must be start, stop or restart')
1004
+ }
1005
+ const key = String(parsed.id ?? parsed.program ?? '')
1006
+ if (key === '') return fail(res, 400, 'bad-request', 'id is required')
1007
+ if (action !== 'stop') cancelIdleExit()
1008
+ const dir = typeof parsed.dir === 'string' ? parsed.dir : ''
1009
+ let result
1010
+ try {
1011
+ result = await (programOp = programOp.then(
1012
+ async () => (action === 'start'
1013
+ ? startProgramByKey(cwd, key, { dir })
1014
+ : action === 'stop'
1015
+ ? stopProgramByKey(cwd, key, { dir })
1016
+ : restartProgramByKey(cwd, key, { dir })),
1017
+ () => ({ ok: false, code: 'program-failed', message: 'previous program operation failed', status: 500 }),
1018
+ ))
1019
+ } catch (error) {
1020
+ return fail(res, error?.status ?? 500, error?.code ?? 'program-failed', error?.message ?? String(error))
1021
+ }
1022
+ if (result.ok !== true) return fail(res, result.status ?? 500, result.code ?? 'program-failed', result.message ?? 'program operation failed')
1023
+ return json(res, 200, Object.assign({ ok: true, action }, result))
1024
+ }
1025
+
1026
+ if (path === '/v1/programs/log') {
1027
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET only')
1028
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
1029
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1030
+ const key = String(url.searchParams.get('id') ?? '')
1031
+ if (key === '') return fail(res, 400, 'bad-request', 'id is required')
1032
+ const dir = String(url.searchParams.get('dir') ?? '')
1033
+ const offsetRaw = url.searchParams.get('offset')
1034
+ const offset = offsetRaw === null || offsetRaw === '' ? null : Number(offsetRaw)
1035
+ const bytesRaw = Number(url.searchParams.get('bytes') ?? '')
1036
+ const result = await readProgramLog(cwd, key, {
1037
+ dir,
1038
+ offset: Number.isFinite(offset) ? offset : null,
1039
+ bytes: Number.isFinite(bytesRaw) && bytesRaw > 0 ? bytesRaw : undefined,
1040
+ })
1041
+ if (result.ok !== true) return fail(res, result.status ?? 500, result.code ?? 'log-failed', result.message ?? 'log read failed')
1042
+ return json(res, 200, result)
1043
+ }
1044
+
1045
+ if (path === '/v1/programs/log/stream') {
1046
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET only')
1047
+ const cwd = absoluteCwd(url.searchParams.get('cwd'))
1048
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1049
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1050
+ const key = String(url.searchParams.get('id') ?? '')
1051
+ if (key === '') return fail(res, 400, 'bad-request', 'id is required')
1052
+ const dir = String(url.searchParams.get('dir') ?? '')
1053
+ const listed = await listPrograms(cwd, { dir })
1054
+ const program = findProgram(listed.programs, key)
1055
+ if (program === null) return fail(res, 404, 'no-program', `未找到程序「${key}」`)
1056
+ const offsetRaw = url.searchParams.get('offset')
1057
+ const offset = offsetRaw === null || offsetRaw === '' ? null : Number(offsetRaw)
1058
+ const bytesRaw = Number(url.searchParams.get('bytes') ?? '')
1059
+ res.writeHead(200, {
1060
+ 'content-type': 'text/event-stream; charset=utf-8',
1061
+ 'cache-control': 'no-cache, no-transform',
1062
+ connection: 'keep-alive',
1063
+ 'x-accel-buffering': 'no',
1064
+ })
1065
+ let follow = null
1066
+ follow = startLogFollow(program, {
1067
+ offset: Number.isFinite(offset) ? offset : null,
1068
+ bytes: Number.isFinite(bytesRaw) && bytesRaw > 0 ? bytesRaw : undefined,
1069
+ }, (frame) => {
1070
+ if (frame.type === 'ping') { res.write(': ping\n\n'); return }
1071
+ res.write(`event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`)
1072
+ if (frame.type === 'end') {
1073
+ follow?.stop()
1074
+ res.end()
1075
+ }
1076
+ })
1077
+ req.on('close', () => follow.stop())
1078
+ return
1079
+ }
1080
+
1081
+ if (path === '/v1/status' || path === '/v1/proxy') {
1082
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1083
+ // The rule table is machine-wide, so the page may omit cwd; a workspace is
1084
+ // only a label kept on rows, and the daemon's home is a valid stand-in.
1085
+ const rawCwd = url.searchParams.get('cwd')
1086
+ const asked = rawCwd === null ? null : absoluteCwd(rawCwd)
1087
+ if (rawCwd !== null && asked === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1088
+ // /v1/proxy is machine-wide (the page's rule editor omits cwd); /v1/status
1089
+ // still needs to know whose programs to report, so it stays strict.
1090
+ if (path === '/v1/status' && asked === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1091
+ const cwd = asked ?? home
1092
+ if (asked !== null) rememberWorkspace(asked)
1093
+ const view = await risdProxyView(cwd)
1094
+ // `bridge` is the outcome of the background reload a save kicked off, so the
1095
+ // page can report a failed switch without the save having to wait for it.
1096
+ return json(res, 200, Object.assign({}, view, { daemon: daemonSummary(), bridge: bridgeReloadState }))
1097
+ }
1098
+
1099
+ if (path === '/v1/engine') {
1100
+ if (method === 'GET') {
1101
+ const cwd = absoluteCwd(url.searchParams.get('cwd')) ?? engineCwd
1102
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1103
+ const status = await proxyStatus(cwd)
1104
+ return json(res, 200, {
1105
+ ok: true,
1106
+ cwd,
1107
+ engine: {
1108
+ owned: engineCwd !== null,
1109
+ running: status.running,
1110
+ pid: status.pid,
1111
+ listen: status.listen,
1112
+ logPath: status.logPath,
1113
+ socksUrl: status.socksUrl,
1114
+ },
1115
+ })
1116
+ }
1117
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1118
+ const parsed = parseJson(await readBody(req))
1119
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1120
+ // The maintenance page has no dsh session, so it may start/stop without a
1121
+ // workspace: the engine is machine-scoped and only needs an existing cwd
1122
+ // for the pidfile, so the daemon home is a fine stand-in.
1123
+ const cwd = parsed.cwd === undefined || parsed.cwd === null ? home : absoluteCwd(parsed.cwd)
1124
+ if (cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1125
+ const action = parsed.action
1126
+ if (action !== 'start' && action !== 'stop') return fail(res, 400, 'bad-request', 'action must be start or stop')
1127
+ if (!existsSync(cwd)) return fail(res, 400, 'bad-request', `cwd does not exist: ${cwd}`)
1128
+ const result = await serializeEngine(async () => {
1129
+ if (action === 'start') {
1130
+ const started = await startProxy(cwd)
1131
+ if (started.ok === true) engineCwd = cwd
1132
+ return started
1133
+ }
1134
+ const stopped = await stopProxy(cwd)
1135
+ if (stopped.ok === true) engineCwd = null
1136
+ return stopped
1137
+ })
1138
+ return json(res, 200, { ok: true, cwd, action, result })
1139
+ }
1140
+
1141
+ if (path === '/v1/leases') {
1142
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'POST only')
1143
+ const parsed = parseJson(await readBody(req))
1144
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1145
+ const ownerPid = Number(parsed.ownerPid)
1146
+ if (!Number.isInteger(ownerPid) || ownerPid <= 0) return fail(res, 400, 'bad-request', 'ownerPid must be a positive integer')
1147
+ // null is the client's way of saying "no workspace" (a plugin that did not
1148
+ // have a cwd at mount time); only a wrong TYPE is a bad request.
1149
+ const cwd = parsed.cwd === undefined || parsed.cwd === null ? null : absoluteCwd(parsed.cwd)
1150
+ if (parsed.cwd !== undefined && parsed.cwd !== null && cwd === null) return fail(res, 400, 'bad-request', 'cwd must be an absolute path')
1151
+ const sessionId = parsed.sessionId === undefined ? null : String(parsed.sessionId)
1152
+ cancelIdleExit()
1153
+ const lease = leases.acquire({ ownerPid, sessionId, cwd })
1154
+ return json(res, 200, { ok: true, lease })
1155
+ }
1156
+
1157
+ const leaseMatch = /^\/v1\/leases\/([^/]+)$/.exec(path)
1158
+ if (leaseMatch !== null) {
1159
+ if (method !== 'DELETE') return fail(res, 405, 'method-not-allowed', 'DELETE only')
1160
+ const released = leases.release(decodeURIComponent(leaseMatch[1]))
1161
+ if (released) {
1162
+ // The window that owned debug sessions is gone. Drop its ownership so the
1163
+ // next window is not locked out of every mutating debug action
1164
+ // (review B-P1-1).
1165
+ if (leases.count() === 0) { try { debug.releaseOwners() } catch { /* ignore */ } }
1166
+ scheduleTeardown()
1167
+ }
1168
+ return json(res, 200, { ok: true, released })
1169
+ }
1170
+
1171
+ if (path === '/v1/config') {
1172
+ if (method === 'POST') {
1173
+ const parsed = parseJson(await readBody(req))
1174
+ if (parsed === undefined) return fail(res, 400, 'bad-request', 'body must be a JSON object')
1175
+ if (parsed.lifecycle === undefined) return fail(res, 400, 'bad-request', 'lifecycle is required')
1176
+ // `null`/`[]` used to be written back as the defaults, i.e. a request with
1177
+ // no usable value silently reset the policy (review A2-P2-2).
1178
+ if (parsed.lifecycle === null || Array.isArray(parsed.lifecycle) || typeof parsed.lifecycle !== 'object') {
1179
+ return fail(res, 400, 'bad-request', 'lifecycle 必须是对象')
1180
+ }
1181
+ // Merge over what is on DISK, not over the copy this process loaded:
1182
+ // otherwise a hand edit made while the daemon runs is overwritten by the
1183
+ // in-memory copy on the next checkbox save (review A3-P2-6). The strict
1184
+ // merge copies unknown resources/keys through so normalizeLifecycle is
1185
+ // the one place that rejects them (review A3-P1-2).
1186
+ const disk = readLifecycle(home)
1187
+ const written = writeLifecycle(home, mergeLifecycle(disk.value, parsed.lifecycle))
1188
+ if (written.errors.length > 0) return fail(res, 400, 'bad-request', written.errors.join('; '))
1189
+ lifecycle = written.value
1190
+ // Re-arm the idle timer with the new policy: turning "follow dsh" off
1191
+ // must not leave a timer armed from before the change.
1192
+ if (lifecycle.daemon.followDsh !== true) cancelIdleExit()
1193
+ else if (leases.count() === 0 && engineCwd === null) scheduleIdleExit()
1194
+ return json(res, 200, { ok: true, lifecycle, configPath: join(home, 'risd-lifecycle.json') })
1195
+ }
1196
+ if (method !== 'GET') return fail(res, 405, 'method-not-allowed', 'GET or POST')
1197
+ return json(res, 200, {
1198
+ ok: true,
1199
+ apiVersion: RISD_API_VERSION,
1200
+ keepPolicy: 'session',
1201
+ // Report the constant the timers actually use; the old literal was a
1202
+ // second source of truth and `engineRestart` described nothing that
1203
+ // exists in the daemon (review A-P2-3).
1204
+ idleExitMs: IDLE_EXIT_MS,
1205
+ lifecycle,
1206
+ lifecycleErrors: readLifecycle(home).errors ?? [],
1207
+ })
1208
+ }
1209
+
1210
+ // m11421: 维护页源码比进程新时,页面上的按钮是「重启并刷新」——光刷新救不了
1211
+ // 旧代码(模块图在进程内存里)。这里让 daemon 自己交接:先起一个带 --wait-pid
1212
+ // 的后继(等本进程退出后才 bind 端口,避免 already-running),再走 handoff 的
1213
+ // stop 路径(保留代理引擎/桥接,由后继收养)。
1214
+ if (path === '/v1/restart') {
1215
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'POST only')
1216
+ const already = restarting
1217
+ restarting = true
1218
+ json(res, 200, { ok: true, restarting: true, pid: process.pid })
1219
+ if (!already) {
1220
+ setImmediate(() => {
1221
+ spawnRestartSuccessor()
1222
+ if (onShutdown !== null) onShutdown(true)
1223
+ })
1224
+ }
1225
+ return undefined
1226
+ }
1227
+
1228
+ if (path === '/v1/shutdown') {
1229
+ if (method !== 'POST') return fail(res, 405, 'method-not-allowed', 'POST only')
1230
+ const parsed = parseJson(await readBody(req)) ?? {}
1231
+ const handoff = parsed.handoff === true
1232
+ json(res, 200, { ok: true, draining: true, handoff })
1233
+ if (onShutdown !== null) setImmediate(() => onShutdown(handoff === true))
1234
+ return undefined
1235
+ }
1236
+
1237
+ return fail(res, 404, 'not-found', `no such endpoint: ${method} ${path}`)
1238
+ } catch (error) {
1239
+ if (error instanceof DebugError) {
1240
+ const code = String(error.code ?? 'debug-failed')
1241
+ // `debug-owned` / `not-startable` are the daemon's own codes; the rest map
1242
+ // through the engine so the plugin sees the same status as before P3.
1243
+ const status = code === 'debug-owned' ? 409
1244
+ : code === 'not-startable' ? 400
1245
+ : debugErrorStatus(code)
1246
+ return fail(res, status, code, String(error.message ?? error))
1247
+ }
1248
+ const code = String(error?.code ?? '')
1249
+ const status = code === 'too-large' ? 413 : code === 'timeout' ? 408 : 500
1250
+ const reason = status === 413 ? 'too-large' : status === 408 ? 'timeout' : 'internal'
1251
+ return fail(res, status, reason, String(error?.message ?? error))
1252
+ }
1253
+ }
1254
+
1255
+ const server = createServer(handler)
1256
+ // Keep-alive sockets from a dead plugin must not delay shutdown: idle them out
1257
+ // after 1s instead of Node's 5s default.
1258
+ server.keepAliveTimeout = 1000
1259
+
1260
+ let engineInherited = false
1261
+
1262
+ function engineSummary() {
1263
+ // `owned` means "this daemon has started the engine during its lifetime"; a
1264
+ // pidfile found at startup is reported as owned:false so the plugin can still
1265
+ // show the inherited banner and offer to stop it (Phase 1a behaviour).
1266
+ try {
1267
+ const pid = proxyPid()
1268
+ return { owned: engineCwd !== null, inherited: engineInherited, pid: pid ?? 0, state: pid === null ? 'stopped' : 'running', cwd: engineCwd }
1269
+ } catch {
1270
+ return { owned: false, inherited: engineInherited, pid: 0, state: 'unknown', cwd: engineCwd }
1271
+ }
1272
+ }
1273
+
1274
+ function daemonSummary() {
1275
+ return { pid: process.pid, version, apiVersion: RISD_API_VERSION, leases: leases.count() }
1276
+ }
1277
+
1278
+ const listenResult = await new Promise((resolve) => {
1279
+ const onError = (error) => {
1280
+ server.removeListener('listening', onListening)
1281
+ resolve({ ok: false, error })
1282
+ }
1283
+ const onListening = () => {
1284
+ server.removeListener('error', onError)
1285
+ resolve({ ok: true })
1286
+ }
1287
+ server.once('error', onError)
1288
+ server.once('listening', onListening)
1289
+ server.listen(port, '127.0.0.1')
1290
+ })
1291
+
1292
+ if (!listenResult.ok) {
1293
+ const error = listenResult.error
1294
+ if (error?.code === 'EADDRINUSE') {
1295
+ const probe = await probeRisdHealth(port)
1296
+ if (probe?.ok === true && Number(probe.body?.apiVersion) === RISD_API_VERSION) {
1297
+ // Same port, different home: the other daemon is healthy but its state file
1298
+ // lives elsewhere, so two daemons would overwrite each other's token/port
1299
+ // and the plugin would talk to whichever wrote last (review A-P2-9).
1300
+ if (typeof probe.body?.home === 'string' && probe.body.home !== '' && probe.body.home !== home) {
1301
+ return { ok: false, code: 'home-mismatch', found: String(probe.body.home), home, port }
1302
+ }
1303
+ return { ok: false, code: 'already-running', pid: Number(probe.body?.pid) || 0, port }
1304
+ }
1305
+ if (probe?.ok === true) {
1306
+ return { ok: false, code: 'api-mismatch', found: Number(probe.body?.apiVersion) || 0, port }
1307
+ }
1308
+ return { ok: false, code: 'port-busy', port }
1309
+ }
1310
+ return { ok: false, code: 'listen-failed', error }
1311
+ }
1312
+
1313
+ const actualPort = server.address()?.port ?? port
1314
+ const state = {
1315
+ apiVersion: RISD_API_VERSION,
1316
+ version,
1317
+ pid: process.pid,
1318
+ port: actualPort,
1319
+ token,
1320
+ home,
1321
+ startedAt,
1322
+ url: `http://127.0.0.1:${actualPort}`,
1323
+ }
1324
+
1325
+ try {
1326
+ writeRisdState(state, home)
1327
+ } catch (error) {
1328
+ server.close()
1329
+ return { ok: false, code: 'state-write-failed', error }
1330
+ }
1331
+
1332
+ // Phase 1b P6 (handoff): the predecessor wrote down what it owned. If that engine
1333
+ // is still the one in the pidfile, adopt it instead of reporting owned:false —
1334
+ // that is the whole point of handing over: no teardown, no restart, no dropped
1335
+ // connection while the plugin restarts the daemon.
1336
+ try {
1337
+ const handoff = previousState?.handoff
1338
+ if (handoff !== null && handoff !== undefined && typeof handoff.cwd === 'string' && handoff.cwd !== '') {
1339
+ const pid = proxyPid()
1340
+ if (pid !== null && Number(handoff.enginePid) === pid) {
1341
+ engineCwd = handoff.cwd
1342
+ engineInherited = true
1343
+ }
1344
+ }
1345
+ } catch { /* adoption is best effort: the pidfile decides ownership anyway */ }
1346
+
1347
+ leases.start()
1348
+
1349
+ // Phase 1b P3: the daemon owns the bridge heartbeat and the janitor from the
1350
+ // moment it is ready. The plugin no longer writes either while it forwards.
1351
+ try {
1352
+ writeHeartbeat()
1353
+ heartbeat = setInterval(() => {
1354
+ try { writeHeartbeat() } catch { /* the watchdog decides; log is best effort */ }
1355
+ }, 3000)
1356
+ heartbeat.unref?.()
1357
+ } catch {
1358
+ heartbeat = null
1359
+ }
1360
+ try {
1361
+ armJanitor({ ownerPid: process.pid })
1362
+ } catch { /* a janitor failure must not keep the daemon from serving */ }
1363
+
1364
+ // A daemon opened from the maintenance page (or by ⧉ before the plugin has taken a
1365
+ // lease) owns nothing yet. Without arming here it never armed the idle timer at
1366
+ // all — `scheduleIdleExit` is only reached from lease teardown and POST /v1/config
1367
+ // — so every click left one more resident node process (review C2-P1-1). A lease
1368
+ // arriving right after cancels this timer again.
1369
+ if (engineCwd === null && leases.count() === 0) scheduleIdleExit()
1370
+
1371
+ // We are the machine-level owner now, so reconcile what the previous run left:
1372
+ // git entries for a dead engine, a bridge parked by us, stale pid/state files.
1373
+ // Run the startup reconcile through the engine queue: it touches the engine
1374
+ // pidfile and a user's /v1/action may already be in flight. Own pid is passed so
1375
+ // the reconcile can never delete the state file of this very daemon.
1376
+ void serializeEngine(() => reconcileStartupLeftovers({
1377
+ ownPid: process.pid,
1378
+ log: (message) => { try { process.stdout.write(`${message}\n`) } catch { /* ignore */ } },
1379
+ })).catch(() => {})
1380
+
1381
+ let stopping = false
1382
+ /**
1383
+ * Stop serving.
1384
+ * @param {{handoff?: boolean}} [options] - `handoff` = a successor will take over:
1385
+ * leave the engine, bridge, heartbeat file, janitor and state note in place.
1386
+ */
1387
+ async function stop(options = {}) {
1388
+ if (stopping) return
1389
+ stopping = true
1390
+ const handoff = options?.handoff === true
1391
+ cancelIdleExit()
1392
+ if (heartbeat !== null) {
1393
+ clearInterval(heartbeat)
1394
+ heartbeat = null
1395
+ }
1396
+ leases.stop()
1397
+ // JDWP sockets are process-local: detach before closing so a VM paused on a
1398
+ // breakpoint is resumed instead of being left frozen for the next daemon.
1399
+ // Following the daemon is not configurable (m07741): stop everything we supervise.
1400
+ await debug.stopAll().catch(() => {})
1401
+ if (handoff) {
1402
+ // Hand the network over: the successor adopts the engine pid, the bridge
1403
+ // watchdog keeps its heartbeat (20 s window), and the state note is what it
1404
+ // reads to know the engine is its own. Deliberately no teardown/disarm.
1405
+ try {
1406
+ writeRisdState(Object.assign({}, state, {
1407
+ handoff: { cwd: engineCwd, enginePid: proxyPid() ?? 0, at: new Date().toISOString() },
1408
+ }), home)
1409
+ } catch { /* best effort: the successor can still adopt by pidfile */ }
1410
+ // Keep the armed watcher from tearing the network down in the gap between
1411
+ // our exit and the successor's registration (it reads this stamp).
1412
+ try { markJanitorHandoff() } catch { /* no armed watcher: nothing to tell */ }
1413
+ server.closeIdleConnections?.()
1414
+ await new Promise((resolve) => {
1415
+ const timer = setTimeout(() => {
1416
+ server.closeAllConnections?.()
1417
+ resolve(undefined)
1418
+ }, 1500)
1419
+ timer.unref?.()
1420
+ server.close(() => {
1421
+ clearTimeout(timer)
1422
+ resolve(undefined)
1423
+ })
1424
+ })
1425
+ return
1426
+ }
1427
+ // "Stop the daemon" means stop what it supervises: JVMs first (JDWP sockets
1428
+ // were detached above), then the network layers below. A handoff skips all of
1429
+ // this — the successor adopts them.
1430
+ await stopAllPrograms()
1431
+ // Drain in-flight operations first: a start that was already running would
1432
+ // otherwise spawn an engine after teardown and leave an orphan (review A-P1-2).
1433
+ await engineOp.catch(() => {})
1434
+ await bridgeOp.catch(() => {})
1435
+ // Only remove the state file if it is still ours: a newer daemon that
1436
+ // replaced us must keep its own file.
1437
+ const current = readRisdState(home)
1438
+ if (current !== null && current.pid === process.pid) removeRisdState(home)
1439
+ // Graceful exit takes the network with it (only what THIS daemon owns: an
1440
+ // engine found in the pidfile at startup belongs to someone else and is left
1441
+ // alone). Bounded: a slow bridge probe on a WSL `/mnt/c` mount must not keep
1442
+ // `risd stop` — or the next spawn — waiting. If the bound hits, the armed
1443
+ // janitor finishes the job after this process is gone — which is why the
1444
+ // watcher is only disarmed when the teardown actually completed. Unconditional
1445
+ // disarm after a timed-out race would leave the engine/pidfile/port behind with
1446
+ // nothing left to clean them up (review A-P0-2).
1447
+ let tornDown = false
1448
+ // Following the daemon is not configurable (m07741): the proxy always goes with
1449
+ // it. Keeping a resource alive past its supervisor used to require a detached
1450
+ // heartbeat writer (D3) and would have left the machine with no page to stop it.
1451
+ await Promise.race([
1452
+ (typeof teardown === 'function' ? teardown(engineCwd) : teardownNetwork(engineCwd)).then(() => { tornDown = true }),
1453
+ new Promise((resolve) => { const timer = setTimeout(resolve, teardownTimeoutMs); timer.unref?.() }),
1454
+ ])
1455
+ engineCwd = null
1456
+ server.closeIdleConnections?.()
1457
+ await new Promise((resolve) => {
1458
+ const timer = setTimeout(() => {
1459
+ server.closeAllConnections?.()
1460
+ resolve(undefined)
1461
+ }, 1500)
1462
+ timer.unref?.()
1463
+ server.close(() => {
1464
+ clearTimeout(timer)
1465
+ resolve(undefined)
1466
+ })
1467
+ })
1468
+ if (tornDown) {
1469
+ try { disarmJanitor() } catch { /* janitor may not be armed */ }
1470
+ } else {
1471
+ // The armed watcher outlives us on purpose: it retries the cleanup once the
1472
+ // process is gone (same effect the exit hook used to provide).
1473
+ try { process.stderr.write('risd: teardown did not finish within 5s; leaving the janitor armed\n') } catch { /* detached stdio */ }
1474
+ }
1475
+ }
1476
+
1477
+ return { ok: true, server, port: actualPort, state, leases, stop }
1478
+ }