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
package/lib/index.js CHANGED
@@ -51,11 +51,11 @@
51
51
  * @module dsh-ris-ide
52
52
  */
53
53
  import { appendFile, copyFile, cp, link, lstat, mkdir, open, readdir, readFile, readlink, rename, rm, stat, symlink, truncate, writeFile } from 'node:fs/promises'
54
- import { createReadStream, createWriteStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
54
+ import { closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
55
55
  import { watch } from 'node:fs'
56
56
  import { createHash } from 'node:crypto'
57
- import { spawn } from 'node:child_process'
58
- import { homedir } from 'node:os'
57
+ import { spawn, spawnSync } from 'node:child_process'
58
+ import { homedir, tmpdir } from 'node:os'
59
59
  import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep, parse } from 'node:path'
60
60
  import { fileURLToPath } from 'node:url'
61
61
  import { pipeline } from 'node:stream/promises'
@@ -65,6 +65,37 @@ import {
65
65
  createDebugSessions, DebugError, debugErrorStatus, jdwpAgentArg, allocateDebugPort, waitForTcp,
66
66
  waitForJdwpListening, toJsonSafe,
67
67
  } from './debug/engine.js'
68
+ import { allowList, autoRules, engineSide, gitProxyPlan, injectionFor, isSocksCapableProgram, mergeConfigs, parseHostSpec, parsePortSpec, programKey, proxyConfigPath, proxyHomeDir, proxyPid, proxyStatus, readProxyConfig, ruleEffectiveness, runWindowsGitConfig, startProxy, stopProxy, stopProxySync, writeProxyConfig } from './proxy.js'
69
+ import {
70
+ buildProfile,
71
+ redirectorCommand,
72
+ localRedirectorRunning,
73
+ redirectorStatus,
74
+ redirectorStatusCached,
75
+ reloadRedirectorsWithProfile,
76
+ startRedirectors,
77
+ stopRedirector,
78
+ posixToWindowsPath,
79
+ syncRedirector,
80
+ windowsToPosixPath,
81
+ writeHeartbeat,
82
+ } from './redirector.js'
83
+ import { armJanitor, disarmJanitor, janitorStatus, writeStateAtomic } from './janitor.js'
84
+ import {
85
+ acquireLease,
86
+ debugAction as daemonDebugAction,
87
+ ensureRisd,
88
+ getProxyView,
89
+ probeRisd,
90
+ risdHealth,
91
+ listPrograms as daemonListPrograms,
92
+ programAction as daemonProgramAction,
93
+ proxyAction,
94
+ readProgramLog as daemonReadProgramLog,
95
+ releaseLease,
96
+ saveProxy,
97
+ } from './risd-client.js'
98
+ import { scheduleStartupReconcile } from './startup.js'
68
99
 
69
100
  export const name = 'dsh-ris-ide'
70
101
  /**
@@ -108,6 +139,36 @@ export function pickGitBash(candidates) {
108
139
  return undefined
109
140
  }
110
141
 
142
+ /** Shell constructs that only a bash/msys shell understands (not cmd.exe). */
143
+ const BASH_DIALECT_RE = /(^|[\s;&|(])(exec|export|unset|source)\s|\$\(|`|\$\{[^}]*\}|\$[A-Z][A-Z0-9_]*\b/
144
+ /**
145
+ * Constructs that mean the command belongs to PowerShell, not bash. `$env:NAME`
146
+ * (the way PowerShell spells an environment variable), `$PSScriptRoot` &
147
+ * friends, `$x = 1` assignments, `-Command`, `.ps1` and an explicit `pwsh`.
148
+ */
149
+ const POWERSHELL_DIALECT_RE = /\$env:|\$(?:global|script|local|private|using|function|input|args|PSItem|PSScriptRoot|PSEdition|PSVersionTable|LASTEXITCODE|Error|Host|PID)\b|\$[A-Za-z_][A-Za-z0-9_]*\s*=|\b(?:powershell|pwsh)\b|-Command\b|\.ps1\b/i
150
+ /**
151
+ * Whether a custom `startCommand` is written in bash dialect.
152
+ *
153
+ * `runtime=auto` now selects the native PowerShell wrapper on Windows, which runs a
154
+ * custom command through `cmd.exe`. A command with `$(cat ...)`, `exec java` or
155
+ * `$HOME` then dies instantly with no explanation (review A2-P1-2), so the caller
156
+ * uses this to prefer Git Bash when the command needs it.
157
+ *
158
+ * Only *unambiguous* bash signals count: `$(`, backticks, `${...}`, `exec`/`export`
159
+ * and ALL-CAPS `$VAR` (how POSIX spells `$HOME`). Lowercase `$x` and `$env:NAME`
160
+ * are how PowerShell writes its own variables, and `$x = 1` is a PowerShell
161
+ * assignment — treating those as bash sent `pwsh`/`powershell` commands through Git
162
+ * Bash (or failed with `no-bash` when it was missing) (review C3-P1-1).
163
+ * @param {string} command - custom start command (JDWP placeholder already expanded).
164
+ * @returns {boolean} true when a POSIX shell is required.
165
+ */
166
+ export function isBashDialectCommand(command) {
167
+ if (typeof command !== 'string' || command.trim() === '') return false
168
+ if (POWERSHELL_DIALECT_RE.test(command) === true) return false
169
+ return BASH_DIALECT_RE.test(command)
170
+ }
171
+
111
172
  /** Detect a usable Git Bash on this Windows machine (see {@link pickGitBash}). */
112
173
  export function detectGitBash() {
113
174
  if (!IS_WINDOWS) return undefined
@@ -123,17 +184,30 @@ export function detectGitBash() {
123
184
  * @returns `{ runtime: 'bash', bashPath }` or `{ runtime: 'powershell' }`.
124
185
  * @throws {TailError} when `bash` is requested but Git Bash is not installed.
125
186
  */
126
- export function resolveWindowsRuntime(runtime, bashPath) {
187
+ export function resolveWindowsRuntime(runtime, bashPath, { bashDialect = false } = {}) {
127
188
  const requested = runtime === 'bash' || runtime === 'powershell' ? runtime : 'auto'
128
189
  if (requested === 'powershell') return { runtime: 'powershell' }
129
- const found = bashPath !== undefined ? pickGitBash([bashPath]) : detectGitBash()
130
- if (requested === 'bash') {
190
+ if (requested === 'auto' && bashDialect === true) {
191
+ // The command cannot run under cmd.exe: keep the pre-review behaviour for this
192
+ // one program instead of failing at launch (review A2-P1-2).
193
+ const found = bashPath !== undefined ? pickGitBash([bashPath]) : detectGitBash()
131
194
  if (found === undefined) {
132
- throw new TailError('no-bash', '没有找到 Git Bash(WSL 的 bash.exe 不支持);装 Git Bash 或把 runtime 设成 "powershell"', 400)
195
+ throw new TailError('no-bash', '这段 startCommand 是 bash 方言($(…)/exec/$VAR),但没找到 Git Bash:装 Git Bash 或把 runtime 设为 "powershell" 并改写命令', 400)
133
196
  }
134
197
  return { runtime: 'bash', bashPath: found }
135
198
  }
136
- return found === undefined ? { runtime: 'powershell' } : { runtime: 'bash', bashPath: found }
199
+ // 2026-11-09 Windows review: the Git Bash wrapper receives Windows paths
200
+ // verbatim, and MSYS rewrites/mangles them (`mkdir -p 'C:\x'` creates a file
201
+ // named `C:\x`, `cd 'C:\x'` fails). `auto` used to prefer Git Bash whenever
202
+ // it was installed — i.e. the most common Windows dev box — so the default is
203
+ // now the native PowerShell wrapper (no path translation). `bash` stays
204
+ // available, but only when asked for explicitly.
205
+ if (requested === 'auto') return { runtime: 'powershell' }
206
+ const found = bashPath !== undefined ? pickGitBash([bashPath]) : detectGitBash()
207
+ if (found === undefined) {
208
+ throw new TailError('no-bash', '没有找到 Git Bash(WSL 的 bash.exe 不支持);装 Git Bash 或把 runtime 设成 "powershell"', 400)
209
+ }
210
+ return { runtime: 'bash', bashPath: found }
137
211
  }
138
212
  /** The Host services this plugin needs: the HTTP route registry and session cwd lookup. */
139
213
  export const inject = ['webServer', 'sessions', 'tools']
@@ -319,6 +393,29 @@ const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
319
393
  const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
320
394
  /** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
321
395
  const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
396
+ /**
397
+ * Proxy rules + engine control.
398
+ * `GET` reports the stored rules (with per-row parse diagnostics) and whether the
399
+ * tunnel engine is up; `POST` saves the form; `/action` starts/stops the engine
400
+ * and writes the scoped git config.
401
+ */
402
+ const PROXY_PATH = `${ROUTE_PREFIX}/proxy`
403
+ const PROXY_ACTION_PATH = `${ROUTE_PREFIX}/proxy/action`
404
+ /** Program picker for the rules table: this OS, plus Windows when reachable. */
405
+ const PROXY_PROGRAMS_PATH = `${ROUTE_PREFIX}/proxy/programs`
406
+ /**
407
+ * File browser for the rules table's 「固定程序」 source: a rule can name an
408
+ * executable that is not running yet, so it is proxied the moment it starts.
409
+ */
410
+ const PROXY_BROWSE_PATH = `${ROUTE_PREFIX}/proxy/browse`
411
+ /**
412
+ * On-demand daemon start for the IDE button: clicking ⧉ must work even after
413
+ * `risd stop` (or a crash), so the client asks the host to spawn it rather than
414
+ * falling back to the old standalone window.
415
+ */
416
+ const RISD_ENSURE_PATH = `${ROUTE_PREFIX}/risd/ensure`
417
+ /** Where the page asks which client bundle the host is serving (m09693). */
418
+ const BUILD_PATH = `${ROUTE_PREFIX}/build`
322
419
  /** Workspace cache holding extracted sources / decompiled files. */
323
420
  export const IDE_CACHE_DIR = `${IDE_STATE_DIR}/cache`
324
421
  /** Where the visual settings dialog persists the decompiler jar. */
@@ -419,6 +516,160 @@ export class TailError extends Error {
419
516
  }
420
517
  }
421
518
 
519
+ /**
520
+ * Process-wide lifecycle for the detached child services (proxy engine, redirector,
521
+ * git proxy, janitor).
522
+ *
523
+ * The child services outlive any one plugin effect: dsh disposes the fiber tree and
524
+ * only then calls `process.exit()`, so the synchronous `exit` listener is the last
525
+ * chance to stop them. That listener — and the detached janitor that covers
526
+ * SIGKILL/crash/closed-terminal — must NOT be removed by the effect teardown.
527
+ * Removing them was the Ctrl+C leak: the hook was already gone when `process.exit()`
528
+ * ran, so the engine kept routing with no UI left to stop it. Living here also makes
529
+ * a profile hot reload harmless: the listener is installed once per process and a
530
+ * heartbeat stopped by the teardown is simply restarted.
531
+ */
532
+ let lifecycle = null
533
+ /** Engine left behind by a previous dsh process: `{ pid, owner, detectedAt } | null`. */
534
+ let inheritedEngine = null
535
+
536
+ /**
537
+ * Write the watchdog heartbeat now and keep writing it every 3 s.
538
+ *
539
+ * A failed write is NOT harmless: the elevated watchdog tears the bridge down
540
+ * after 20 s without a fresh heartbeat, so the user would see "代理桥接自己没了"
541
+ * with no explanation in the log. Warn once per failure streak (reset on the
542
+ * first successful beat) instead of swallowing it.
543
+ *
544
+ * @param logger - optional `{ warn(message) }` (the host context logger).
545
+ */
546
+ function startHeartbeat(logger = null) {
547
+ let warned = false
548
+ const beat = () => {
549
+ let ok = false
550
+ try {
551
+ ok = writeHeartbeat() !== false
552
+ } catch {
553
+ ok = false
554
+ }
555
+ if (ok === true) {
556
+ warned = false
557
+ return
558
+ }
559
+ if (warned === true) return
560
+ warned = true
561
+ try {
562
+ logger?.warn?.('[dsh-ris-ide] 心跳写入失败:提权看门狗 20s 后会拆除代理桥接;请检查 ~/.dsh-ris-ide 是否可写(DSH_RIS_IDE_PROXY_HOME)')
563
+ } catch { /* logging must never break the heartbeat */ }
564
+ }
565
+ beat()
566
+ return setInterval(beat, 3000)
567
+ }
568
+
569
+ /**
570
+ * Adopt an engine whose dsh is gone (`proxy.pid` alive, no watcher of ours).
571
+ *
572
+ * The pidfile is machine-wide, so an engine with a RUNNING janitor already has an
573
+ * owner on this machine: either another dsh (multi-instance case — leave it alone)
574
+ * or the watcher that is about to clean up after a crash. An engine with no watcher
575
+ * can only have survived the pre-fix teardown — take it over and report it, instead
576
+ * of letting it run invisibly or spawning a second one.
577
+ * @returns {{pid: number, owner: number, detectedAt: string} | null} the adopted engine.
578
+ */
579
+ function adoptLeftoverEngine() {
580
+ try {
581
+ const pid = proxyPid()
582
+ if (pid === null || pid <= 0) {
583
+ inheritedEngine = null
584
+ return null
585
+ }
586
+ if (inheritedEngine !== null && inheritedEngine.pid === pid) return inheritedEngine
587
+ const watcher = janitorStatus()
588
+ if (watcher.owner === process.pid) {
589
+ // Ours already (e.g. a hot reload): not "left behind".
590
+ inheritedEngine = null
591
+ return null
592
+ }
593
+ if (watcher.running === true) return inheritedEngine
594
+ inheritedEngine = { pid, owner: watcher.owner, detectedAt: new Date().toISOString() }
595
+ return inheritedEngine
596
+ } catch {
597
+ return inheritedEngine
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Install (once per process) the exit hook, heartbeat and janitor, and adopt an
603
+ * engine left behind by a previous dsh process.
604
+ * @returns {{beat: NodeJS.Timeout | null, onExit: Function, owner: number}} the state.
605
+ */
606
+ function ensureLifecycle(ctx = null) {
607
+ if (lifecycle !== null && lifecycle.owner === process.pid) {
608
+ if (lifecycle.beat === null) lifecycle.beat = startHeartbeat(ctx?.logger ?? null)
609
+ return lifecycle
610
+ }
611
+ adoptLeftoverEngine()
612
+ const onExit = () => {
613
+ try { stopProxySync() } catch { /* best effort while exiting */ }
614
+ try { stopRedirectorSync() } catch { /* best effort while exiting */ }
615
+ try { clearGitProxySync() } catch { /* best effort while exiting */ }
616
+ // Deliberately NO disarmJanitor(): the watcher must see our pid disappear and
617
+ // clean up itself — it is the only path that survives SIGKILL, a crash or a
618
+ // closed terminal, where no 'exit' listener runs at all.
619
+ }
620
+ process.once('exit', onExit)
621
+ lifecycle = { beat: startHeartbeat(ctx?.logger ?? null), onExit, owner: process.pid }
622
+ // Idempotent for the same owner; replaces a watcher left watching a dead dsh.
623
+ try { armJanitor({ ownerPid: process.pid }) } catch { /* the watcher is optional */ }
624
+ return lifecycle
625
+ }
626
+
627
+ /**
628
+ * Hand the machine-level lifecycle over to the daemon (daemonMode off → auto).
629
+ *
630
+ * A profile hot reload re-runs this plugin without restarting the process, so the
631
+ * exit hook/heartbeat/janitor installed by an earlier `ensureLifecycle` would keep
632
+ * running and compete with the daemon's own. This is the ONLY place they are
633
+ * removed again — a normal dispose must keep them armed (review P0-2).
634
+ */
635
+ function releaseLegacyLifecycle() {
636
+ if (lifecycle === null || lifecycle.owner !== process.pid) return
637
+ try { process.removeListener('exit', lifecycle.onExit) } catch { /* ignore */ }
638
+ if (lifecycle.beat !== null) clearInterval(lifecycle.beat)
639
+ try { disarmJanitor() } catch { /* the watcher may not exist */ }
640
+ lifecycle = null
641
+ }
642
+
643
+ /**
644
+ * Exit hook for an engine THIS plugin had to start in `daemonMode=auto` because the
645
+ * daemon was down (port stolen, spawn failed, version mismatch). The daemon isn't
646
+ * running to own the teardown, and auto mode deliberately installs no lifecycle, so
647
+ * without this the engine, the bridge and the scoped git entry outlive dsh — git
648
+ * then points at a dead tunnel (review C2-P1-3).
649
+ *
650
+ * It never writes a heartbeat or arms a janitor: those stay the daemon's job, and
651
+ * writing them here would re-create the two-owner problem.
652
+ */
653
+ let localProxyCleanup = null
654
+ function armLocalProxyCleanup() {
655
+ if (localProxyCleanup !== null) return
656
+ // A legacy lifecycle (daemonMode=off) already installs an exit hook that stops the
657
+ // same three layers; a second hook would just run the same sync cleanups twice.
658
+ if (lifecycle !== null) return
659
+ localProxyCleanup = () => {
660
+ try { stopProxySync() } catch { /* best effort while exiting */ }
661
+ try { stopRedirectorSync() } catch { /* best effort while exiting */ }
662
+ try { clearGitProxySync() } catch { /* best effort while exiting */ }
663
+ }
664
+ process.once('exit', localProxyCleanup)
665
+ }
666
+ /** Forget the local fallback cleanup once its engine is gone or the daemon took over. */
667
+ function disarmLocalProxyCleanup() {
668
+ if (localProxyCleanup === null) return
669
+ try { process.removeListener('exit', localProxyCleanup) } catch { /* ignore */ }
670
+ localProxyCleanup = null
671
+ }
672
+
422
673
  /**
423
674
  * Register this plugin's two routes for its lifetime.
424
675
  *
@@ -445,6 +696,7 @@ export function apply(ctx, config) {
445
696
  stopGraceMs: clampBytes(config?.stopGraceMs, DEFAULT_STOP_GRACE_MS, MAX_STOP_GRACE_MS),
446
697
  runtime: config?.runtime === 'bash' || config?.runtime === 'powershell' ? config.runtime : 'auto',
447
698
  bashPath: typeof config?.bashPath === 'string' && config.bashPath !== '' ? config.bashPath : undefined,
699
+ daemonMode: daemonModeEnabled(config) ? 'auto' : 'off',
448
700
  }
449
701
  ctx.effect(() => ctx.webServer.register({
450
702
  kind: 'prefix',
@@ -463,6 +715,59 @@ export function apply(ctx, config) {
463
715
  }, LOG_ROTATE_INTERVAL_MS)
464
716
  return () => clearInterval(timer)
465
717
  }, 'dsh-ris-ide: log rotation')
718
+ // Child services belong to the PROCESS, not to this effect (see ensureLifecycle):
719
+ // dsh disposes the fiber tree first and calls process.exit() afterwards, so a
720
+ // teardown that removed the exit hook or disarmed the janitor left the detached
721
+ // engine alive with no UI to stop it.
722
+ ctx.effect(() => {
723
+ // The page's workspace list must survive idle windows: only the plugin can ask
724
+ // the host whether a session still exists, so refresh it in both modes (m08228).
725
+ const dshWindowTimer = setInterval(() => { refreshDshWindows(ctx) }, DSH_WINDOW_REFRESH_MS)
726
+ dshWindowTimer.unref?.()
727
+ const stopDshWindows = () => clearInterval(dshWindowTimer)
728
+ // daemonMode=auto: the daemon owns the engine, the heartbeat and the janitor,
729
+ // so the plugin must install none of them. Doing half of it (exit hook without
730
+ // engine ownership, or the reverse) is how Ctrl+C started leaking in the first
731
+ // place; the two halves ship together in Phase 1b P3/P4.
732
+ if (options.daemonMode === 'auto') {
733
+ // Switching off→auto in a hot reload: the daemon now owns the engine, the
734
+ // heartbeat and the janitor, so drop the legacy trio to avoid two owners
735
+ // (review C-P1-6).
736
+ releaseLegacyLifecycle()
737
+ return stopDshWindows
738
+ }
739
+ const adopted = adoptLeftoverEngine()
740
+ if (adopted !== null) {
741
+ try {
742
+ ctx.logger?.warn?.(`[dsh-ris-ide] 接管上一个会话留下的代理引擎(引擎 pid ${adopted.pid},原所有者 pid ${adopted.owner > 0 ? adopted.owner : '未知'})`)
743
+ } catch { /* logging is best effort */ }
744
+ }
745
+ // Previous runs (and reboots) leave machine-level side effects behind — a git
746
+ // entry pointing at a dead tunnel, a parked ProxyBridgeSvc, a stale pidfile.
747
+ // Reconcile against today's rules/state before the panel can show them.
748
+ scheduleStartupReconcile({ log: (message) => ctx.logger?.warn?.(message) })
749
+ const state = ensureLifecycle(ctx)
750
+ return () => {
751
+ stopDshWindows()
752
+ // Only the heartbeat stops here: its stop is exactly what the elevated bridge
753
+ // watchdog waits for (20 s freshness), and the next apply (a profile hot
754
+ // reload) restarts it in the same second. The exit hook and the janitor stay
755
+ // armed — they are the guards for process.exit(), SIGKILL, a crash and a
756
+ // closed terminal.
757
+ if (state.beat !== null) {
758
+ clearInterval(state.beat)
759
+ state.beat = null
760
+ }
761
+ }
762
+ }, 'dsh-ris-ide: stop child services on exit')
763
+ // Optional risd bridge (Phase 1a): discovery + lease only. The engine is still
764
+ // ours, so this effect must not stop it — `stopRisdBridge` just releases the
765
+ // lease and lets the daemon's liveness poll do the rest.
766
+ ctx.effect(() => {
767
+ if (options.daemonMode !== 'auto') return () => {}
768
+ startRisdBridge(ctx, undefined)
769
+ return () => stopRisdBridge()
770
+ }, 'dsh-ris-ide: risd lease (optional daemon)')
466
771
  }
467
772
 
468
773
  /**
@@ -474,6 +779,146 @@ export function apply(ctx, config) {
474
779
  * @param res - Node response face.
475
780
  * @param options - `{ maxBytes, restrictToCwd, stopGraceMs }` (see {@link apply}).
476
781
  */
782
+ /** Where the daemon's maintenance page learns our URL(s) + sessionIds (GET /v1/dsh). */
783
+ const DSH_WINDOW_FILENAME = 'dsh-window.json'
784
+ /** Rewrite at most this often; a changed sessionId forces an immediate write. */
785
+ const DSH_WINDOW_THROTTLE_MS = 3000
786
+ /** Keep the list short: the page only needs the workspaces someone is working in. */
787
+ const DSH_WINDOW_MAX_ENTRIES = 8
788
+ let dshWindowNote = { at: 0, host: '', sessionId: '', cwd: '' }
789
+
790
+ /**
791
+ * Upsert one dsh window record (origin + sessionId per workspace). A daemon page
792
+ * can then offer every workspace's IDE in one window instead of one page per cwd.
793
+ * Loopback Hosts only, best effort, never throws.
794
+ * @param req - the incoming HTTP request.
795
+ */
796
+ function noteDshWindow(req) {
797
+ // `node --test` runs against the developer's real home unless a test isolates
798
+ // DSH_RIS_IDE_PROXY_HOME. Fake contexts with /tmp workspaces used to collect
799
+ // entries in dsh-window.json and the daemon page listed them as workspaces
800
+ // (m08500), so tests must opt in explicitly.
801
+ if (process.env.NODE_TEST_CONTEXT !== undefined && process.env.DSH_RIS_IDE_WINDOW_NOTE !== '1') return
802
+ // Every other route on this prefix goes through isLoopbackRequest, which also
803
+ // rejects a cross-site Origin. This write feeds the daemon's workspace list, so a
804
+ // random page must not be able to seed it (review C2-P2-4).
805
+ if (!isLoopbackRequest(req)) return
806
+ const host = String(req?.headers?.host ?? '')
807
+ const now = Date.now()
808
+ let sessionId = ''
809
+ let cwd = ''
810
+ try {
811
+ const url = new URL(String(req.url ?? '/'), `http://${host}`)
812
+ sessionId = url.searchParams.get('sessionId') ?? ''
813
+ cwd = url.searchParams.get('cwd') ?? ''
814
+ } catch { /* malformed URL: keep the blanks */ }
815
+ // A request without a workspace cannot be attributed to one; recording it under
816
+ // `existing[0].cwd` replaced some OTHER workspace's window (review C-P1-5).
817
+ if (cwd === '' || !isAbsolute(cwd)) return
818
+ // Only a real dsh window may claim a workspace: its requests always carry
819
+ // ?sessionId=. The `/windows?cwd=` probes from the standalone/maintenance page do
820
+ // not, and inheriting the previous window's id made `/ws-a` open with `/ws-b`'s
821
+ // session and made the liveness check prune the wrong entry (review C2-P1-2).
822
+ if (sessionId === '') return
823
+ // A workspace nobody recorded yet is written immediately (the page needs it, and
824
+ // there are at most DSH_WINDOW_MAX_ENTRIES). Everything already recorded is at
825
+ // most one write per window: two windows alternating requests used to defeat the
826
+ // throttle and write the machine-level file on EVERY request (review C3-P2-6) —
827
+ // inside the window only the in-memory key moves.
828
+ const home = (() => { try { return proxyHomeDir() } catch { return '' } })()
829
+ if (home === '') return
830
+ const path = join(home, DSH_WINDOW_FILENAME)
831
+ let existing = []
832
+ try {
833
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
834
+ if (Array.isArray(parsed?.windows)) existing = parsed.windows
835
+ } catch { /* first write */ }
836
+ const known = existing.some((row) => row !== null && typeof row === 'object'
837
+ && (row.cwd ?? '') === cwd && (row.sessionId ?? '') === sessionId)
838
+ if (known && now - dshWindowNote.at < DSH_WINDOW_THROTTLE_MS) {
839
+ dshWindowNote = { at: dshWindowNote.at, host, sessionId, cwd }
840
+ return
841
+ }
842
+ dshWindowNote = { at: now, host, sessionId, cwd }
843
+ try {
844
+ mkdirSync(home, { recursive: true, mode: 0o700 })
845
+ const entry = {
846
+ url: `http://${host}`,
847
+ sessionId,
848
+ cwd,
849
+ // Which plugin process wrote this row: another dsh (same home) refreshes and
850
+ // prunes only its own rows (review C2-P2-2).
851
+ ownerPid: process.pid,
852
+ at: new Date(now).toISOString(),
853
+ }
854
+ const windows = existing.filter((row) => row !== null && typeof row === 'object' && (row.cwd ?? '') !== cwd)
855
+ windows.unshift(entry)
856
+ const trimmed = windows.slice(0, DSH_WINDOW_MAX_ENTRIES)
857
+ // Atomic replace: a half-written file reads as "no windows" in the daemon
858
+ // (review C2-P2-1 / A2-P2-17).
859
+ writeStateAtomic(path, { windows: trimmed })
860
+ } catch { /* the daemon page simply greys the IDE tab out */ }
861
+ }
862
+ /** How often the plugin refreshes the liveness of remembered dsh windows. */
863
+ const DSH_WINDOW_REFRESH_MS = 10_000
864
+
865
+ /**
866
+ * Keep the remembered windows' `at` fresh while dsh still knows their session, so
867
+ * the daemon page lists every workspace that is currently open instead of only the
868
+ * one that happened to hit an endpoint within the freshness window (m08228).
869
+ * The plugin is the only writer of dsh-window.json; a daemon-side timer cannot
870
+ * answer "does this session still exist" because it has no host context.
871
+ * @param ctx - Host context (`ctx.sessions.get(id)`).
872
+ * @returns {{changed:number, windows:number}} how many entries were refreshed.
873
+ */
874
+ export function refreshDshWindows(ctx) {
875
+ const result = { changed: 0, windows: 0, dropped: 0 }
876
+ try {
877
+ const path = join(proxyHomeDir(), DSH_WINDOW_FILENAME)
878
+ let windows = []
879
+ try {
880
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
881
+ if (Array.isArray(parsed?.windows)) windows = parsed.windows
882
+ } catch { return result }
883
+ if (windows.length === 0) return result
884
+ const now = Date.now()
885
+ const canVerify = typeof ctx?.sessions?.get === 'function'
886
+ let dirty = false
887
+ const next = windows.reduce((out, row) => {
888
+ if (row === null || typeof row !== 'object') return out
889
+ // Another dsh process owns this row (same machine-level home): its own plugin
890
+ // refreshes/prunes it. Deleting it here made two instances erase each other's
891
+ // workspaces (review C2-P2-2). Legacy rows (no ownerPid) are treated as ours;
892
+ // a garbage value must not be read as "someone else's row" (Number('abc') is
893
+ // NaN and used to fall through to the pruning branch, review C3-P2-5).
894
+ const rawOwner = Number(row.ownerPid)
895
+ const ownerPid = Number.isInteger(rawOwner) && rawOwner > 0 ? rawOwner : process.pid
896
+ if (ownerPid !== process.pid) { out.push(row); return out }
897
+ const sessionId = typeof row.sessionId === 'string' ? row.sessionId : ''
898
+ // An empty session id cannot be verified (legacy rows); keep it and let the
899
+ // daemon's retain TTL retire it.
900
+ if (sessionId === '' || !canVerify) { out.push(row); return out }
901
+ const session = ctx.sessions.get(sessionId)
902
+ const sessionCwd = typeof session?.header?.cwd === 'string' ? session.header.cwd : ''
903
+ // "Session exists" is not enough: a session may have been reopened on another
904
+ // workspace, and refreshing the old cwd would keep a wrong row alive.
905
+ if (!session || (sessionCwd !== '' && sessionCwd !== row.cwd)) {
906
+ dirty = true
907
+ result.dropped += 1
908
+ return out
909
+ }
910
+ dirty = true
911
+ result.changed += 1
912
+ out.push(Object.assign({}, row, { at: new Date(now).toISOString() }))
913
+ return out
914
+ }, [])
915
+ // Report the surviving size: the pre-prune number misled callers/tests (review E P2-2).
916
+ result.windows = next.length
917
+ if (dirty) writeStateAtomic(path, { windows: next })
918
+ } catch { /* best effort: the page keeps showing what it last knew */ }
919
+ return result
920
+ }
921
+
477
922
  export function handleRequest(ctx, req, res, options) {
478
923
  try {
479
924
  dispatchRequest(ctx, req, res, options)
@@ -490,6 +935,7 @@ export function handleRequest(ctx, req, res, options) {
490
935
 
491
936
  /** The actual router behind {@link handleRequest}'s exception fence. */
492
937
  function dispatchRequest(ctx, req, res, options) {
938
+ noteDshWindow(req)
493
939
  const method = req.method ?? 'GET'
494
940
  const pathname = requestPathname(req)
495
941
  if (pathname === WINDOWS_PATH) {
@@ -635,6 +1081,10 @@ function dispatchRequest(ctx, req, res, options) {
635
1081
  return
636
1082
  }
637
1083
  if (pathname === DEBUGS_PATH) {
1084
+ if (!isLoopbackRequest(req)) {
1085
+ writeJson(res, 403, { ok: false, code: 'forbidden', message: 'this route answers loopback requests only' })
1086
+ return
1087
+ }
638
1088
  if (method !== 'GET') {
639
1089
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
640
1090
  return
@@ -654,6 +1104,56 @@ function dispatchRequest(ctx, req, res, options) {
654
1104
  serveSafely(res, () => serveDebugSource(ctx, req, res, options))
655
1105
  return
656
1106
  }
1107
+ if (pathname === PROXY_PATH) {
1108
+ serveSafely(res, () => serveProxy(ctx, req, res, options))
1109
+ return
1110
+ }
1111
+ if (pathname === BUILD_PATH) {
1112
+ if (method !== 'GET') {
1113
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1114
+ return
1115
+ }
1116
+ // No auth beyond loopback: it names a build, not a secret, and the page that
1117
+ // needs it may be the one asking before it has any other state.
1118
+ if (!isLoopbackRequest(req)) {
1119
+ writeJson(res, 403, { ok: false, code: 'forbidden', message: 'this route answers loopback requests only' })
1120
+ return
1121
+ }
1122
+ writeJson(res, 200, { ok: true, version: PKG_VERSION, build: clientBundleStamp() })
1123
+ return
1124
+ }
1125
+ if (pathname === RISD_ENSURE_PATH) {
1126
+ if (method !== 'POST') {
1127
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
1128
+ return
1129
+ }
1130
+ serveSafely(res, () => serveRisdEnsure(ctx, req, res, options))
1131
+ return
1132
+ }
1133
+ if (pathname === PROXY_ACTION_PATH) {
1134
+ if (method !== 'POST') {
1135
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
1136
+ return
1137
+ }
1138
+ serveSafely(res, () => serveProxyAction(ctx, req, res, options))
1139
+ return
1140
+ }
1141
+ if (pathname === PROXY_PROGRAMS_PATH) {
1142
+ if (method !== 'GET') {
1143
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1144
+ return
1145
+ }
1146
+ serveSafely(res, () => serveProxyPrograms(ctx, req, res, options))
1147
+ return
1148
+ }
1149
+ if (pathname === PROXY_BROWSE_PATH) {
1150
+ if (method !== 'GET') {
1151
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1152
+ return
1153
+ }
1154
+ serveSafely(res, () => serveProxyBrowse(ctx, req, res, options))
1155
+ return
1156
+ }
657
1157
  if (pathname === SETTINGS_PATH) {
658
1158
  serveSafely(res, () => serveSettings(ctx, req, res, options))
659
1159
  return
@@ -696,6 +1196,10 @@ function dispatchRequest(ctx, req, res, options) {
696
1196
  return
697
1197
  }
698
1198
  if (pathname === OPENS_PATH) {
1199
+ if (!isLoopbackRequest(req)) {
1200
+ writeJson(res, 403, { ok: false, code: 'forbidden', message: 'this route answers loopback requests only' })
1201
+ return
1202
+ }
699
1203
  if (method !== 'GET') {
700
1204
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
701
1205
  return
@@ -1206,6 +1710,47 @@ function createOrderedPages(rootCount, pageSize, emit, options = {}) {
1206
1710
  }
1207
1711
  }
1208
1712
 
1713
+ /**
1714
+ * Identify the client bundle this host is serving right now.
1715
+ *
1716
+ * Why a page needs it: plugin bundles are served with `immutable` caching and a
1717
+ * revision-baked path, so an HTTP reload picks up a new build — but a page that
1718
+ * is ALREADY OPEN keeps running the bundle it booted with, which is why a
1719
+ * stylesheet tweak looks like it "needs a hard refresh". The stamp rides the
1720
+ * The stamp rides the stream's `hello` and `/dsh-ris-ide/build`; the page compares
1721
+ * it with the one it booted with and offers a refresh (it never reloads itself: a
1722
+ * reload would throw the conversation view or the IDE window's unsaved buffers
1723
+ * away, review C3-P1-2/P1-3).
1724
+ *
1725
+ * `standalone/window.html` is part of the stamp because the standalone window page
1726
+ * is served from it: its changes must reach the already-open window too. A DSH page
1727
+ * never loads it, so a window-only change makes the DSH hint say "refresh" where a
1728
+ * reload does not actually change the DSH bundle — harmless, and the window page
1729
+ * does pick it up.
1730
+ *
1731
+ * Metadata only (size + mtime): three `statSync` calls per hello is free, while
1732
+ * hashing a multi-megabyte bundle would not be.
1733
+ * @returns {string} 12 hex chars, stable until one of the bundle files changes.
1734
+ */
1735
+ function clientBundleStamp() {
1736
+ const hash = createHash('sha1')
1737
+ const dir = fileURLToPath(new URL('.', import.meta.url))
1738
+ for (const name of ['client.js', 'client-codemirror.js', 'standalone/window.html']) {
1739
+ hash.update(name)
1740
+ hash.update('\0')
1741
+ try {
1742
+ const info = statSync(join(dir, name))
1743
+ hash.update(`${info.size}:${info.mtimeMs}`)
1744
+ } catch {
1745
+ // A trimmed install still gets a stable stamp; adding the file later
1746
+ // changes it, which is what the page needs to notice.
1747
+ hash.update('absent')
1748
+ }
1749
+ hash.update('\n')
1750
+ }
1751
+ return hash.digest('hex').slice(0, 12)
1752
+ }
1753
+
1209
1754
  /**
1210
1755
  * Run `worker(root, index)` for every root with at most `concurrency` in flight.
1211
1756
  * A worker must handle its own errors — one broken repo must not cancel the rest.
@@ -4466,6 +5011,9 @@ async function serveStream(ctx, req, res, options) {
4466
5011
  send('hello', {
4467
5012
  ok: true,
4468
5013
  version: PKG_VERSION,
5014
+ // Which client bundle this host serves NOW (see clientBundleStamp): a page
5015
+ // that booted an older one reloads itself instead of needing Ctrl+Shift+R.
5016
+ build: clientBundleStamp(),
4469
5017
  root: cwd,
4470
5018
  topics,
4471
5019
  window: windowCwd !== undefined,
@@ -5165,6 +5713,1188 @@ async function serveSettings(ctx, req, res, options) {
5165
5713
  }
5166
5714
  }
5167
5715
 
5716
+
5717
+ /**
5718
+ * Short, stable fingerprint of the machine-wide table.
5719
+ *
5720
+ * The dialog posts the WHOLE table, so two windows (or two people) editing at once
5721
+ * would silently overwrite each other: whoever saves last wins and the other row is
5722
+ * gone with no error. The fingerprint travels with the write, so a stale payload is
5723
+ * refused (409) instead of applied.
5724
+ * @param config - a normalised proxy config.
5725
+ * @returns a 12-char hex fingerprint of everything the dialog can change.
5726
+ */
5727
+ export function configRevision(config) {
5728
+ const view = {
5729
+ socks: [String(config?.socks?.host ?? ''), Number(config?.socks?.port ?? 0)],
5730
+ listenPort: Number(config?.listenPort ?? 0),
5731
+ rules: (Array.isArray(config?.rules) ? config.rules : []).map((rule) => [
5732
+ String(rule.id ?? ''),
5733
+ String(rule.program ?? ''),
5734
+ String(rule.hosts ?? ''),
5735
+ String(rule.ports ?? ''),
5736
+ rule.enabled === true,
5737
+ rule.shadow === true,
5738
+ String(rule.source ?? ''),
5739
+ ]),
5740
+ }
5741
+ return createHash('sha1').update(JSON.stringify(view)).digest('hex').slice(0, 12)
5742
+ }
5743
+
5744
+ /**
5745
+ * One stored rule, decorated with what the engine will actually make of it: the
5746
+ * parsed host patterns / ports plus the fragments it rejected, so the dialog can
5747
+ * flag a typo instead of silently dropping a destination.
5748
+ * @param rule - a rule from the normalised config.
5749
+ * @returns the rule plus `hostsParsed|hostsInvalid|portsParsed|portsInvalid`.
5750
+ */
5751
+ function decorateProxyRule(rule) {
5752
+ const hosts = parseHostSpec(rule.hosts)
5753
+ const ports = parsePortSpec(rule.ports)
5754
+ // A shadow is a loopback LISTENER, so it needs ports it can actually bind: `*`
5755
+ // parses to port 0 ("any port"), which must not make a rule sweepable here.
5756
+ const bindable = ports.ports.filter((port) => port > 0)
5757
+ const shadowable = hosts.patterns.length > 0 && hosts.patterns.every((pattern) => /^\d{1,3}(\.\d{1,3}){3}$/.test(pattern)) && bindable.length > 0
5758
+ const socksCapable = isSocksCapableProgram(rule.program)
5759
+ const verdict = ruleEffectiveness(rule)
5760
+ return Object.assign({}, rule, {
5761
+ hostsParsed: hosts.patterns,
5762
+ hostsInvalid: hosts.invalid,
5763
+ portsParsed: ports.ports,
5764
+ portsInvalid: ports.invalid,
5765
+ // What the rule can do is NOT the same for both mechanisms: only a literal
5766
+ // IPv4 destination can be pre-bound on a loopback port, and a wildcard can
5767
+ // only be matched per connection (the CONNECT proxy).
5768
+ shadowable,
5769
+ // Which mechanism this program actually needs — the dialog shows it and the
5770
+ // engine defaults the mapping flag from it (SOCKS-aware programs need none,
5771
+ // everything else can only reach the tunnel through a mapped port).
5772
+ socksCapable,
5773
+ autoShadow: shadowable && !socksCapable,
5774
+ // A rule applies only when enabled AND program/IP/port are all explicit
5775
+ // (`*` spells "everything"); the dialog marks the others instead of letting a
5776
+ // half-written row look active.
5777
+ effective: verdict.effective,
5778
+ ineffectiveReason: verdict.reason,
5779
+ // The rule table is machine-wide (ProxyBridge hooks the kernel and matches
5780
+ // processes), so a row's workspace is provenance only: the dialog shows it
5781
+ // as「来源」 and never treats it as a boundary.
5782
+ origin: rule.workspace === '' ? '' : basename(rule.workspace),
5783
+ })
5784
+ }
5785
+
5786
+ /** Companion-plugin hints: `dsh-ris-yds` assists YonBIP/YMS development (local
5787
+ * runtime, intranet access, development config). Only the capabilities are
5788
+ * named here — never its internals, and never the tools it happens to patch.
5789
+ * We only RECOMMEND it when the workspace really looks like a YMS project: the
5790
+ * two plugins stay usable standalone, so this must never turn into a
5791
+ * requirement (and it must never guess on a plain Java/Vue repo). */
5792
+ function detectCompanionPlugin(cwd) {
5793
+ const evidence = []
5794
+ try {
5795
+ if (existsSync(join(cwd, 'yms-home'))) evidence.push('yms-home/')
5796
+ if (existsSync(join(cwd, '.dsh-ris-yds'))) evidence.push('.dsh-ris-yds/')
5797
+ if (evidence.length === 0) {
5798
+ const settings = join(cwd, '.vscode', 'settings.json')
5799
+ if (existsSync(settings) && readFileSync(settings, 'utf8').includes('"yds.')) {
5800
+ evidence.push('.vscode/settings.json (yds.*)')
5801
+ }
5802
+ }
5803
+ } catch {
5804
+ // Detection is best effort: an unreadable workspace simply gets no hint.
5805
+ }
5806
+ if (evidence.length === 0) return null
5807
+ return {
5808
+ plugin: 'dsh-ris-yds',
5809
+ detected: evidence.join(', '),
5810
+ hint: '检测到 YonBIP/YMS 工程:dsh-ris-yds 提供本地运行 YMS、访问内网资源、准备开发配置等辅助开发能力(可选,不装不影响本插件)。',
5811
+ }
5812
+ }
5813
+
5814
+ /**
5815
+ * The whole proxy state the dialog needs, in ONE round trip: rules (decorated),
5816
+ * upstream address, engine state, and the scoped git entry it would write.
5817
+ * @param cwd - workspace directory.
5818
+ * @param gitHost - optional host to narrow the git entry to.
5819
+ * @returns a JSON-safe view.
5820
+ */
5821
+ async function proxyView(cwd, gitHost) {
5822
+ const status = await proxyStatus(cwd)
5823
+ const allow = allowList(status.config)
5824
+ const git = gitProxyPlan(status.config, { host: gitHost })
5825
+ const watcher = janitorStatus()
5826
+ // An engine adopted from a PREVIOUS dsh process (see adoptLeftoverEngine): the
5827
+ // dialog shows a takeover banner with a one-click stop instead of pretending this
5828
+ // session started it. The flag is dropped as soon as that engine is gone.
5829
+ const inherited = inheritedEngine !== null && inheritedEngine.pid === status.pid ? inheritedEngine : null
5830
+ return {
5831
+ ok: true,
5832
+ side: engineSide(),
5833
+ // The dialog sends this back with its save, so a table edited in another window
5834
+ // is refused instead of silently overwritten.
5835
+ revision: configRevision(status.config),
5836
+ // ONE engine and ONE config per machine: the path is not workspace-derived.
5837
+ configPath: proxyConfigPath(),
5838
+ home: proxyHomeDir(),
5839
+ shared: true,
5840
+ workspace: cwd,
5841
+ socks: status.config.socks,
5842
+ listenPort: status.config.listenPort,
5843
+ rules: await proxyRulesView(cwd, status.config),
5844
+ running: status.running,
5845
+ pid: status.pid,
5846
+ listen: status.listen,
5847
+ logPath: status.logPath,
5848
+ socksUrl: status.socksUrl,
5849
+ allow,
5850
+ git,
5851
+ // ProxyBridge is the PRIMARY path (kernel hook, matches by process name, so
5852
+ // it covers programs we never launched); the engine's loopback mappings and
5853
+ // the spawn-time injection remain as the fallback when it is not running.
5854
+ redirector: Object.assign(redirectorStatusCached(), {
5855
+ // What the CLI would be told to do, so the dialog can show the exact
5856
+ // command instead of asking the user to assemble one.
5857
+ rules: buildProfile(status.config).rules.length,
5858
+ }),
5859
+ // Where the daemon maintenance page lives (null when daemonMode is off). The
5860
+ // header and console "IDE" buttons open that page instead of the window: it
5861
+ // embeds the IDE and can switch workspace, so one tab covers them all.
5862
+ risd: risdBridge !== null && risdBridge.state !== null
5863
+ ? { available: true, url: risdBridge.state.url, port: risdBridge.state.port, apiVersion: risdBridge.state.apiVersion }
5864
+ : { available: false },
5865
+ // Watchdog state: it is what removes the layers if dsh itself is killed.
5866
+ janitor: watcher,
5867
+ // Who owns the child services right now (0 = no watcher state at all).
5868
+ owner: watcher.owner,
5869
+ // Takeover of a leftover engine (pid + the dsh that started it, 0 = unknown).
5870
+ inherited: inherited !== null,
5871
+ inheritedPid: inherited === null ? 0 : inherited.pid,
5872
+ inheritedFrom: inherited === null ? 0 : inherited.owner,
5873
+ inheritedSince: inherited === null ? '' : inherited.detectedAt,
5874
+ }
5875
+ }
5876
+
5877
+ /**
5878
+ * The rule rows the dialog renders: every stored rule (whoever wrote it), minus
5879
+ * the loopback mapping rows dsh-ris-yds keeps as a fallback — those are an
5880
+ * implementation detail of "no system-level interception", not something the
5881
+ * user configures, so they never reach the dialog (they stay in the file, which
5882
+ * is what the engine and the redirector profile are built from).
5883
+ *
5884
+ * Templates are appended only where the machine has no row for that program
5885
+ * yet, so a fresh workspace still shows the starter rows. `template: true` marks
5886
+ * a starter row the user has not saved: the dialog shows it, but must NOT write
5887
+ * it back (that would turn a suggestion into a stored rule living forever in the
5888
+ * shared table).
5889
+ * @param cwd - workspace the rows are rendered for.
5890
+ * @param config - the normalised machine table.
5891
+ * @returns decorated rows, stored first then templates.
5892
+ */
5893
+ async function proxyRulesView(cwd, config) {
5894
+ const own = config.rules.filter((rule) => !(rule.source === 'yds' && rule.shadow === true))
5895
+ const covered = new Set(own.map((rule) => programKey(rule.program)))
5896
+ const templates = autoRules(cwd).filter((rule) => !covered.has(programKey(rule.program)))
5897
+ const stored = await Promise.all(own.map(async (rule) => {
5898
+ const decorated = decorateProxyRule(rule)
5899
+ // A rule can start its program itself (that is the only way to inject the
5900
+ // tunnel into something we did not launch), so the row shows whether it is
5901
+ // up and where its log is.
5902
+ const service = await readService(proxyRunLogPath(cwd, rule.id)).catch(() => undefined)
5903
+ return Object.assign(decorated, {
5904
+ runnable: decorated.socksCapable && String(rule.program ?? '').trim() !== '',
5905
+ runLogPath: proxyRunLogPath(cwd, rule.id),
5906
+ run: service === undefined ? null : { pid: service.pid, alive: service.alive },
5907
+ })
5908
+ }))
5909
+ return stored.concat(templates.map((rule) => Object.assign(decorateProxyRule(rule), { template: true })))
5910
+ }
5911
+
5912
+ /**
5913
+ * Phase 1a bridge to risd: the daemon owns the read-only view, the plugin keeps
5914
+ * the parts that need a live process (per-rule run state, the inherited-engine
5915
+ * banner, the bridge status it still starts itself).
5916
+ *
5917
+ * `daemonMode` defaults to `auto` since 1.8.0: the ⧉ button and the tool layer
5918
+ * both want the daemon (it owns the engine, the programs and the page), and the
5919
+ * daemon was opt-in only while it was being built. `daemonMode=off` (config or
5920
+ * `DSH_RISD_MODE=off`) is still the one-word rollback to the pre-1.8 wiring.
5921
+ * @type {{mode: 'off'|'auto', state: object|null, leaseId: string|null, pending: Promise<void>|null, warnedAt: number}|null}
5922
+ */
5923
+ let risdBridge = null
5924
+
5925
+ function daemonModeEnabled(config) {
5926
+ // 1.8.0 defaults to auto (m07355: the IDE entry always lands on risd-ui). Test
5927
+ // processes keep the historical off default so plugin suites do not spawn real
5928
+ // daemons; an explicit daemonMode/DSH_RISD_MODE still wins over both.
5929
+ //
5930
+ // Only the documented values switch it on. A typo ('of'), a stringified boolean
5931
+ // ('false') or 0 used to enable the daemon silently because the old test was
5932
+ // `value !== 'off'` (review E P2-1); unknown values now mean "off".
5933
+ const fallback = process.env.NODE_TEST_CONTEXT !== undefined && process.env.DSH_RISD_MODE === undefined ? 'off' : 'auto'
5934
+ const value = config?.daemonMode ?? process.env.DSH_RISD_MODE ?? fallback
5935
+ if (value === true || value === 'auto' || value === 'on') return true
5936
+ if (value === '') return true
5937
+ return false
5938
+ }
5939
+
5940
+ /**
5941
+ * Circuit breaker for automatic daemon starts.
5942
+ *
5943
+ * Every auto-start path (the ⧉ button, tool healing) must give up after a few
5944
+ * failures: a daemon that cannot boot (bad home permissions, port stolen by
5945
+ * something that never answers, broken Node install) would otherwise be spawned
5946
+ * again on every click/tool call, each costing the full 5 s health window. After
5947
+ * three failures inside two minutes we stop for five minutes and tell the user
5948
+ * what to run by hand.
5949
+ */
5950
+ const RISD_HEAL_WINDOW_MS = 2 * 60_000
5951
+ const RISD_HEAL_MAX_ATTEMPTS = 3
5952
+ const RISD_HEAL_COOLDOWN_MS = 5 * 60_000
5953
+ let risdHeal = { attempts: 0, since: 0, blockedUntil: 0, lastError: '' }
5954
+
5955
+ /** @returns true while automatic starts are paused. */
5956
+ export function risdHealBlocked(now = Date.now()) {
5957
+ return now < risdHeal.blockedUntil
5958
+ }
5959
+
5960
+ /** @returns the message shown instead of starting the daemon, or ''. */
5961
+ export function risdHealReason(now = Date.now()) {
5962
+ if (!risdHealBlocked(now)) return ''
5963
+ const seconds = Math.max(1, Math.ceil((risdHeal.blockedUntil - now) / 1000))
5964
+ return `连续 ${RISD_HEAL_MAX_ATTEMPTS} 次自动启动 risd 失败(${risdHeal.lastError || 'unknown'}),${seconds}s 内不再自动唤起;请运行 risd serve 查看原因`
5965
+ }
5966
+
5967
+ /** Count one failed start; the third inside the window trips the breaker. */
5968
+ export function noteRisdHealFailure(error, now = Date.now()) {
5969
+ if (now - risdHeal.since > RISD_HEAL_WINDOW_MS) { risdHeal.attempts = 0; risdHeal.since = now }
5970
+ if (risdHeal.attempts === 0) risdHeal.since = now
5971
+ risdHeal.attempts += 1
5972
+ risdHeal.lastError = String(error ?? '').slice(0, 200)
5973
+ if (risdHeal.attempts >= RISD_HEAL_MAX_ATTEMPTS) {
5974
+ risdHeal.blockedUntil = now + RISD_HEAL_COOLDOWN_MS
5975
+ risdHeal.attempts = 0
5976
+ risdHeal.since = 0
5977
+ }
5978
+ }
5979
+
5980
+ /** A successful start clears the breaker. */
5981
+ export function noteRisdHealSuccess() {
5982
+ risdHeal = { attempts: 0, since: 0, blockedUntil: 0, lastError: '' }
5983
+ }
5984
+
5985
+ function startRisdBridge(ctx, cwd) {
5986
+ risdBridge = { mode: 'auto', state: null, leaseId: null, pending: null, warnedAt: 0 }
5987
+ const bridge = risdBridge
5988
+ bridge.pending = (async () => {
5989
+ const ensured = await ensureRisd({ home: proxyHomeDir() })
5990
+ if (ensured.ok !== true) {
5991
+ try {
5992
+ ctx.logger?.warn?.(`[dsh-ris-ide] risd 不可用(${ensured.reason ?? 'unknown'}),代理视图回退到插件本地`)
5993
+ } catch { /* logging is best effort */ }
5994
+ return
5995
+ }
5996
+ await attachBridgeState(ensured.state, cwd)
5997
+ })().finally(() => {
5998
+ if (bridge === risdBridge) bridge.pending = null
5999
+ })
6000
+ }
6001
+
6002
+ /**
6003
+ * Point the bridge at a live daemon and make sure this window holds a lease.
6004
+ *
6005
+ * Keeping the same function for start / heal / ensure matters: a lease acquired
6006
+ * once survives a single failed request, and a window that keeps its lease is what
6007
+ * `followDsh` uses to decide that dsh is still open (review C-P1-1).
6008
+ * @param state - daemon state from `ensureRisd()`.
6009
+ * @param cwd - workspace for the lease (null before the first session is known).
6010
+ * @returns the same state, for chaining.
6011
+ */
6012
+ function attachBridgeState(state, cwd = null) {
6013
+ const bridge = risdBridge
6014
+ if (bridge === null || bridge.mode !== 'auto') return state
6015
+ bridge.state = state
6016
+ bridge.degraded = false
6017
+ bridge.lastProbeAt = Date.now()
6018
+ // The daemon owns the engine now: the local fallback hook (armed when the engine
6019
+ // was started behind the daemon's back) must not stop it on dsh exit (review
6020
+ // C3-P2-7).
6021
+ disarmLocalProxyCleanup()
6022
+ if (bridge.leaseId === null) {
6023
+ void acquireLease(state, { ownerPid: process.pid, sessionId: null, cwd: cwd ?? null })
6024
+ .then((lease) => {
6025
+ if (lease.ok === true && lease.body?.lease !== undefined) bridge.leaseId = lease.body.lease.id
6026
+ })
6027
+ .catch(() => { /* the next attach retries */ })
6028
+ }
6029
+ return state
6030
+ }
6031
+
6032
+ /**
6033
+ * The daemon state a writer should use, or null when this process should write
6034
+ * locally.
6035
+ *
6036
+ * A single failed request used to null the pointer permanently and let the plugin
6037
+ * write the machine-wide table behind the daemon's back (review C-P0-2). Now a
6038
+ * missing pointer is a *degraded* state: retry the handshake (throttled), and let
6039
+ * the caller refuse to write locally while the daemon may still be alive.
6040
+ * @param cwd - workspace for the lease.
6041
+ * @returns live daemon state, or null.
6042
+ */
6043
+ async function risdBridgeState(cwd = null) {
6044
+ const bridge = risdBridge
6045
+ if (bridge === null || bridge.mode !== 'auto') return null
6046
+ if (bridge.pending !== null) {
6047
+ await Promise.race([bridge.pending, new Promise((resolve) => { const timer = setTimeout(resolve, 3000); timer.unref?.() })])
6048
+ }
6049
+ if (bridge.state !== null) return bridge.state
6050
+ if (Date.now() - (bridge.lastProbeAt ?? 0) < 5000) return null
6051
+ bridge.lastProbeAt = Date.now()
6052
+ const ensured = await ensureRisd({ home: proxyHomeDir() }).catch(() => ({ ok: false, reason: 'spawn failed' }))
6053
+ if (ensured.ok !== true) {
6054
+ bridge.degraded = true
6055
+ return null
6056
+ }
6057
+ return attachBridgeState(ensured.state, cwd)
6058
+ }
6059
+
6060
+ function stopRisdBridge() {
6061
+ const bridge = risdBridge
6062
+ if (bridge === null) return
6063
+ // Releasing the lease is all this process owns: the daemon decides what to do
6064
+ // with the engine, and in phase 1a the engine is still ours, so nothing else
6065
+ // may be stopped from here.
6066
+ if (bridge.state !== null && bridge.leaseId !== null) void releaseLease(bridge.state, bridge.leaseId)
6067
+ bridge.state = null
6068
+ bridge.leaseId = null
6069
+ bridge.pending = null
6070
+ risdBridge = null
6071
+ }
6072
+
6073
+ /**
6074
+ * Ask the daemon for the read-only view and dress it up as the plugin's own.
6075
+ * @returns the decorated view, or null when the daemon is off/unreachable (the
6076
+ * caller then falls back to the local `proxyView`).
6077
+ */
6078
+ async function risdForwardedView(cwd, gitHost) {
6079
+ if (risdBridge === null || risdBridge.mode !== 'auto') return null
6080
+ const bridge = risdBridge
6081
+ if (bridge.state === null) {
6082
+ if (bridge.pending !== null) {
6083
+ await Promise.race([bridge.pending, new Promise((resolve) => setTimeout(resolve, 3000))])
6084
+ }
6085
+ if (bridge.state === null) return null
6086
+ }
6087
+ const base = await getProxyView(bridge.state, cwd)
6088
+ if (base === null || base.ok !== true) {
6089
+ // One failed read does not prove the daemon is gone: mark the bridge degraded,
6090
+ // KEEP the lease (a lost lease makes followDsh tear down tunnels that other
6091
+ // windows still use) and let the next call re-handshake (review C-P0-2).
6092
+ bridge.state = null
6093
+ bridge.degraded = true
6094
+ return null
6095
+ }
6096
+ return mergeRisdView(base, cwd, gitHost)
6097
+ }
6098
+
6099
+ async function mergeRisdView(base, cwd, gitHost) {
6100
+ const config = readProxyConfig(cwd)
6101
+ const watcher = janitorStatus()
6102
+ const inherited = inheritedEngine !== null && inheritedEngine.pid === base.pid ? inheritedEngine : null
6103
+ const redirectorRules = Number.isInteger(base.redirector?.rules) ? base.redirector.rules : buildProfile(config).rules.length
6104
+ return Object.assign({}, base, {
6105
+ risd: risdBridge !== null && risdBridge.state !== null
6106
+ ? { available: true, url: risdBridge.state.url, port: risdBridge.state.port, apiVersion: risdBridge.state.apiVersion }
6107
+ : { available: true, url: base.url ?? '', port: base.port ?? 0, apiVersion: base.apiVersion ?? 0 },
6108
+ rules: await proxyRulesView(cwd, config),
6109
+ git: gitProxyPlan(config, { host: gitHost }),
6110
+ redirector: Object.assign(redirectorStatusCached(), { rules: redirectorRules }),
6111
+ janitor: base.janitor ?? watcher,
6112
+ owner: base.owner ?? watcher.owner,
6113
+ inherited: inherited !== null,
6114
+ inheritedPid: inherited === null ? 0 : inherited.pid,
6115
+ inheritedFrom: inherited === null ? 0 : inherited.owner,
6116
+ inheritedSince: inherited === null ? '' : inherited.detectedAt,
6117
+ })
6118
+ }
6119
+
6120
+ /**
6121
+ * Where a rule's 启动/停止 button keeps its log.
6122
+ *
6123
+ * A separate directory, not `.dsh-ris-ide/logs`: those logs are scanned as panel
6124
+ * rows, and a program we started only to proxy it should not appear as a third
6125
+ * copy of itself in the program list.
6126
+ * @param cwd - workspace the rule belongs to.
6127
+ * @param ruleId - the rule's id (already validated as a plain string).
6128
+ * @returns absolute log path.
6129
+ */
6130
+ function proxyRunLogPath(cwd, ruleId) {
6131
+ const slug = String(ruleId).replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 80)
6132
+ return join(cwd, '.dsh-ris-ide', 'proxy-run', `${slug}.log`)
6133
+ }
6134
+
6135
+ /**
6136
+ * Build the program row `startProgram` needs, out of one rule.
6137
+ *
6138
+ * The row is synthesised rather than scanned: the dialog's rule is the source of
6139
+ * truth (it names an absolute executable or a bare program on PATH), and the
6140
+ * start path only has to know how to run it under the wrapper.
6141
+ * @param cwd - workspace (log location + default working directory).
6142
+ * @param rule - one decorated proxy rule.
6143
+ * @returns the program row.
6144
+ */
6145
+ function proxyRunProgram(cwd, rule) {
6146
+ const logPath = proxyRunLogPath(cwd, rule.id)
6147
+ const command = String(rule.program ?? '').trim()
6148
+ return {
6149
+ id: `proxy-run:${rule.id}`,
6150
+ name: programKey(command) || 'program',
6151
+ dir: cwd,
6152
+ // Absolute paths and bare names both work; quote so a path with spaces stays
6153
+ // one argument for the shell wrapper.
6154
+ startCommand: quoteShell(command),
6155
+ logName: basename(logPath, '.log'),
6156
+ logPath,
6157
+ stopGraceMs: 5000,
6158
+ running: null,
6159
+ kind: 'custom',
6160
+ }
6161
+ }
6162
+
6163
+ /** `GET` reads the proxy state, `POST` validates + saves the form. */
6164
+ /**
6165
+ * Start the daemon if it is not running and report where its page lives.
6166
+ *
6167
+ * Loopback-only, like every other proxy route: the page it returns is a LAN-less
6168
+ * 127.0.0.1 URL, and spawning a machine-level process is not something a remote
6169
+ * request may trigger.
6170
+ */
6171
+ async function serveRisdEnsure(ctx, req, res, options) {
6172
+ if (!isLoopbackRequest(req)) {
6173
+ throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6174
+ }
6175
+ // daemonMode=off means the plugin keeps ownership of the engine, the heartbeat
6176
+ // and the janitor. A spawned daemon unconditionally writes its heartbeat and arms
6177
+ // its own janitor, and the janitor REPLACES a watcher owned by a different pid —
6178
+ // so starting one here silently removed the plugin's crash cleanup (dsh crash left
6179
+ // the engine/bridge/git behind) and a daemon crash tore down the engine the plugin
6180
+ // was still using (review C2-P0-1). Off mode therefore keeps the pre-1.8
6181
+ // behaviour: answer "unavailable" and let the caller fall back to the standalone
6182
+ // window. Users who want the maintenance page opt into daemonMode=auto.
6183
+ if (options.daemonMode !== 'auto') {
6184
+ writeJson(res, 200, {
6185
+ ok: false,
6186
+ risd: { available: false, reason: 'daemonMode=off:IDE 请用独立窗口(把 daemonMode 设为 auto 可启用维护页)' },
6187
+ })
6188
+ return
6189
+ }
6190
+ const paused = risdHealReason()
6191
+ if (paused !== '') {
6192
+ writeJson(res, 200, { ok: false, risd: { available: false, reason: paused } })
6193
+ return
6194
+ }
6195
+ const ensured = await ensureRisd({ home: proxyHomeDir() })
6196
+ if (ensured.ok !== true) {
6197
+ // A version mismatch is not a crash: re-spawning the same old daemon cannot
6198
+ // fix it, so it must not spend breaker budget (review C-P2-1).
6199
+ const mismatch = ensured.reason === 'api-mismatch'
6200
+ if (!mismatch) noteRisdHealFailure(ensured.reason ?? 'unavailable')
6201
+ writeJson(res, 200, {
6202
+ ok: false,
6203
+ risd: { available: false, reason: mismatch ? 'risd 版本与插件不一致:请重启 dsh 以启动匹配版本' : (ensured.reason ?? 'unavailable') },
6204
+ })
6205
+ return
6206
+ }
6207
+ noteRisdHealSuccess()
6208
+ const state = ensured.state
6209
+ attachBridgeState(state, null)
6210
+ writeJson(res, 200, {
6211
+ ok: true,
6212
+ spawned: ensured.spawned === true,
6213
+ risd: {
6214
+ available: true,
6215
+ url: `http://127.0.0.1:${state.port}`,
6216
+ port: state.port,
6217
+ apiVersion: state.apiVersion,
6218
+ },
6219
+ })
6220
+ }
6221
+
6222
+ async function serveProxy(ctx, req, res, options) {
6223
+ try {
6224
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6225
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
6226
+ const method = req.method ?? 'GET'
6227
+ if (method === 'POST') {
6228
+ const body = await readJsonBody(req)
6229
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
6230
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
6231
+ const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
6232
+ const gitHostBody = typeof body.gitHost === 'string' ? body.gitHost : undefined
6233
+ // Phase 1b P4: when risd owns the proxy, it is also the only writer of the
6234
+ // machine-wide table. Forward the write and let the daemon's CAS reject a
6235
+ // stale form; the view returned to the dialog is still built locally (row
6236
+ // decoration needs this process's program list).
6237
+ const writeState = await risdBridgeState(cwd)
6238
+ if (writeState === null && risdBridge !== null && risdBridge.mode === 'auto') {
6239
+ // The daemon may still be alive: writing the machine-wide table here would
6240
+ // race it (split-brain rules/git). Only a confirmed-absent daemon falls back.
6241
+ const probe = await probeRisd({ home: proxyHomeDir() }).catch(() => ({ usable: false, reason: 'unreachable' }))
6242
+ if (probe.usable === true) {
6243
+ throw new TailError('bad-gateway', 'risd 正在运行但连接未就绪,本次保存未写入:请稍后重试,或在概览停掉 daemon 后重试', 503)
6244
+ }
6245
+ }
6246
+ if (writeState !== null) {
6247
+ const call = await saveProxy(writeState, { cwd, config: body.config, revision: body.revision, gitHost: gitHostBody })
6248
+ if (call.status === 409) {
6249
+ // Two different 409s reach this branch: a stale table (conflict, with
6250
+ // `conflict:true` and a revision) and a version mismatch between plugin
6251
+ // and daemon (`code:'api-mismatch'`, no conflict flag). Only the first is
6252
+ // something the dialog can recover from by reloading; the second needs a
6253
+ // dsh restart, so it keeps design §7.1's 503 instead of being reported as
6254
+ // "someone else changed the rules" (review C-P2-1).
6255
+ if (call.body !== null && call.body.code === 'api-mismatch') {
6256
+ throw new TailError('risd-upgrade-required', `${call.body.message ?? '插件与 risd 版本不一致'}:请重启 dsh,让插件启动匹配版本的 risd`, 503)
6257
+ }
6258
+ const view = await proxyView(cwd, gitHostBody)
6259
+ writeJson(res, 409, Object.assign({}, call.body, { view }))
6260
+ return
6261
+ }
6262
+ if (call.ok !== true) {
6263
+ throw new TailError('bad-gateway', `risd 写入失败:${call.body?.message ?? call.error ?? `HTTP ${call.status}`}`, 502)
6264
+ }
6265
+ const view = await proxyView(cwd, gitHostBody)
6266
+ writeJson(res, 200, Object.assign({}, view, { reloadNote: call.body?.reloadNote ?? '' }))
6267
+ return
6268
+ }
6269
+ // The dialog shows the WHOLE machine-wide table, so its payload is
6270
+ // authoritative for the rows a human owns (source user/auto): a row the
6271
+ // payload no longer carries was deleted. Driven rows (source yds) are owned
6272
+ // by the bridge, which upserts them by id and retires them itself.
6273
+ const incoming = body.config !== null && typeof body.config === 'object' ? body.config : {}
6274
+ const stored = readProxyConfig(cwd)
6275
+ // Optimistic concurrency: the payload names the table it was rendered from.
6276
+ // An empty/absent revision is accepted (the CLI writes without one), but a
6277
+ // MISMATCH means someone else changed the table in between — refuse and hand
6278
+ // the current view back, so the dialog reloads instead of dropping their rows.
6279
+ const baseRevision = typeof body.revision === 'string' ? body.revision.trim() : ''
6280
+ const currentRevision = configRevision(stored)
6281
+ if (baseRevision !== '' && baseRevision !== currentRevision) {
6282
+ const view = await proxyView(cwd)
6283
+ writeJson(res, 409, {
6284
+ ok: false,
6285
+ conflict: true,
6286
+ code: 'conflict',
6287
+ message: '规则表已在别处被修改,本次改动未写入',
6288
+ revision: currentRevision,
6289
+ view,
6290
+ })
6291
+ return
6292
+ }
6293
+ const rows = Array.isArray(incoming.rules)
6294
+ ? incoming.rules
6295
+ .filter((rule) => rule !== null && typeof rule === 'object')
6296
+ .map((rule) => Object.assign({}, rule, { workspace: rule.workspace ?? cwd }))
6297
+ : []
6298
+ const keptIds = new Set(rows.map((rule) => String(rule.id ?? '')))
6299
+ const retired = stored.rules
6300
+ .filter((rule) => rule.source !== 'yds' && !keptIds.has(rule.id))
6301
+ .map((rule) => rule.id)
6302
+ const written = mergeConfigs(
6303
+ Object.assign({}, stored, { rules: stored.rules.filter((rule) => !retired.includes(rule.id)) }),
6304
+ { socks: incoming.socks, listenPort: incoming.listenPort, rules: rows, workspace: cwd },
6305
+ )
6306
+ writeProxyConfig(cwd, written)
6307
+ // Clean up what the PREVIOUS table applied before the new one takes effect:
6308
+ // the bridge reload below restarts ProxyBridge, but the scoped git entry is
6309
+ // not part of that profile and would otherwise stay on the old host.
6310
+ const git = await reconcileGitProxy(cwd)
6311
+ // Apply without a manual restart: our own engine watches proxy.json and
6312
+ // swaps its allow-list/listeners in place; ProxyBridge reads its profile only
6313
+ // at start, so the elevated watchdog restarts just that process (no UAC, the
6314
+ // dialog never has to ask the user to stop/start).
6315
+ const bridge = redirectorStatusCached()
6316
+ let reloadNote = ''
6317
+ // Revoking is part of switching: ProxyBridge parses its profile only at start,
6318
+ // so a failed reload would leave the OLD rules intercepting while the dialog
6319
+ // reports a successful save. Stop the bridge instead of leaving stale rules.
6320
+ const revoke = async (reason) => {
6321
+ const stopped = await stopRedirector()
6322
+ return `${reason};${stopped.stopped === true
6323
+ ? '已停止系统层拦截,避免继续按旧规则代理'
6324
+ : `未能停止系统层拦截(${stopped.reason ?? '未知原因'}),旧规则可能仍在生效`}`
6325
+ }
6326
+ if (bridge.running === true) {
6327
+ // ONE call does the whole job: ProxyBridge reads its profile only at start,
6328
+ // so a reload that does not rewrite the profile would relaunch the OLD rules
6329
+ // and still report success (that was B3). The helper writes first, then
6330
+ // restarts, and only claims a side was reloaded when it saw the new pid.
6331
+ try {
6332
+ // Which sides exist per platform is `reloadRedirectorsWithProfile`'s own
6333
+ // default; spelling it out here duplicated that knowledge and would drift
6334
+ // when the default changes (review C3-P2-8).
6335
+ const reload = await reloadRedirectorsWithProfile(cwd)
6336
+ const done = Array.isArray(reload.reloaded) ? reload.reloaded : []
6337
+ const skipped = Array.isArray(reload.skipped) ? reload.skipped : []
6338
+ reloadNote = done.length > 0
6339
+ ? '系统层拦截已按新规则自动重启'
6340
+ : await revoke(`系统层拦截未重载:${skipped.map((item) => `${item.side}:${item.reason}`).join(';') || reload.reason || '未知原因'}`)
6341
+ } catch (error) {
6342
+ reloadNote = await revoke(`系统层拦截未重载:${error?.message ?? error}`)
6343
+ }
6344
+ }
6345
+ const view = await proxyView(cwd, typeof body.gitHost === 'string' ? body.gitHost : undefined)
6346
+ writeJson(res, 200, Object.assign({}, view, { reloadNote, git }))
6347
+ return
6348
+ }
6349
+ if (method !== 'GET') throw new TailError('method-not-allowed', 'GET or POST', 405)
6350
+ const sessionId = url.searchParams.get('sessionId') ?? ''
6351
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
6352
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
6353
+ const gitHost = url.searchParams.get('gitHost') ?? undefined
6354
+ // Phase 1a: when risd is opted in and reachable the VIEW comes from the
6355
+ // daemon (single source for config/revision/engine status); the plugin only
6356
+ // decorates it. Any daemon problem falls back to the local view, so the
6357
+ // dialog never breaks because an optional process is down.
6358
+ writeJson(res, 200, (await risdForwardedView(cwd, gitHost)) ?? await proxyView(cwd, gitHost))
6359
+ } catch (error) {
6360
+ writeTailError(res, error)
6361
+ }
6362
+ }
6363
+
6364
+ /**
6365
+ * Where the git proxy we wrote is remembered.
6366
+ *
6367
+ * `stop` (and the exit hook) must undo EXACTLY what `start` wrote: the key is
6368
+ * host-scoped when the repo has an origin, global otherwise, and clearing the
6369
+ * wrong one would either leave a dangling proxy or stomp the user's own setting.
6370
+ * @returns {string} absolute path of the state file.
6371
+ */
6372
+ function gitProxyStatePath() {
6373
+ return join(proxyHomeDir(), 'git-proxy.json')
6374
+ }
6375
+
6376
+ /** @returns {{key: string, host: string}} the entry start wrote, or empty strings. */
6377
+ function readGitProxyState() {
6378
+ try {
6379
+ const raw = JSON.parse(readFileSync(gitProxyStatePath(), 'utf8'))
6380
+ return {
6381
+ key: typeof raw?.key === 'string' ? raw.key : '',
6382
+ host: typeof raw?.host === 'string' ? raw.host : '',
6383
+ }
6384
+ } catch {
6385
+ return { key: '', host: '' }
6386
+ }
6387
+ }
6388
+
6389
+ /**
6390
+ * Remember (or forget) the git proxy entry.
6391
+ * @param {{key: string, host: string}|null} state - null clears the file.
6392
+ */
6393
+ function writeGitProxyState(state) {
6394
+ const path = gitProxyStatePath()
6395
+ if (state === null) {
6396
+ try { rmSync(path, { force: true }) } catch { /* nothing to clear */ }
6397
+ return
6398
+ }
6399
+ mkdirSync(dirname(path), { recursive: true })
6400
+ writeFileSync(path, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 })
6401
+ }
6402
+
6403
+ /**
6404
+ * Host of the workspace's `origin` remote, so the proxy entry is scoped to one
6405
+ * server instead of being a machine-wide `http.proxy`.
6406
+ * @param {string} cwd - workspace root.
6407
+ * @returns {string} hostname, or '' when there is no readable remote.
6408
+ */
6409
+ function gitOriginHost(cwd) {
6410
+ const out = spawnSync('git', ['-C', cwd, 'config', '--get', 'remote.origin.url'], {
6411
+ encoding: 'utf8', windowsHide: true, timeout: 4000,
6412
+ })
6413
+ if (out.status !== 0 || typeof out.stdout !== 'string') return ''
6414
+ try { return new URL(out.stdout.trim()).host } catch { return '' }
6415
+ }
6416
+
6417
+ /**
6418
+ * Host of the enabled `git` rule, if the table declares one.
6419
+ *
6420
+ * This is the user's own statement of "git goes to this server" (yds writes it
6421
+ * from `git.url`), so it outranks the workspace's `origin` — a mirror or a
6422
+ * proxy-fronted clone must not decide where git may tunnel to.
6423
+ * @param {string} cwd - workspace root (only used to find the shared config).
6424
+ * @returns {string} the first host pattern, or ''.
6425
+ */
6426
+ function gitRuleHost(cwd) {
6427
+ const rules = readProxyConfig(cwd).rules
6428
+ for (const rule of rules) {
6429
+ if (rule.enabled !== true) continue
6430
+ if (programKey(rule.program) !== 'git') continue
6431
+ const first = String(rule.hosts ?? '').split(',')[0].trim()
6432
+ if (first !== '') return first
6433
+ }
6434
+ return ''
6435
+ }
6436
+
6437
+ /**
6438
+ * Write or clear the git proxy that belongs to the running tunnel.
6439
+ *
6440
+ * git reads this from its own config, so a plain `git` command in any terminal —
6441
+ * and the dsh-git plugin — goes through the tunnel without a per-command flag.
6442
+ * @param {{cwd: string, host?: string, enabled: boolean}} options - target and direction.
6443
+ * @returns {Promise<{ok: boolean, key?: string, error?: string}>} outcome.
6444
+ */
6445
+ async function syncGitProxy({ cwd, host, enabled }) {
6446
+ const previous = readGitProxyState()
6447
+ if (enabled !== true) {
6448
+ const key = previous.key
6449
+ if (key === '') return { ok: true, key: '' }
6450
+ const cleared = await runGitConfig(['--unset', key])
6451
+ const windowsCleared = runWindowsGitConfig(['--unset', key])
6452
+ writeGitProxyState(null)
6453
+ return { ok: true, key, cleared: cleared.ok === true, windowsCleared: windowsCleared.ok === true }
6454
+ }
6455
+ // Precedence: an explicit host, then the table's own git rule, then whatever we
6456
+ // wrote last time, and only then the repo's origin (a mirror is not a target).
6457
+ const target = (typeof host === 'string' && host !== '')
6458
+ ? host
6459
+ : (gitRuleHost(cwd) || (previous.host !== '' ? previous.host : gitOriginHost(cwd)))
6460
+ if (target === '') return { ok: false, error: '没有 git 规则也没有 origin,无法确定代理作用域', key: '' }
6461
+ // A stale entry for another host would keep a dead proxy alive for that remote.
6462
+ if (previous.key !== '' && previous.host !== '' && previous.host !== target) {
6463
+ await runGitConfig(['--unset', previous.key])
6464
+ writeGitProxyState(null)
6465
+ }
6466
+ const plan = gitProxyPlan(readProxyConfig(cwd), { host: target, enabled: true })
6467
+ if (plan.value === '') return { ok: false, error: '没有可用的 SOCKS 地址', key: plan.key }
6468
+ const written = await runGitConfig([plan.key, plan.value])
6469
+ if (written.ok !== true) return { ok: false, error: written.error, key: plan.key }
6470
+ // The Windows-side git reads its own config file AND cannot resolve the internal
6471
+ // host (its DNS knows nothing about gitlab.hanslaser.com), so socks5h has to be in
6472
+ // that file too — otherwise YonCode's git fails before any interception can happen.
6473
+ const windows = runWindowsGitConfig([plan.key, plan.value])
6474
+ writeGitProxyState({ key: plan.key, host: target, windows: windows.ok === true })
6475
+ return { ok: true, key: plan.key, host: target, windows }
6476
+ }
6477
+
6478
+ /**
6479
+ * Re-align the scoped git entry with the table that was just saved.
6480
+ *
6481
+ * Saving rules used to write `proxy.json` and reload the bridge only; the
6482
+ * `git config --global` entry of the PREVIOUS host survived, so removing or
6483
+ * repointing the git rule left every terminal pointed at a dead tunnel. A
6484
+ * surviving git rule wins (syncGitProxy unsets the old key first, and only when
6485
+ * the recorded value is still ours); with no git rule left, ours is cleared.
6486
+ * @param {string} cwd - workspace root.
6487
+ * @returns {Promise<object>} outcome of the sync/clear.
6488
+ */
6489
+ async function reconcileGitProxy(cwd) {
6490
+ const host = gitRuleHost(cwd)
6491
+ if (host === '') return syncGitProxy({ cwd, enabled: false })
6492
+ return syncGitProxy({ cwd, host, enabled: true })
6493
+ }
6494
+
6495
+ /** Synchronous git-proxy undo for the exit hook, which cannot await anything. */
6496
+ function clearGitProxySync() {
6497
+ const { key } = readGitProxyState()
6498
+ if (key === '') return
6499
+ try { spawnSync('git', ['config', '--global', '--unset', key], { windowsHide: true, timeout: 4000 }) } catch { /* best effort */ }
6500
+ // Same undo on the Windows side: leaving a dead socks address there breaks git for
6501
+ // every Windows tool until someone notices.
6502
+ try { runWindowsGitConfig(['--unset', key]) } catch { /* best effort */ }
6503
+ writeGitProxyState(null)
6504
+ }
6505
+
6506
+ /** Run one `git config --global` mutation; a missing git is a reported no-op. */
6507
+ function runGitConfig(args) {
6508
+ return new Promise((resolvePromise) => {
6509
+ const child = spawn('git', ['config', '--global', ...args], { windowsHide: true })
6510
+ let stderr = ''
6511
+ let settled = false
6512
+ const done = (result) => { if (!settled) { settled = true; resolvePromise(result) } }
6513
+ child.stderr?.on('data', (chunk) => { if (stderr.length < 4096) stderr += chunk.toString('utf8') })
6514
+ child.on('error', (error) => done({ ok: false, error: isMissingExecutable(error) ? '本机没有安装 git' : String(error?.message ?? error) }))
6515
+ child.on('close', (code) => done(code === 0 ? { ok: true } : { ok: false, error: stderr.trim() || `git exited with ${code}` }))
6516
+ })
6517
+ }
6518
+
6519
+ /** Start/stop the engine and write/clear the scoped git proxy entry. */
6520
+ async function serveProxyAction(ctx, req, res, options) {
6521
+ try {
6522
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6523
+ const body = await readJsonBody(req)
6524
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
6525
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
6526
+ const cwd = resolveCwd(ctx, sessionId, typeof body.cwd === 'string' ? body.cwd : undefined)
6527
+ const action = typeof body.action === 'string' ? body.action : 'status'
6528
+ const gitHost = typeof body.gitHost === 'string' ? body.gitHost : undefined
6529
+ // Engine + bridge + git are the daemon's once it owns the proxy; the per-rule
6530
+ // 启动/停止 buttons stay here because they launch a child of THIS process (the
6531
+ // injection only works on a child we spawn ourselves).
6532
+ const daemonActions = new Set(['start', 'stop', 'git-on', 'git-off', 'redirector-sync', 'redirector-start', 'redirector-stop', 'redirector-restart', 'status'])
6533
+ const actionState = await risdBridgeState(cwd)
6534
+ if (actionState === null && risdBridge !== null && risdBridge.mode === 'auto' && daemonActions.has(action)) {
6535
+ const probe = await probeRisd({ home: proxyHomeDir() }).catch(() => ({ usable: false, reason: 'unreachable' }))
6536
+ if (probe.usable === true) {
6537
+ throw new TailError('bad-gateway', `risd 正在运行但连接未就绪,${action} 未执行:请稍后重试`, 503)
6538
+ }
6539
+ }
6540
+ if (actionState !== null && daemonActions.has(action)) {
6541
+ const call = await proxyAction(actionState, { cwd, action, gitHost })
6542
+ if (call.ok !== true) {
6543
+ // No answer at all (network error / timeout) is not a business failure: the
6544
+ // action did not run, and the panel has no second entry point for the engine
6545
+ // any more. Answer 503 + "retry", and re-arm the handshake so the retry can
6546
+ // succeed instead of hitting the same dead socket (review C-P2-8).
6547
+ if (call.status === 0 || call.body === null) {
6548
+ void risdBridgeState(cwd).catch(() => {})
6549
+ throw new TailError('risd-unavailable', `risd 不可用(${call.error ?? 'no answer'}),${action} 未执行:请稍后重试,页面会在下一次重新唤起 daemon`, 503)
6550
+ }
6551
+ throw new TailError('bad-gateway', `risd 操作失败:${call.body?.message ?? call.error ?? `HTTP ${call.status}`}`, 502)
6552
+ }
6553
+ if (action === 'start' || action === 'stop') inheritedEngine = null
6554
+ writeJson(res, 200, Object.assign({ ok: true, action, result: call.body?.result }, await proxyView(cwd, gitHost)))
6555
+ return
6556
+ }
6557
+ let result
6558
+ if (action === 'start') {
6559
+ // One button, three layers: engine (spawned children) + system-level
6560
+ // interception (everything else, UAC/root is the expected prompt) + the git
6561
+ // config entry (so a plain `git` and dsh-git inherit the tunnel). Stopping
6562
+ // undoes all three, and so does the host exit hook.
6563
+ //
6564
+ // Reached only when the daemon is unavailable (otherwise the branch above
6565
+ // answers): this engine is ours, so install the exit hook that auto mode would
6566
+ // otherwise rely on the daemon to provide (review C2-P1-3).
6567
+ armLocalProxyCleanup()
6568
+ const engine = await startProxy(cwd)
6569
+ const redirector = await startRedirectors()
6570
+ const git = await syncGitProxy({ cwd, host: gitHost, enabled: true })
6571
+ if (engine.ok === true) inheritedEngine = null
6572
+ result = Object.assign({}, engine, { redirector, git })
6573
+ } else if (action === 'stop') {
6574
+ const git = await syncGitProxy({ cwd, host: gitHost, enabled: false })
6575
+ const redirector = await stopRedirector()
6576
+ const stopped = await stopProxy(cwd)
6577
+ disarmLocalProxyCleanup()
6578
+ // The banner must not come back once the adopted engine is really gone.
6579
+ if (proxyPid() === null) inheritedEngine = null
6580
+ result = Object.assign({}, stopped, { redirector, git })
6581
+ } else if (action === 'git-on' || action === 'git-off') {
6582
+ const plan = gitProxyPlan(readProxyConfig(cwd), { host: gitHost, enabled: action === 'git-on' })
6583
+ result = action === 'git-on'
6584
+ ? Object.assign({ key: plan.key, value: plan.value }, await runGitConfig([plan.key, plan.value]))
6585
+ : Object.assign({ key: plan.key }, await runGitConfig(['--unset', plan.key]))
6586
+ } else if (action === 'run' || action === 'run-stop') {
6587
+ // Start/stop the rule's program OURSELVES: injection only works on a child
6588
+ // process, so "配置好规则 → 点启动" is the only way to proxy a program that
6589
+ // the user would otherwise launch by hand.
6590
+ const ruleId = typeof body.ruleId === 'string' ? body.ruleId : ''
6591
+ if (ruleId === '') throw new TailError('bad-request', 'ruleId is required', 400)
6592
+ const rule = readProxyConfig(cwd).rules.find((item) => item.id === ruleId)
6593
+ if (rule === undefined) throw new TailError('bad-request', `没有规则 ${ruleId}`, 404)
6594
+ const program = proxyRunProgram(cwd, rule)
6595
+ if (action === 'run-stop') {
6596
+ result = await stopLogPath(program.logPath, options?.stopGraceMs ?? DEFAULT_STOP_GRACE_MS)
6597
+ } else {
6598
+ if (rule.enabled !== true) throw new TailError('bad-request', '规则未启用,启动后不会走代理', 400)
6599
+ if (String(rule.program ?? '').trim() === '') throw new TailError('bad-request', '规则还没选程序', 400)
6600
+ if (!isSocksCapableProgram(rule.program)) throw new TailError('bad-request', `${programKey(rule.program)} 不支持 SOCKS,只能走 127.0.0.1 映射`, 400)
6601
+ const started = await startProgram(cwd, dirname(program.logPath), program, options)
6602
+ result = { started: started.alreadyRunning !== true, program: started.program?.logPath ?? program.logPath }
6603
+ }
6604
+ } else if (action === 'redirector-sync') {
6605
+ // Export the machine-wide table as a ProxyBridge profile and report the
6606
+ // exact command. Starting it needs root/UAC, which a web route cannot ask
6607
+ // for, so the command is returned for the user (or an agent with rights).
6608
+ result = await syncRedirector(cwd, { start: false })
6609
+ } else if (action === 'redirector-start') {
6610
+ result = await syncRedirector(cwd, { start: true })
6611
+ } else if (action === 'redirector-stop') {
6612
+ result = await stopRedirector()
6613
+ } else if (action === 'redirector-restart') {
6614
+ // Same contract as the daemon: stop, let the profile write settle, start.
6615
+ const stopped = await stopRedirector()
6616
+ await new Promise((resolve) => setTimeout(resolve, 300))
6617
+ const started = await startRedirectors()
6618
+ result = {
6619
+ stopped,
6620
+ started: started.started ?? [],
6621
+ skipped: started.skipped ?? [],
6622
+ running: started.running === true,
6623
+ }
6624
+ } else if (action !== 'status') {
6625
+ throw new TailError('bad-request', `unknown proxy action "${action}"`, 400)
6626
+ }
6627
+ writeJson(res, 200, Object.assign({ ok: true, action, result }, await proxyView(cwd, gitHost)))
6628
+ } catch (error) {
6629
+ writeTailError(res, error)
6630
+ }
6631
+ }
6632
+
6633
+ /**
6634
+ * Programs the rule table offers in its picker.
6635
+ *
6636
+ * Deliberately SOCKS-aware programs only: a rule other than these cannot be
6637
+ * proxied by injection (its only route is a 127.0.0.1 listener, which needs no
6638
+ * picker entry), so offering them would promise something we cannot deliver.
6639
+ */
6640
+ const PROXY_PROGRAM_SUGGESTIONS = ['java', 'javaw', 'mvn', 'git', 'node', 'npm', 'curl', 'python', 'python3']
6641
+
6642
+ /** Distinct program names of the processes on THIS side of the OS boundary. */
6643
+ function localProgramNames() {
6644
+ const names = new Set()
6645
+ if (IS_WINDOWS) return names
6646
+ try {
6647
+ for (const entry of readdirSync('/proc')) {
6648
+ if (!/^\d+$/.test(entry)) continue
6649
+ try {
6650
+ const commandLine = readFileSync(`/proc/${entry}/cmdline`, 'utf8')
6651
+ const first = commandLine.split('\0')[0]
6652
+ if (first !== '') names.add(basename(first))
6653
+ } catch { /* the process exited between readdir and read */ }
6654
+ }
6655
+ } catch { /* no /proc: the suggestions still make the picker usable */ }
6656
+ return names
6657
+ }
6658
+
6659
+ /** Program names of the WINDOWS side, via PowerShell (interop may be off). */
6660
+ function windowsProgramNames() {
6661
+ // A cold PowerShell start is 3s here and worse under load: the old 4s budget made
6662
+ // the picker silently drop every Windows entry. Cache it and give it room.
6663
+ const cached = windowsProgramCache
6664
+ if (cached !== null && Date.now() - cached.at < WINDOWS_PROGRAM_TTL_MS) return Promise.resolve(new Set(cached.names))
6665
+ return new Promise((resolvePromise) => {
6666
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
6667
+ 'Get-Process | Select-Object -ExpandProperty ProcessName -Unique'], { windowsHide: true })
6668
+ let stdout = ''
6669
+ let settled = false
6670
+ const done = (names) => { if (!settled) { settled = true; resolvePromise(names) } }
6671
+ child.stdout?.on('data', (chunk) => { if (stdout.length < 200000) stdout += chunk.toString('utf8') })
6672
+ child.on('error', () => done(new Set()))
6673
+ child.on('timeout', () => done(new Set()))
6674
+ child.on('close', () => {
6675
+ const names = new Set(stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== ''))
6676
+ if (names.size > 0) windowsProgramCache = { at: Date.now(), names: [...names] }
6677
+ done(names)
6678
+ })
6679
+ setTimeout(() => done(new Set()), TIMEOUT_WINDOWS_PROGRAMS_MS).unref?.()
6680
+ })
6681
+ }
6682
+
6683
+ /** Last successful Windows process list (the probe is too slow to repeat per open). */
6684
+ let windowsProgramCache = null
6685
+
6686
+ /** Drop the cached Windows process list (tests, or after a program was installed). */
6687
+ export function resetWindowsProgramCache() {
6688
+ windowsProgramCache = null
6689
+ }
6690
+ /** How long a successful Windows process list stays usable. */
6691
+ const WINDOWS_PROGRAM_TTL_MS = 20000
6692
+ /** Budget for one PowerShell process listing (cold start alone is ~3s). */
6693
+ const TIMEOUT_WINDOWS_PROGRAMS_MS = 12000
6694
+
6695
+ /** `GET` the program picker's candidates (this side + Windows when reachable). */
6696
+ /**
6697
+ * List one directory for the rules table's 「固定程序」 browser.
6698
+ *
6699
+ * A rule can point at an executable that is not running yet, so the panel needs
6700
+ * a way to pick an absolute path — by hand typing it is error-prone, and the
6701
+ * workspace tree only covers one root. Directories come first; files are limited
6702
+ * to things that can plausibly be programs (executable bit, or a known suffix),
6703
+ * so a build output directory does not bury the java.exe the user came for.
6704
+ * @param ctx - host context.
6705
+ * @param req - `?path=<dir>`; missing means the platform temp/home root.
6706
+ * @param res - JSON response.
6707
+ * @param options - host options.
6708
+ */
6709
+ async function serveProxyBrowse(ctx, req, res, options) {
6710
+ try {
6711
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6712
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
6713
+ const sessionId = url.searchParams.get('sessionId') ?? ''
6714
+ const clientCwd = url.searchParams.get('cwd') ?? ''
6715
+ // Two file systems can hold the same rule's program: the host's own (posix) and,
6716
+ // from WSL, the Windows one under /mnt. `side` says which spelling the UI uses.
6717
+ const side = url.searchParams.get('side') === 'windows' || (IS_WINDOWS && url.searchParams.get('side') !== 'local')
6718
+ ? 'windows'
6719
+ : 'local'
6720
+ const requested = url.searchParams.get('path') ?? ''
6721
+ const windowsRoots = side === 'windows' ? windowsBrowseRoots() : []
6722
+ // Translate the UI's spelling into something readdir understands. Keeping the
6723
+ // original in `display` is what lets a click write back `D:\…` instead of `/mnt/d/…`.
6724
+ let target
6725
+ let display
6726
+ if (side === 'windows') {
6727
+ const asWindows = requested !== '' && /^[A-Za-z]:[\\/]/.test(requested)
6728
+ const asPosix = requested.startsWith('/mnt/')
6729
+ if (asWindows === true) {
6730
+ target = windowsToPosixPath(requested)
6731
+ display = requested.replace(/\//g, '\\').replace(/\\+$/, '') || requested
6732
+ } else if (asPosix === true) {
6733
+ target = requested
6734
+ display = posixToWindowsPath(requested)
6735
+ } else if (requested === '') {
6736
+ const first = windowsRoots[0]
6737
+ if (first === undefined) throw new TailError('bad-request', '这台机器上没有可浏览的 Windows 盘(/mnt/<盘> 不存在)', 400)
6738
+ target = windowsToPosixPath(first.path)
6739
+ display = first.path
6740
+ } else {
6741
+ throw new TailError('bad-request', `Windows 侧需要盘符路径(如 D:\\Program Files):${requested}`, 400)
6742
+ }
6743
+ } else {
6744
+ // Only the host side needs a session cwd; the Windows side is absolute by nature
6745
+ // and must keep working when the caller has no session (CLI, tests).
6746
+ const root = resolveCwd(ctx, sessionId, clientCwd)
6747
+ target = requested === '' ? root : resolve(root, expandHome(requested))
6748
+ display = target
6749
+ }
6750
+ if (target === '') throw new TailError('bad-request', `无法解析路径:${requested}`, 400)
6751
+
6752
+ let entries
6753
+ try {
6754
+ entries = await readdir(target, { withFileTypes: true })
6755
+ } catch (error) {
6756
+ throw new TailError('bad-request', `无法读取目录 ${display}:${error?.code ?? error}`, 400)
6757
+ }
6758
+ const dirs = []
6759
+ const files = []
6760
+ for (const entry of entries) {
6761
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name.startsWith('$')) continue
6762
+ const full = join(target, entry.name)
6763
+ const shown = side === 'windows' ? posixToWindowsPath(full) : full
6764
+ if (entry.isDirectory()) {
6765
+ dirs.push({ name: entry.name, path: shown })
6766
+ continue
6767
+ }
6768
+ if (!entry.isFile()) continue
6769
+ // On /mnt every Windows file carries the exec bit (drvfs), so the mode fallback
6770
+ // would list DLLs and logs; there only the suffix list is meaningful.
6771
+ const looksProgram = side === 'windows'
6772
+ ? PROGRAM_SUFFIXES.some((suffix) => entry.name.toLowerCase().endsWith(suffix))
6773
+ : isProgramFile(full, entry.name)
6774
+ if (looksProgram) files.push({ name: entry.name, path: shown })
6775
+ }
6776
+ dirs.sort((a, b) => a.name.localeCompare(b.name))
6777
+ files.sort((a, b) => a.name.localeCompare(b.name))
6778
+ const parentTarget = dirname(target) === target ? null : dirname(target)
6779
+ writeJson(res, 200, {
6780
+ ok: true,
6781
+ side,
6782
+ path: display,
6783
+ parent: parentTarget === null ? null : (side === 'windows' ? posixToWindowsPath(parentTarget) : parentTarget),
6784
+ roots: side === 'windows' ? windowsRoots : browseRoots(),
6785
+ dirs: dirs.slice(0, 300),
6786
+ files: files.slice(0, 300),
6787
+ })
6788
+ } catch (error) {
6789
+ writeTailError(res, error)
6790
+ }
6791
+ }
6792
+
6793
+ /**
6794
+ * Quick-jump roots for the Windows side of the picker (opened from WSL via /mnt).
6795
+ * @returns {Array<{name: string, path: string}>} roots with WINDOWS paths.
6796
+ */
6797
+ function windowsBrowseRoots() {
6798
+ const roots = []
6799
+ const seen = new Set()
6800
+ const push = (name, posix) => {
6801
+ if (existsSync(posix) !== true || seen.has(posix)) return
6802
+ seen.add(posix)
6803
+ roots.push({ name, path: posixToWindowsPath(posix) })
6804
+ }
6805
+ for (const letter of ['c', 'd', 'e', 'f']) push(`Windows ${letter.toUpperCase()}:`, `/mnt/${letter}`)
6806
+ for (const letter of ['c', 'd']) {
6807
+ push(`${letter.toUpperCase()}:\\Program Files`, `/mnt/${letter}/Program Files`)
6808
+ push(`${letter.toUpperCase()}:\\YonCode`, `/mnt/${letter}/Program Files/YonCode`)
6809
+ push(`${letter.toUpperCase()}:\\Git`, `/mnt/${letter}/Program Files/Git`)
6810
+ }
6811
+ return roots
6812
+ }
6813
+
6814
+ /** Names that look like a launchable program, for the browse listing. */
6815
+ function isProgramFile(fullPath, name) {
6816
+ const lower = name.toLowerCase()
6817
+ if (PROGRAM_SUFFIXES.some((suffix) => lower.endsWith(suffix))) return true
6818
+ try {
6819
+ // POSIX marks executables with a mode bit; Windows has no such bit and is
6820
+ // covered by the suffix list above.
6821
+ return (statSync(fullPath).mode & 0o111) !== 0
6822
+ } catch {
6823
+ return false
6824
+ }
6825
+ }
6826
+
6827
+ /** Suffixes the file browser always shows (plus anything with an exec bit). */
6828
+ const PROGRAM_SUFFIXES = ['.exe', '.cmd', '.bat', '.ps1', '.jar', '.sh', '.bin', '.mjs', '.cjs']
6829
+
6830
+ /** Quick-jump roots offered by the file browser. */
6831
+ function browseRoots() {
6832
+ // The tree starts at the two things a program path can live under, and nothing
6833
+ // else: the filesystem root (every path is reachable from it) and, on WSL, the
6834
+ // Windows disks. Workspace/home/temp shortcuts only pushed the real start down.
6835
+ const roots = []
6836
+ if (IS_WINDOWS) {
6837
+ for (const letter of ['C', 'D', 'E']) {
6838
+ if (existsSync(`${letter}:\\`) === true) roots.push({ name: `磁盘 ${letter}:`, path: `${letter}:\\` })
6839
+ }
6840
+ return roots
6841
+ }
6842
+ roots.push({ name: '根路径 /', path: '/' })
6843
+ for (const letter of ['c', 'd']) {
6844
+ if (existsSync(`/mnt/${letter}`) === true) roots.push({ name: `Windows ${letter.toUpperCase()}:`, path: `/mnt/${letter}` })
6845
+ }
6846
+ return roots
6847
+ }
6848
+
6849
+ async function serveProxyPrograms(ctx, req, res, options) {
6850
+ try {
6851
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6852
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
6853
+ const side = engineSide()
6854
+ // On Windows the local side IS the Windows side; inside WSL both sides are
6855
+ // reachable (the picker must offer navicat.exe even though the engine runs in
6856
+ // the Linux side), so the Windows probe runs on either branch.
6857
+ // Only programs we can actually proxy are listed: injecting the tunnel means
6858
+ // setting a SOCKS address (env or JVM flag), and a program that has no SOCKS
6859
+ // client cannot be helped that way.
6860
+ const capable = (names) => names
6861
+ .filter((name) => isSocksCapableProgram(name))
6862
+ .map((name) => ({ name, side: engineSide() }))
6863
+ const local = IS_WINDOWS
6864
+ ? capable([...await windowsProgramNames()].map((name) => (name.endsWith('.exe') ? name : `${name}.exe`)))
6865
+ .map((item) => ({ ...item, side: 'windows' }))
6866
+ : capable([...localProgramNames()])
6867
+ let remote = []
6868
+ if (!IS_WINDOWS) {
6869
+ const names = await windowsProgramNames()
6870
+ if (names.size > 0) {
6871
+ remote = capable([...names].map((name) => (name.endsWith('.exe') ? name : `${name}.exe`)))
6872
+ .map((item) => ({ ...item, side: 'windows' }))
6873
+ }
6874
+ }
6875
+ const suggested = PROXY_PROGRAM_SUGGESTIONS.map((name) => ({ name, side, suggested: true }))
6876
+ const seen = new Set()
6877
+ const programs = []
6878
+ for (const item of [...local, ...remote, ...suggested]) {
6879
+ const key = `${item.side}:${item.name.toLowerCase()}`
6880
+ if (seen.has(key)) continue
6881
+ seen.add(key)
6882
+ programs.push(item)
6883
+ }
6884
+ programs.sort((a, b) => Number(b.suggested === true) - Number(a.suggested === true) || a.name.localeCompare(b.name))
6885
+ writeJson(res, 200, {
6886
+ ok: true,
6887
+ side,
6888
+ // Why the list is short: a program without a SOCKS client can only use a
6889
+ // 127.0.0.1 listener, and those need no entry here.
6890
+ note: '只列出支持 SOCKS 的程序(java/git/node/curl 等);其它程序只能靠 127.0.0.1 同端口映射,无需在此选择。',
6891
+ programs: programs.slice(0, 400),
6892
+ })
6893
+ } catch (error) {
6894
+ writeTailError(res, error)
6895
+ }
6896
+ }
6897
+
5168
6898
  async function serveDebug(ctx, req, res, options) {
5169
6899
  try {
5170
6900
  if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
@@ -5346,6 +7076,80 @@ async function serveStart(ctx, req, res, options) {
5346
7076
  * @param options - `{ stopGraceMs }`.
5347
7077
  * @returns `{ alreadyRunning, program }`.
5348
7078
  */
7079
+ /**
7080
+ * Decide whether a program needs its dependencies installed before it can run.
7081
+ *
7082
+ * A freshly cloned frontend has no `node_modules`, and the failure it produces
7083
+ * (`cross-env: not found`, `vite: not found`) looks like a broken command rather
7084
+ * than a missing install. Installing up front — with the output going into the same
7085
+ * log the panel already tails — turns that into a visible, self-healing step.
7086
+ * @param {string} cwd - program working directory.
7087
+ * @returns {{pm: string, args: string[], dir: string}|null} plan, or null when the
7088
+ * directory has no package.json or already has dependencies.
7089
+ */
7090
+ export function installPlanFor(cwd) {
7091
+ try {
7092
+ if (!existsSync(join(cwd, 'package.json'))) return null
7093
+ const modules = join(cwd, 'node_modules')
7094
+ if (existsSync(modules)) {
7095
+ const entries = readdirSync(modules)
7096
+ // An empty node_modules is what a killed install leaves behind.
7097
+ if (entries.length > 0) return null
7098
+ }
7099
+ const has = (name) => existsSync(join(cwd, name))
7100
+ const pm = has('pnpm-lock.yaml') ? 'pnpm' : (has('yarn.lock') ? 'yarn' : 'npm')
7101
+ const args = pm === 'npm' ? ['install', '--no-audit', '--no-fund'] : ['install']
7102
+ return { pm, args, dir: cwd }
7103
+ } catch {
7104
+ return null
7105
+ }
7106
+ }
7107
+
7108
+ /**
7109
+ * Run the install phase with its output appended to the program log.
7110
+ *
7111
+ * The proxy environment is stripped on purpose: npm's own traffic goes to a
7112
+ * registry (often a loopback mirror), and an injected ALL_PROXY would send that
7113
+ * through the tunnel where the allow list refuses it.
7114
+ * @param {object} plan - from {@link installPlanFor}.
7115
+ * @param {object} env - base environment.
7116
+ * @param {string} logPath - log the panel tails.
7117
+ * @param {number} timeoutMs - cap for a cold install.
7118
+ * @returns {Promise<{ok: boolean, ms: number, pm: string, error?: string}>} outcome.
7119
+ */
7120
+ export function runInstallPhase(plan, env, logPath, timeoutMs = 1200000) {
7121
+ const clean = Object.assign({}, env)
7122
+ for (const key of Object.keys(clean)) {
7123
+ if (/^(ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|NO_PROXY|all_proxy|http_proxy|https_proxy|no_proxy)$/.test(key)) delete clean[key]
7124
+ }
7125
+ const fd = openSync(logPath, 'a')
7126
+ const started = Date.now()
7127
+ return new Promise((resolvePromise) => {
7128
+ const child = spawn(plan.pm, plan.args, {
7129
+ cwd: plan.dir, env: clean, stdio: ['ignore', fd, fd], shell: IS_WINDOWS, windowsHide: true,
7130
+ })
7131
+ let settled = false
7132
+ const done = (result) => {
7133
+ if (settled) return
7134
+ settled = true
7135
+ try { closeSync(fd) } catch { /* already closed */ }
7136
+ resolvePromise(result)
7137
+ }
7138
+ const timer = setTimeout(() => {
7139
+ try { child.kill('SIGKILL') } catch { /* gone already */ }
7140
+ done({ ok: false, ms: Date.now() - started, pm: plan.pm, error: `安装超时(${Math.round(timeoutMs / 1000)}s)` })
7141
+ }, timeoutMs)
7142
+ child.on('error', (error) => {
7143
+ clearTimeout(timer)
7144
+ done({ ok: false, ms: Date.now() - started, pm: plan.pm, error: isMissingExecutable(error) ? `本机没有安装 ${plan.pm}` : String(error?.message ?? error) })
7145
+ })
7146
+ child.on('close', (code) => {
7147
+ clearTimeout(timer)
7148
+ done(code === 0 ? { ok: true, ms: Date.now() - started, pm: plan.pm } : { ok: false, ms: Date.now() - started, pm: plan.pm, error: `${plan.pm} install exited with ${code}` })
7149
+ })
7150
+ })
7151
+ }
7152
+
5349
7153
  export async function startProgram(cwd, logsDir, program, options) {
5350
7154
  if (options?.debug === undefined) await debugSessions.detach(program.logPath)
5351
7155
  if (program.kind === 'instance') {
@@ -5364,9 +7168,28 @@ export async function startProgram(cwd, logsDir, program, options) {
5364
7168
  const childEnv = Object.assign({}, process.env, { DSH_LOG_DIR: logsDir }, {
5365
7169
  DSH_STOP_GRACE_MS: String(clampBytes(graceMs, DEFAULT_STOP_GRACE_MS, MAX_STOP_GRACE_MS)),
5366
7170
  })
7171
+ // A rule can name this program: inject the proxy at launch, so "配好规则再启动"
7172
+ // actually proxies it (Java reads JAVA_TOOL_OPTIONS, node/curl read ALL_PROXY).
7173
+ // Programs started outside this panel cannot be intercepted — they rely on the
7174
+ // 127.0.0.1 shadow listeners instead.
7175
+ Object.assign(childEnv, proxyEnvFor(program, cwd))
7176
+ // Dependencies first: a missing node_modules would otherwise surface as
7177
+ // "cross-env: not found" and look like the entry itself is broken.
7178
+ const installPlan = options?.skipInstall === true ? null : installPlanFor(cwd)
7179
+ if (installPlan !== null) {
7180
+ const header = `--- 初始化:${installPlan.pm} ${installPlan.args.join(' ')}(node_modules 缺失)---\n`
7181
+ await appendFile(program.logPath, header, 'utf8').catch(() => {})
7182
+ const init = await runInstallPhase(installPlan, childEnv, program.logPath, options?.installTimeoutMs)
7183
+ const summary = init.ok === true
7184
+ ? `--- 初始化完成:${init.pm} install(${Math.round(init.ms / 1000)}s)---\n`
7185
+ : `--- 初始化失败:${init.pm} install(${init.error ?? '未知原因'}),见上方输出 ---\n`
7186
+ await appendFile(program.logPath, summary, 'utf8').catch(() => {})
7187
+ if (init.ok !== true) throw new TailError('init-failed', `依赖安装失败:${init.error ?? '未知原因'}(日志:${program.logPath})`, 502)
7188
+ }
5367
7189
  let child
5368
7190
  if (IS_WINDOWS) {
5369
- const selected = resolveWindowsRuntime(options?.runtime, options?.bashPath)
7191
+ const customCommand = typeof program.startCommand === 'string' ? program.startCommand.replace(/\s*\$\{JDWP_ARGS\}\s*/g, ' ') : ''
7192
+ const selected = resolveWindowsRuntime(options?.runtime, options?.bashPath, { bashDialect: isBashDialectCommand(customCommand) })
5370
7193
  if (selected.runtime === 'bash') {
5371
7194
  // Git Bash: same wrapper as Linux, Windows-flavored classpath.
5372
7195
  const spec = buildStartSpec(program, { workspace: cwd, logsDir, variant: 'windows-bash', debug: options?.debug })
@@ -5418,6 +7241,67 @@ export async function startProgram(cwd, logsDir, program, options) {
5418
7241
  }
5419
7242
  }
5420
7243
 
7244
+ /**
7245
+ * Environment a started program needs to use the workspace proxy.
7246
+ *
7247
+ * Matches the program against the enabled rules: a rule that names a bare
7248
+ * program (`java`, `git`) matches any process with that basename, whatever its
7249
+ * path; a rule that names a path only matches that executable. The path is
7250
+ * therefore optional — it buys precision, not reach.
7251
+ * injection that fits that program. Returns `{}` when no rule matches or the
7252
+ * workspace has no upstream — a silent no-op rather than an error, because most
7253
+ * programs have no rule and must start exactly as before.
7254
+ * @param program - one row from {@link scanPrograms}.
7255
+ * @param cwd - workspace the program is launched from (the shared proxy config
7256
+ * only uses it to identify which rules belong to this workspace).
7257
+ * @returns environment overlay for the child process.
7258
+ */
7259
+ function proxyEnvFor(program, cwd) {
7260
+ // A Windows-side redirector cannot see a process this side spawns, so only the
7261
+ // local hook may disable injection ("covered twice" was the old, wrong test).
7262
+ try {
7263
+ const config = readProxyConfig(cwd)
7264
+ if (config.socks.host === '' || config.socks.port === 0) return {}
7265
+ // ProxyBridge is the primary path when the LOCAL hook is up: it already
7266
+ // redirects this side's connections at the socket layer, so adding env/JVM
7267
+ // options on top would only stack two proxies. A Windows-side redirector does
7268
+ // NOT count — it hooks the Windows stack and cannot see a process this side
7269
+ // spawns, which is exactly the WSL + YonCode split.
7270
+ if (localRedirectorRunning()) return {}
7271
+ const names = new Set()
7272
+ const paths = new Set()
7273
+ for (const candidate of [program?.name, program?.command, program?.exe, program?.id]) {
7274
+ if (typeof candidate !== 'string' || candidate === '') continue
7275
+ names.add(programKey(candidate))
7276
+ if (candidate.includes('/') || candidate.includes('\\')) paths.add(candidate.replace(/\\/g, '/').toLowerCase())
7277
+ }
7278
+ const matchRule = (spec) => {
7279
+ if (typeof spec !== 'string' || spec === '') return false
7280
+ const isPath = spec.includes('/') || spec.includes('\\')
7281
+ if (!isPath) return names.has(programKey(spec))
7282
+ // A path rule is precise: it matches that executable only. When we do not
7283
+ // know the launched path, fall back to the basename so the rule is not
7284
+ // silently dead (the panel often launches by name, e.g. `java`).
7285
+ if (paths.size === 0) return names.has(programKey(spec))
7286
+ return paths.has(spec.replace(/\\/g, '/').toLowerCase())
7287
+ }
7288
+ const rule = config.rules.find((item) => item.enabled && matchRule(item.program))
7289
+ if (rule === undefined) return {}
7290
+ const injection = injectionFor(programKey(rule.program), config, { side: engineSide() })
7291
+ const env = Object.assign({}, injection?.env ?? {})
7292
+ const jvmArgs = Array.isArray(injection?.jvmArgs) ? injection.jvmArgs : []
7293
+ // Careful: an existing JAVA_TOOL_OPTIONS must be kept (it may carry the
7294
+ // user's own -Xmx); the proxy options are appended.
7295
+ if (jvmArgs.length > 0) {
7296
+ const previous = typeof process.env.JAVA_TOOL_OPTIONS === 'string' ? process.env.JAVA_TOOL_OPTIONS.trim() : ''
7297
+ env.JAVA_TOOL_OPTIONS = [previous, jvmArgs.join(' ')].filter((part) => part !== '').join(' ')
7298
+ }
7299
+ return env
7300
+ } catch {
7301
+ return {}
7302
+ }
7303
+ }
7304
+
5421
7305
  /**
5422
7306
  * Start one program in debug mode: stop it if needed, restart it with the JDWP
5423
7307
  * agent on a free loopback port, wait for the port, then attach.
@@ -6112,6 +7996,29 @@ async function considerSpring(workspace, file, programs, launch) {
6112
7996
  }
6113
7997
 
6114
7998
  /** Record one frontend program when its manifest has a dev-ish script. */
7999
+ /**
8000
+ * YonBIP module manifest of a frontend directory (`module.xml` beside package.json).
8001
+ *
8002
+ * This is a yds/MDF convention: the deployed module name lives in `module.xml`, while
8003
+ * `package.json`'s `name` is often the *backend* domainKey — so a row named after the
8004
+ * package would read exactly like the java program's row. Only projects that ship a
8005
+ * module.xml are affected; a plain npm project keeps its package name.
8006
+ * @param dir - frontend project directory.
8007
+ * @returns `{ present, name }`; `name` is `''` when the manifest names nothing.
8008
+ */
8009
+ async function moduleXmlManifest(dir) {
8010
+ const text = await readTextIfSmall(join(dir, 'module.xml'))
8011
+ if (text === undefined) return { present: false, name: '' }
8012
+ const match = /<module\b[^>]*\sname\s*=\s*"([^"]*)"/.exec(text)
8013
+ return { present: true, name: match === null ? '' : match[1].trim() }
8014
+ }
8015
+
8016
+ /** Row name for a frontend: module.xml → folder (yds), else package.json → folder. */
8017
+ function nameOfFrontend(manifest, manifestXml, dir) {
8018
+ if (manifestXml.present === true) return manifestXml.name !== '' ? manifestXml.name : basename(dir)
8019
+ return typeof manifest.name === 'string' && manifest.name !== '' ? manifest.name : basename(dir)
8020
+ }
8021
+
6115
8022
  async function considerFrontend(workspace, file, programs) {
6116
8023
  const dir = dirname(file)
6117
8024
  const text = await readTextIfSmall(file)
@@ -6128,13 +8035,17 @@ async function considerFrontend(workspace, file, programs) {
6128
8035
  if (scripts === undefined) return
6129
8036
  const script = ['dev', 'start', 'serve'].find((key) => typeof scripts[key] === 'string' && scripts[key].trim() !== '')
6130
8037
  if (script === undefined) return
8038
+ const manifestXml = await moduleXmlManifest(dir)
6131
8039
  const relDir = relative(workspace, dir) || '.'
6132
8040
  const id = `frontend:${relDir}#${script}`
6133
8041
  if (programs.has(id)) return
6134
8042
  programs.set(id, {
6135
8043
  id,
6136
8044
  kind: 'frontend',
6137
- name: typeof manifest.name === 'string' && manifest.name !== '' ? manifest.name : basename(dir),
8045
+ // yds project (it has module.xml): name after the manifest, else the folder —
8046
+ // `package.json`'s name there is the domainKey and collides with the java row.
8047
+ // A plain npm project has no module.xml and keeps its package name.
8048
+ name: nameOfFrontend(manifest, manifestXml, dir),
6138
8049
  project: projectOf(relDir, workspace),
6139
8050
  dir,
6140
8051
  relDir,
@@ -6151,7 +8062,12 @@ async function considerFrontend(workspace, file, programs) {
6151
8062
  function assignLogNames(programs) {
6152
8063
  const used = new Map()
6153
8064
  for (const program of programs) {
6154
- const base = sanitizeLogName(`${program.project ? `${program.project}-` : ''}${program.name}`)
8065
+ // Frontend rows are already named after their own manifest (module.xml / folder),
8066
+ // so prefixing the project only produced names that collided with the backend row
8067
+ // of the same yds module ("yonasset-c-ass-kk-hans" vs. the launcher's row).
8068
+ const base = sanitizeLogName(program.kind === 'frontend'
8069
+ ? program.name
8070
+ : `${program.project ? `${program.project}-` : ''}${program.name}`)
6155
8071
  const count = used.get(base) ?? 0
6156
8072
  used.set(base, count + 1)
6157
8073
  program.logName = count === 0 ? base : `${base}-${count + 1}`
@@ -6220,16 +8136,18 @@ export function buildStartSpec(program, context) {
6220
8136
  ? ` ${jdwpAgentArg(context.debug.port, context.debug.suspend === true)} `
6221
8137
  : ' '
6222
8138
  const withDebug = custom.replace(/\s*\$\{JDWP_ARGS\}\s*/g, debugArg)
8139
+ const customDir = context.variant === 'windows-bash' ? toMsysPath(program.dir) : program.dir
6223
8140
  return {
6224
- command: /^cd\s/.test(withDebug) ? withDebug : `cd ${quoteShell(program.dir)} && ${withDebug}`,
8141
+ command: /^cd\s/.test(withDebug) ? withDebug : `cd ${quoteShell(customDir)} && ${withDebug}`,
6225
8142
  cwd: program.dir,
6226
8143
  wrapperPath,
6227
8144
  env: program.env,
6228
8145
  }
6229
8146
  }
6230
8147
  if (program.kind === 'frontend') {
8148
+ const frontDir = context.variant === 'windows-bash' ? toMsysPath(program.dir) : program.dir
6231
8149
  return {
6232
- command: `cd ${quoteShell(program.dir)} && exec ${quoteShell(program.packageManager ?? 'npm')} run ${quoteShell(program.script ?? 'dev')}`,
8150
+ command: `cd ${quoteShell(frontDir)} && exec ${quoteShell(program.packageManager ?? 'npm')} run ${quoteShell(program.script ?? 'dev')}`,
6233
8151
  cwd: program.dir,
6234
8152
  wrapperPath,
6235
8153
  env: program.env,
@@ -6256,9 +8174,13 @@ export function buildStartSpec(program, context) {
6256
8174
  const windowsBash = context.variant === 'windows-bash'
6257
8175
  const classesDir = windowsBash ? 'target\\classes' : 'target/classes'
6258
8176
  const classPathSep = windowsBash ? ';' : ':'
8177
+ // Git Bash runs on Windows but its builtins are POSIX: mkdir/cd need /c/... .
8178
+ // The JVM is a Windows binary, so -D paths stay in Windows spelling.
8179
+ const shellCspDir = windowsBash ? toMsysPath(cspDir) : cspDir
8180
+ const shellDir = windowsBash ? toMsysPath(program.dir) : program.dir
6259
8181
  const command = [
6260
- `mkdir -p ${quoteShell(cspDir)}`,
6261
- `cd ${quoteShell(program.dir)}`,
8182
+ `mkdir -p ${quoteShell(shellCspDir)}`,
8183
+ `cd ${quoteShell(shellDir)}`,
6262
8184
  'mvn -Pdev compile',
6263
8185
  'mvn -Pdev dependency:build-classpath -Dmdep.includeScope=runtime -Dmdep.outputFile=target/cp.txt',
6264
8186
  // `exec` is what makes the wrapper's child BE the JVM, so a stop TERMs the
@@ -6507,6 +8429,22 @@ export function resolveSpringArgs(program, workspace) {
6507
8429
  }
6508
8430
 
6509
8431
  /** One shell word, quoted only when it needs to be. */
8432
+ /**
8433
+ * Translate `C:\x\y` into the MSYS spelling `/c/x/y`.
8434
+ *
8435
+ * Only the Git Bash wrapper needs this: the Windows JVM still receives the
8436
+ * original `C:\...` paths for `-D` flags (it cannot read `/c/...`), but the
8437
+ * shell's own `mkdir`/`cd` must see POSIX paths or MSYS treats the drive colon
8438
+ * and backslashes as literal characters.
8439
+ * @param {string} value - a Windows or already-POSIX path.
8440
+ * @returns {string} MSYS path when the input looks like `X:\...`, else the input.
8441
+ */
8442
+ export function toMsysPath(value) {
8443
+ const match = /^([A-Za-z]):[\\/](.*)$/.exec(String(value ?? ''))
8444
+ if (match === null) return String(value ?? '')
8445
+ return `/${match[1].toLowerCase()}/${match[2].replace(/\\/g, '/')}`
8446
+ }
8447
+
6510
8448
  export function quoteShell(value) {
6511
8449
  const text = String(value)
6512
8450
  if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(text)) return text
@@ -6729,7 +8667,12 @@ export function findConfigEntryIndex(entries, candidate, used) {
6729
8667
  && (entry.kind === undefined || entry.kind === candidate.kind))
6730
8668
  if (byDir !== -1) return byDir
6731
8669
  }
6732
- return entries.findIndex((entry, at) => free(at) && entry.name === candidate.name)
8670
+ // Name is the last resort, and only within the same kind: two different kinds can
8671
+ // legitimately share a name (a yds project's package.json name equals its java
8672
+ // module), and matching across kinds made an update copy a launcher's startCommand
8673
+ // onto an unrelated frontend row — and then drop the launcher itself.
8674
+ return entries.findIndex((entry, at) => free(at) && entry.name === candidate.name
8675
+ && (entry.kind === undefined || candidate.kind === undefined || entry.kind === candidate.kind))
6733
8676
  }
6734
8677
 
6735
8678
  /**
@@ -7197,6 +9140,111 @@ export function registerAgentTools(ctx, options) {
7197
9140
  }
7198
9141
  return { sessionId, cwd: resolveCwd(ctx, sessionId) }
7199
9142
  }
9143
+ // ── P4: daemon-first tools ────────────────────────────────────────────────
9144
+ // In daemonMode=auto the engine, the programs and the JDWP sessions belong to
9145
+ // risd, so a tool asks the daemon first. Anything it cannot answer — a stopped
9146
+ // daemon, a stale bridge, an older risd — falls back to the local plugin
9147
+ // implementation, which is exactly what ran before this phase.
9148
+ // A tool call is also a "bring it back" gesture for the daemon: if it crashed
9149
+ // (or the user ran `risd stop`) while dsh is still open, re-spawn it once and
9150
+ // keep using it instead of silently degrading to the plugin-local path. The
9151
+ // hint is what an agent needs when even that fails.
9152
+ const healDaemon = async () => {
9153
+ const bridge = risdBridge
9154
+ if (bridge === null) return null
9155
+ const now = Date.now()
9156
+ if (risdHealBlocked(now)) return null
9157
+ if (now - (fallbackWarnedAt.get('__heal') ?? 0) < 5000) return bridge.state
9158
+ fallbackWarnedAt.set('__heal', now)
9159
+ const ensured = await ensureRisd({ home: proxyHomeDir() }).catch(() => ({ ok: false, reason: 'spawn failed' }))
9160
+ if (ensured.ok !== true) {
9161
+ // A version mismatch is not a failed start: the same mismatched daemon is
9162
+ // still running, and spending breaker budget on it would stop every tool
9163
+ // for five minutes (review C-P2-1).
9164
+ if (ensured.reason === 'api-mismatch') {
9165
+ warnDaemonMismatch()
9166
+ return null
9167
+ }
9168
+ noteRisdHealFailure(ensured.reason ?? 'unknown')
9169
+ return null
9170
+ }
9171
+ noteRisdHealSuccess()
9172
+ return attachBridgeState(ensured.state, null)
9173
+ }
9174
+ const daemonStateForTools = async () => {
9175
+ const bridge = risdBridge
9176
+ if (bridge === null) return null
9177
+ if (bridge.state !== null) {
9178
+ // A daemon can die between two calls while the pointer still looks live.
9179
+ // Probe at most once per 5 s (health is cheap and unauthenticated) so a
9180
+ // half-dead daemon costs one timeout per window instead of one per tool call
9181
+ // (review C-P2-2); a dead one drops the pointer and falls into the heal path.
9182
+ if (Date.now() - (bridge.lastProbeAt ?? 0) < 5000) return bridge.state
9183
+ bridge.lastProbeAt = Date.now()
9184
+ const health = await risdHealth(bridge.state).catch(() => null)
9185
+ if (health !== null && health.ok === true) return bridge.state
9186
+ bridge.state = null
9187
+ bridge.degraded = true
9188
+ }
9189
+ if (bridge.pending !== null) {
9190
+ await Promise.race([
9191
+ bridge.pending,
9192
+ new Promise((resolve) => { const timer = setTimeout(resolve, 3000); timer.unref?.() }),
9193
+ ])
9194
+ }
9195
+ if (bridge.state !== null) return bridge.state
9196
+ const healed = await healDaemon()
9197
+ // Silence here was the bug: the tools ran locally while the agent (and the
9198
+ // user) believed the daemon owned the programs/JDWP sessions (review C-P2-2).
9199
+ if (healed === null) warnDaemonFallback()
9200
+ return healed
9201
+ }
9202
+ const warnDaemonFallback = () => {
9203
+ const now = Date.now()
9204
+ if (now - (fallbackWarnedAt.get('__daemon') ?? 0) < 60_000) return
9205
+ fallbackWarnedAt.set('__daemon', now)
9206
+ try {
9207
+ ctx.logger?.warn?.('[dsh-ris-ide] risd 不可用,agent 工具改走插件本地实现:这样启动的程序不在 daemon 的托管范围内(停 daemon 不会停它)')
9208
+ } catch { /* logging is best effort */ }
9209
+ }
9210
+ const warnDaemonMismatch = () => {
9211
+ const now = Date.now()
9212
+ if (now - (fallbackWarnedAt.get('__mismatch') ?? 0) < 60_000) return
9213
+ fallbackWarnedAt.set('__mismatch', now)
9214
+ try {
9215
+ ctx.logger?.warn?.('[dsh-ris-ide] risd 版本与插件不一致(apiVersion 不匹配),工具改走插件本地实现;重启 dsh 会启动匹配版本的 risd')
9216
+ } catch { /* logging is best effort */ }
9217
+ }
9218
+ const fallbackWarnedAt = new Map()
9219
+ const warnFallback = (what, error) => {
9220
+ const now = Date.now()
9221
+ if (now - (fallbackWarnedAt.get(what) ?? 0) < 60_000) return
9222
+ fallbackWarnedAt.set(what, now)
9223
+ try {
9224
+ ctx.logger?.warn?.(`[dsh-ris-ide] ${what} 回退到插件本地实现:${describe(error)}`)
9225
+ } catch { /* logging is best effort */ }
9226
+ }
9227
+ // Resolve *which* program a tool meant, through the daemon's own list: in auto
9228
+ // mode the daemon owns the program registry, so its ids are the reference.
9229
+ const daemonProgramFor = async (daemon, cwd, args) => {
9230
+ const res = await daemonListPrograms(daemon, cwd, {})
9231
+ if (res.ok !== true) throw new Error(`risd /v1/programs ${res.status ?? ''} ${res.error ?? ''}`.trim())
9232
+ const rows = Array.isArray(res.body?.programs) ? res.body.programs : []
9233
+ const wantedId = typeof args?.id === 'string' && args.id !== '' ? args.id : null
9234
+ const wantedName = typeof args?.name === 'string' && args.name !== '' ? args.name : null
9235
+ if (wantedId !== null) return rows.find((row) => row.id === wantedId)
9236
+ if (wantedName === null) return undefined
9237
+ const exact = rows.find((row) => row.logName === wantedName || row.name === wantedName)
9238
+ if (exact !== undefined) return exact
9239
+ const matches = rows.filter((row) => String(row.name ?? '').includes(wantedName) || String(row.logName ?? '').includes(wantedName))
9240
+ return matches.length === 1 ? matches[0] : undefined
9241
+ }
9242
+ const tailFromText = (textValue, lines) => {
9243
+ const all = String(textValue ?? '').split('\n')
9244
+ if (all.length > 0 && all[all.length - 1] === '') all.pop()
9245
+ const count = Math.min(Math.max(Number(lines) || 80, 1), 500)
9246
+ return all.slice(Math.max(0, all.length - count)).join('\n')
9247
+ }
7200
9248
  const text = (value) => [{ type: 'text', text: value }]
7201
9249
  const LOOSE_OUTPUT = {
7202
9250
  type: 'object',
@@ -7224,9 +9272,33 @@ export function registerAgentTools(ctx, options) {
7224
9272
  // Plugin upgrade => refresh any skill copy this workspace installed.
7225
9273
  kickAutoSync(cwd)
7226
9274
  const logsDir = resolvePath(cwd, 'logs', true)
9275
+ const daemon = await daemonStateForTools()
9276
+ if (daemon !== null) {
9277
+ try {
9278
+ const res = await daemonListPrograms(daemon, cwd, { refresh: args?.refresh === true })
9279
+ if (res.ok !== true) throw new Error(`risd /v1/programs ${res.status ?? ''} ${res.error ?? ''}`.trim())
9280
+ const listed = res.body ?? {}
9281
+ let rows = Array.isArray(listed.programs) ? listed.programs : []
9282
+ if (args?.runningOnly === true) rows = rows.filter((program) => program.running?.alive === true)
9283
+ return jsonSafe({
9284
+ ok: true,
9285
+ root: listed.cwd ?? cwd,
9286
+ dir: listed.dir ?? logsDir,
9287
+ programs: programRows(rows),
9288
+ companion: detectCompanionPlugin(cwd),
9289
+ })
9290
+ } catch (error) { warnFallback('ris_dev_programs', error) }
9291
+ }
7227
9292
  let programs = await scanPrograms(cwd, logsDir, args?.refresh === true)
7228
9293
  if (args?.runningOnly === true) programs = programs.filter((program) => program.running?.alive === true)
7229
- return jsonSafe({ ok: true, root: cwd, dir: logsDir, programs: programRows(programs) })
9294
+ return jsonSafe({
9295
+ ok: true,
9296
+ root: cwd,
9297
+ dir: logsDir,
9298
+ programs: programRows(programs),
9299
+ // Only a real YMS workspace gets a hint; null keeps the payload clean.
9300
+ companion: detectCompanionPlugin(cwd),
9301
+ })
7230
9302
  },
7231
9303
  })
7232
9304
 
@@ -7249,6 +9321,21 @@ export function registerAgentTools(ctx, options) {
7249
9321
  exec?.signal?.throwIfAborted?.()
7250
9322
  const { cwd } = scopeOf(exec)
7251
9323
  const logsDir = resolvePath(cwd, 'logs', true)
9324
+ const daemon = await daemonStateForTools()
9325
+ if (daemon !== null) {
9326
+ try {
9327
+ const remote = await daemonProgramFor(daemon, cwd, args)
9328
+ if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
9329
+ const res = await daemonProgramAction(daemon, { cwd, action: 'start', id: remote.id })
9330
+ if (res.ok !== true) throw new Error(`risd start ${res.status ?? ''} ${res.error ?? ''}`.trim())
9331
+ const body = res.body ?? {}
9332
+ return jsonSafe({
9333
+ ok: true,
9334
+ alreadyRunning: body.alreadyRunning === true,
9335
+ program: programRow(body.program ?? remote),
9336
+ })
9337
+ } catch (error) { warnFallback('ris_dev_start', error) }
9338
+ }
7252
9339
  const program = resolveProgramRef(await scanPrograms(cwd, logsDir, false), args)
7253
9340
  if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
7254
9341
  const result = await startProgram(cwd, logsDir, program, options)
@@ -7278,8 +9365,19 @@ export function registerAgentTools(ctx, options) {
7278
9365
  exec?.signal?.throwIfAborted?.()
7279
9366
  const { cwd } = scopeOf(exec)
7280
9367
  const logsDir = resolvePath(cwd, 'logs', true)
9368
+ const pathAddressed = typeof args?.path === 'string' && args.path !== ''
9369
+ const daemon = await daemonStateForTools()
9370
+ if (daemon !== null && !pathAddressed) {
9371
+ try {
9372
+ const remote = await daemonProgramFor(daemon, cwd, args)
9373
+ if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
9374
+ const res = await daemonProgramAction(daemon, { cwd, action: 'stop', id: remote.id })
9375
+ if (res.ok !== true) throw new Error(`risd stop ${res.status ?? ''} ${res.error ?? ''}`.trim())
9376
+ return jsonSafe(Object.assign({ ok: true, path: res.body?.path ?? remote.logPath }, res.body ?? {}))
9377
+ } catch (error) { warnFallback('ris_dev_stop', error) }
9378
+ }
7281
9379
  let logPath
7282
- if (typeof args?.path === 'string' && args.path !== '') {
9380
+ if (pathAddressed) {
7283
9381
  logPath = resolvePath(cwd, args.path, options?.restrictToCwd === true)
7284
9382
  } else {
7285
9383
  const program = resolveProgramRef(await scanPrograms(cwd, logsDir, false), args)
@@ -7311,9 +9409,32 @@ export function registerAgentTools(ctx, options) {
7311
9409
  exec?.signal?.throwIfAborted?.()
7312
9410
  const { sessionId, cwd } = scopeOf(exec)
7313
9411
  const logsDir = resolvePath(cwd, 'logs', true)
9412
+ const pathAddressed = typeof args?.path === 'string' && args.path !== ''
9413
+ const daemon = await daemonStateForTools()
9414
+ if (daemon !== null && !pathAddressed) {
9415
+ try {
9416
+ const remote = await daemonProgramFor(daemon, cwd, args)
9417
+ if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
9418
+ const res = await daemonReadProgramLog(daemon, { cwd, id: remote.id, bytes: 256 * 1024 })
9419
+ if (res.ok !== true) throw new Error(`risd log ${res.status ?? ''} ${res.error ?? ''}`.trim())
9420
+ const body = res.body ?? {}
9421
+ const logPath = body.path ?? remote.logPath
9422
+ const opened = args?.open !== false
9423
+ if (opened) enqueueOpen({ sessionId, cwd, logPath, title: `${remote.name} 日志` })
9424
+ return jsonSafe({
9425
+ ok: true,
9426
+ path: logPath,
9427
+ exists: body.exists !== false,
9428
+ running: body.running === true,
9429
+ opened,
9430
+ pid: body.pid ?? null,
9431
+ content: tailFromText(body.text, args?.lines),
9432
+ })
9433
+ } catch (error) { warnFallback('ris_dev_logs', error) }
9434
+ }
7314
9435
  let logPath
7315
9436
  let title
7316
- if (typeof args?.path === 'string' && args.path !== '') {
9437
+ if (pathAddressed) {
7317
9438
  logPath = resolvePath(cwd, args.path, options?.restrictToCwd === true)
7318
9439
  title = basename(logPath)
7319
9440
  } else {
@@ -7402,6 +9523,23 @@ export function registerAgentTools(ctx, options) {
7402
9523
  exec?.signal?.throwIfAborted?.()
7403
9524
  const { cwd } = scopeOf(exec)
7404
9525
  const logsDir = resolvePath(cwd, 'logs', true)
9526
+ const daemon = await daemonStateForTools()
9527
+ if (daemon !== null) {
9528
+ try {
9529
+ const remote = await daemonProgramFor(daemon, cwd, args)
9530
+ if (remote === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
9531
+ const res = await daemonProgramAction(daemon, { cwd, action: 'restart', id: remote.id })
9532
+ if (res.ok !== true) throw new Error(`risd restart ${res.status ?? ''} ${res.error ?? ''}`.trim())
9533
+ const body = res.body ?? {}
9534
+ return jsonSafe({
9535
+ ok: true,
9536
+ restarted: body.restarted === true,
9537
+ stopped: body.stopped ?? null,
9538
+ alreadyRunning: body.alreadyRunning === true,
9539
+ program: programRow(body.program ?? remote),
9540
+ })
9541
+ } catch (error) { warnFallback('ris_dev_restart', error) }
9542
+ }
7405
9543
  const program = resolveProgramRef(await scanPrograms(cwd, logsDir, false), args)
7406
9544
  if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
7407
9545
  if (program.kind === 'instance') throw new TailError('not-startable', 'this row is a log of an instance started outside the panel', 400)
@@ -7476,6 +9614,63 @@ export function registerAgentTools(ctx, options) {
7476
9614
  }
7477
9615
  return (await findProgram()).logPath
7478
9616
  }
9617
+ // P4: in auto mode the JDWP session lives in risd. Forward everything the
9618
+ // daemon owns — "open" is UI-only and stays here, and a path-addressed call
9619
+ // keeps the local session (the daemon resolves programs by id).
9620
+ const daemon = await daemonStateForTools()
9621
+ const pathAddressed = typeof args?.path === 'string' && args.path !== ''
9622
+ if (daemon !== null && action !== 'open' && !pathAddressed) {
9623
+ if (action === 'state') {
9624
+ try {
9625
+ const program = await daemonProgramFor(daemon, cwd, args)
9626
+ if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
9627
+ const statusRes = await daemonDebugAction(daemon, { action: 'status', cwd, id: program.id, sessionId })
9628
+ if (statusRes.ok !== true) throw new Error(`risd debug ${statusRes.status ?? ''} ${statusRes.error ?? ''}`.trim())
9629
+ const statusBody = statusRes.body ?? {}
9630
+ const breakpointsRes = await daemonDebugAction(daemon, { action: 'breakpoints', cwd, id: program.id, sessionId })
9631
+ const breakpointsBody = breakpointsRes.ok === true ? (breakpointsRes.body ?? {}) : {}
9632
+ const pending = statusBody?.pendingBreakpoints ?? statusBody?.pending ?? 0
9633
+ return jsonSafe({
9634
+ ok: true,
9635
+ program: programRow(program),
9636
+ running: program.running ?? null,
9637
+ debuggable: program.kind === 'spring',
9638
+ debug: statusBody,
9639
+ breakpoints: breakpointsBody?.breakpoints ?? [],
9640
+ pendingBreakpoints: typeof pending === 'number' ? pending : 0,
9641
+ })
9642
+ } catch (error) { warnFallback('ris_dev_debug', error) }
9643
+ }
9644
+ const mapped = {
9645
+ start: 'start', stop: 'detach', status: 'status', poll: 'events',
9646
+ breakpoints: 'breakpoints', breakpoint_add: 'breakpoint-add',
9647
+ breakpoint_remove: 'breakpoint-remove', breakpoint_clear: 'breakpoint-clear',
9648
+ threads: 'threads', stack: 'stack', variables: 'variables',
9649
+ step: 'step', resume: 'resume', pause: 'pause',
9650
+ }[action]
9651
+ if (mapped !== undefined) {
9652
+ try {
9653
+ const program = await daemonProgramFor(daemon, cwd, args)
9654
+ if (program === undefined) throw new TailError('unknown-program', `no program matched ${describeRef(args)}`, 404)
9655
+ const res = await daemonDebugAction(daemon, Object.assign({
9656
+ action: mapped, cwd, id: program.id, sessionId,
9657
+ }, {
9658
+ className: args?.className,
9659
+ line: args?.line,
9660
+ suspendPolicy: args?.suspendPolicy,
9661
+ requestId: args?.requestId,
9662
+ threadId: args?.threadId,
9663
+ frameIndex: args?.frameIndex,
9664
+ max: args?.max,
9665
+ kind: args?.kind,
9666
+ since: args?.since,
9667
+ suspend: args?.suspend,
9668
+ }))
9669
+ if (res.ok !== true) throw new Error(`risd debug ${res.status ?? ''} ${res.error ?? ''}`.trim())
9670
+ return jsonSafe(Object.assign({ ok: true }, res.body ?? {}))
9671
+ } catch (error) { warnFallback('ris_dev_debug', error) }
9672
+ }
9673
+ }
7479
9674
  try {
7480
9675
  if (action === 'state') {
7481
9676
  // One call that answers "can I debug this, and from what?" before anything
@@ -7754,13 +9949,19 @@ function describeRef(ref) {
7754
9949
  /** Render one program list for the model. */
7755
9950
  function renderProgramList(value) {
7756
9951
  const programs = Array.isArray(value?.programs) ? value.programs : []
7757
- if (programs.length === 0) return `No runnable programs under ${value?.root ?? '?'}.`
9952
+ const companion = value?.companion
9953
+ // The hint is additive: the list itself (and the tool result) stays usable
9954
+ // when the companion plugin is not installed.
9955
+ const hint = companion !== undefined && companion !== null
9956
+ ? `\nOptional companion plugin: ${companion.plugin} (detected ${companion.detected}) — ${companion.hint}`
9957
+ : ''
9958
+ if (programs.length === 0) return `No runnable programs under ${value?.root ?? '?'}.${hint}`
7758
9959
  const lines = [`${programs.length} program(s) under ${value.root} (logs: ${value.dir}):`]
7759
9960
  for (const program of programs) {
7760
9961
  lines.push(`- ${program.running ? '[running]' : '[stopped]'} ${program.name} (${program.kind}) id=${program.id}`)
7761
9962
  lines.push(` dir=${program.dir}${program.mainClass ? ` main=${program.mainClass}` : ''}${program.script ? ` script=${program.script}` : ''} log=${program.logPath}`)
7762
9963
  }
7763
- return lines.join('\n')
9964
+ return lines.join('\n') + hint
7764
9965
  }
7765
9966
 
7766
9967
  /** Render one start result for the model. */
@@ -7917,7 +10118,40 @@ function renderLogs(value) {
7917
10118
 
7918
10119
  /** Test-only surface: the pure pieces, exercised without a live profile. */
7919
10120
  export const __test = {
10121
+ // P4 tests: pretend the plugin is attached to a daemon without booting one.
10122
+ setRisdBridge: (bridge) => { risdBridge = bridge },
7920
10123
  resolvePath,
10124
+ refreshDshWindows,
10125
+ detectCompanionPlugin,
10126
+ renderProgramList,
10127
+ windowsProgramNames,
10128
+ resetWindowsProgramCache,
10129
+ // Proxy rules + engine (the dialog's three routes).
10130
+ PROXY_PATH,
10131
+ RISD_ENSURE_PATH,
10132
+ risdHealBlocked,
10133
+ risdHealReason,
10134
+ noteRisdHealFailure,
10135
+ noteRisdHealSuccess,
10136
+ PROXY_ACTION_PATH,
10137
+ buildProfile,
10138
+ PROXY_PROGRAMS_PATH,
10139
+ PROXY_BROWSE_PATH,
10140
+ serveProxy,
10141
+ serveProxyAction,
10142
+ serveProxyPrograms,
10143
+ serveProxyBrowse,
10144
+ proxyEnvFor,
10145
+ proxyView,
10146
+ // Process-wide child-service lifecycle (exit hook + heartbeat + janitor), and the
10147
+ // adoption of an engine left behind by a previous dsh process.
10148
+ ensureLifecycle,
10149
+ armLocalProxyCleanup,
10150
+ disarmLocalProxyCleanup,
10151
+ isBashDialectCommand,
10152
+ startHeartbeat,
10153
+ adoptLeftoverEngine,
10154
+ decorateProxyRule,
7921
10155
  // The bundled skill + its installer (idempotent, target-aware).
7922
10156
  SKILL_NAME,
7923
10157
  PKG_VERSION,
@@ -8076,6 +10310,7 @@ export const __test = {
8076
10310
  windowsCommandLine,
8077
10311
  taskkillTree,
8078
10312
  windowsStartSpec,
10313
+ toMsysPath,
8079
10314
  logUrl,
8080
10315
  logStatus,
8081
10316
  programStatus,