dsh-ris-ide 1.7.3 → 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 (72) hide show
  1. package/README.md +19 -7
  2. package/bin/proxy-janitor.mjs +106 -11
  3. package/bin/risd.mjs +287 -0
  4. package/bin/run-with-log.ps1 +43 -5
  5. package/lib/client.js +515 -1152
  6. package/lib/index.js +1124 -55
  7. package/lib/janitor.js +106 -15
  8. package/lib/proxy.js +86 -7
  9. package/lib/proxybridge-bundle.js +798 -0
  10. package/lib/redirector.js +484 -35
  11. package/lib/risd/build.js +91 -0
  12. package/lib/risd/debug.js +374 -0
  13. package/lib/risd/git.js +207 -0
  14. package/lib/risd/leases.js +124 -0
  15. package/lib/risd/lifecycle.js +148 -0
  16. package/lib/risd/log.js +59 -0
  17. package/lib/risd/ping.js +94 -0
  18. package/lib/risd/programs.js +348 -0
  19. package/lib/risd/server.js +1478 -0
  20. package/lib/risd/state.js +137 -0
  21. package/lib/risd/ui.js +1705 -0
  22. package/lib/risd/view.js +79 -0
  23. package/lib/risd-client.js +282 -0
  24. package/lib/standalone/window.html +14 -16
  25. package/lib/startup.js +114 -0
  26. package/package.json +4 -1
  27. package/test/client-build.test.mjs +113 -0
  28. package/test/client-viewer.test.mjs +166 -200
  29. package/test/dsh-origin.test.mjs +140 -0
  30. package/test/dsh-window-refresh.test.mjs +100 -0
  31. package/test/harness.test.mjs +9 -0
  32. package/test/host-noloop.test.mjs +74 -0
  33. package/test/host-tail.test.mjs +21 -4
  34. package/test/host-window.test.mjs +4 -4
  35. package/test/janitor.test.mjs +29 -1
  36. package/test/lifecycle.test.mjs +26 -5
  37. package/test/merge-owners.test.mjs +155 -0
  38. package/test/proxy-restart.test.mjs +37 -0
  39. package/test/proxy-window.test.mjs +45 -0
  40. package/test/proxy.test.mjs +41 -0
  41. package/test/proxybridge-bundle.test.mjs +687 -0
  42. package/test/redirector-bundle.test.mjs +391 -0
  43. package/test/redirector.test.mjs +59 -9
  44. package/test/risd-api.test.mjs +470 -0
  45. package/test/risd-bridge-degrade.test.mjs +101 -0
  46. package/test/risd-build.test.mjs +20 -0
  47. package/test/risd-cli-home.test.mjs +50 -0
  48. package/test/risd-client.test.mjs +130 -0
  49. package/test/risd-debug.test.mjs +261 -0
  50. package/test/risd-election.test.mjs +104 -0
  51. package/test/risd-engine.test.mjs +132 -0
  52. package/test/risd-entry.test.mjs +118 -0
  53. package/test/risd-git.test.mjs +109 -0
  54. package/test/risd-handoff.test.mjs +116 -0
  55. package/test/risd-heal.test.mjs +50 -0
  56. package/test/risd-helpers.mjs +108 -0
  57. package/test/risd-host-p2.test.mjs +147 -0
  58. package/test/risd-janitor-guard.test.mjs +46 -0
  59. package/test/risd-lease.test.mjs +83 -0
  60. package/test/risd-lifecycle.test.mjs +210 -0
  61. package/test/risd-log-follow.test.mjs +227 -0
  62. package/test/risd-mode.test.mjs +161 -0
  63. package/test/risd-ping.test.mjs +99 -0
  64. package/test/risd-programs.test.mjs +169 -0
  65. package/test/risd-review-p2.test.mjs +217 -0
  66. package/test/risd-shutdown.test.mjs +97 -0
  67. package/test/risd-teardown.test.mjs +87 -0
  68. package/test/risd-tools.test.mjs +211 -0
  69. package/test/risd-ui.test.mjs +445 -0
  70. package/test/risd-write.test.mjs +170 -0
  71. package/test/startup-reconcile.test.mjs +100 -0
  72. package/test/windows.test.mjs +37 -2
package/README.md CHANGED
@@ -19,14 +19,10 @@ DSH(DeepSeek Harness)Web GUI 右侧栏里的 **RIS-IDE 本地开发面板**
19
19
  |---|
20
20
  | ![侧栏「RIS控制台」](https://raw.githubusercontent.com/ris-cloud/dsh-ris-ide/master/docs/screenshots/ris-console.png) |
21
21
 
22
- | 独立窗口(打开即最大化、无会话历史;控制台标题栏有 📄/⚙)|
22
+ | 独立窗口(普通浏览器窗口、无会话历史;控制台标题栏有 📄/⚙)|
23
23
  |---|
24
24
  | ![独立窗口](https://raw.githubusercontent.com/ris-cloud/dsh-ris-ide/master/docs/screenshots/ris-ide-window.png) |
25
25
 
26
- | 代理面板(🌐):全机规则表,一次启停引擎 / 系统层转发 / git 代理 |
27
- |---|
28
- | ![代理面板](https://raw.githubusercontent.com/ris-cloud/dsh-ris-ide/master/docs/screenshots/ris-proxy.png) |
29
-
30
26
  ## 功能
31
27
 
32
28
  - **程序控制台**:扫描工作区的 Spring Boot 入口、前端 `package.json` 脚本与有 pidfile 的历史实例;每行 `▶ 启动 / ■ 停止 / ⟳ 重启 / 🐞 调试 / ▤ 日志`,启停期间行上有遮罩(文案按动作)。勾选 2 行以上时标题栏出现 **▶ 批量启动 / ■ 批量停止 / 清除**(按列表顺序启动、倒序停止、跳过无需动作的,按钮上显示 `i/N`)。点程序行(名称或整行)下方日志立刻跟随该程序。
@@ -37,7 +33,7 @@ DSH(DeepSeek Harness)Web GUI 右侧栏里的 **RIS-IDE 本地开发面板**
37
33
  - **预览**:`.md/.markdown/.html/.htm` 编辑/预览切换按钮**悬浮在编辑区右上角**(不占代码行高,预览含未保存修改);超过整读上限的大文本以**只读分页预览**打开(滚到近底取下一页、内存超限释放前文、滚动位置按文件记住),标题栏「编辑」可强制全量加载进编辑(上限 32MB)。
38
34
  - **JDWP 调试(仅 Java)**:点行号加断点、双击红点删除(空行/注释行忽略);断点/线程/调用栈/变量/单步/继续;对象与数组懒加载展开、继承字段与空值也列出;依赖 jar 自动取 `-sources.jar`,没有则 `javap` 反汇编,也可在调试面板 ⚙ 填反编译 jar(如 CFR),缓存按 jar 指纹失效并有 64MB/30 天上限回收;命中后自动切「参数」页签、打开源码并高亮当前行;前端程序只能启停/看日志。
39
35
  - **独立窗口**:聊天页右上角 **⧉ RIS-IDE**(或控制台标题栏 ⧉)打开,**填满屏幕**、**不加载 DSH 界面/不带会话历史**,与侧栏同一套 `/dsh-ris-ide/*` 路由与 cookie,没有新端口;窗口按**工作空间**单例,从程序目录调试也不会开出第二个。
40
- - **代理**:规则表是全机一份文件(`~/.dsh-ris-ide/proxy.json`),所以日常入口是 CLI/工具,不是界面——`node <dsh-ris-ide>/lib/proxy.js rules` 看表、`… start` / `… stop` 管引擎,`yds proxy sync` 从 confcenter 自动生成该项目的规则(DB/Redis/gitlab/回调网段)。控制台里的 🌐 只是**查看/手改**用的辅助面板(dsh 侧栏的控制台与独立窗口各有一个)。**一个 启动/停止 管全部三层**——本地引擎(给本插件 spawn 的程序注入代理)、系统层拦截(ProxyBridge 按进程名在系统层改路,覆盖 Navicat、IDE 里的 java、终端 git)、git 配置(`git config --global http.https://<host>/.proxy = socks5h://…`,写完终端里的 `git` 与 dsh-git 都走隧道);`dsh` 退出时三层一起停,不留残留。**全机一份规则表**(`~/.dsh-ris-ide/proxy.json`,`DSH_RIS_IDE_PROXY_HOME` 可改位置),整机生效、不区分工作区与会话,行尾「来源」只记是哪个工作区写的。提权是正常流程:Windows 侧启动时弹 UAC,Linux 侧需要免密 sudo;提不到权时弹窗里给出可直接粘贴的命令。Windows 侧启动还有三个实测过的细节:GUI 安装的服务 `ProxyBridgeSvc` 与 CLI 互斥(都抢 WinDivert 句柄),所以先停服务再起 CLI(停过会记下来,停止时尝试恢复);手起或遗留的 `ProxyBridge_CLI.exe` 先结束再接管;CLI 没有日志开关,stdout 重定向到 `%TEMP%\dsh-ris-proxybridge.log`,起不来时日志尾部就是错误原因。两层兜底:ProxyBridge 没在跑时,支持代理的程序(java / git / node / curl)启动时注入**本机 CONNECT 代理** `http://127.0.0.1:11081`(`ALL_PROXY`/`HTTP(S)_PROXY` + JVM 的 `-Dhttp(s).proxyHost/Port`),每一条连接仍然要过规则里的 IP/端口白名单——注入不再等于「把上游 SOCKS 地址直接发给程序」。想让某个程序完全绕过白名单、直连上游 SOCKS,就在该行加 `"direct": true`(`proxy.json` 里的行级开关,界面暂无控件);不支持代理的客户端(Navicat / JDBC)自动映射 `127.0.0.1:同端口`——这些映射行是实现细节,不进界面。弹窗上部填上游 SOCKS(host/port)与本地 CONNECT 端口,下部是规则表:`启用 · 程序 · IP 允许(1.1.1.* / 逗号)· 端口允许(1521 / 1000-1010,* 表示不限)· 命中方式`。程序列两种来源——**运行中的进程**(本侧 + Windows 侧,只列支持 SOCKS 的)或**固定程序**(文件浏览器选可执行文件,可在启动前配好;裸名按镜像名匹配,含路径则精确到那个可执行文件)。
36
+ - **代理**:规则表是全机一份文件(`~/.dsh-ris-ide/proxy.json`),所以入口是 CLI/工具与 **risd 维护页**——`node <dsh-ris-ide>/lib/proxy.js rules` 看表、`… start` / `… stop` 管引擎,`yds proxy sync` 从 confcenter 自动生成该项目的规则(DB/Redis/gitlab/回调网段)。**插件面板不再内置代理配置界面**(1.8.0 起,D4):risd 维护页的「代理设置」页签(`http://127.0.0.1:11082/ui?tab=proxy`)不依赖 dsh,直接编辑全机规则表。系统层拦截需要的 **ProxyBridge 组件改为首次使用时下载**(不再随包内置 2.9 MB 二进制):risd 维护页「代理 → 组件」一点即下——内置 **Gitee 主地址、GitHub 备用**两个镜像(同一份发版附件,前一个失败自动换下一个),也可上传 `ris-proxy.4.0.tgz`,或设 `DSH_RIS_IDE_PROXYBRIDGE_URL` / `settings.json` 的 `proxybridgeUrl` 走内网镜像;装进 `~/.dsh-ris-ide/proxybridge/bundle/` 后复用,安装完成后面板只显示「已安装」。下载失败时面板给出两个下载地址与手动上传入口。许可文本(MIT + WinDivert LGPL-3.0)随包安装。组件包按**固定 sha256** 校验(下载与上传都验内容;`DSH_RIS_IDE_PROXYBRIDGE_SHA256` 或 `settings.json` 的 `proxybridgeSha256` 可覆盖,置空=首次信任;重发附件改了内容要同步更新常量并发版);已安装后在面板里可「重新下载」(强制刷新缓存副本)。未安装时会明确提示入口而不是静默失败;机器上已装的 ProxyBridge / `DSH_RIS_IDE_PROXYBRIDGE` 仍是回退。WSL 下先把 Windows 版复制到 `%LOCALAPPDATA%\dsh-ris-ide\proxybridge\windows` 再启动。**一个 启动/停止 管全部三层**——本地引擎(给本插件 spawn 的程序注入代理)、系统层拦截(ProxyBridge 按进程名在系统层改路,覆盖 Navicat、IDE 里的 java、终端 git)、git 配置(`git config --global http.https://<host>/.proxy = socks5h://…`,写完终端里的 `git` 与 dsh-git 都走隧道);`dsh` 退出时三层一起停,不留残留。**全机一份规则表**(`~/.dsh-ris-ide/proxy.json`,`DSH_RIS_IDE_PROXY_HOME` 可改位置),整机生效、不区分工作区与会话,行尾「来源」列只记是用户行还是 yds 注入(`yds·win` / `yds·wsl` 还会标出命中的一侧)。提权是正常流程:Windows 侧启动时弹 UAC,Linux 侧需要免密 sudo;提不到权时弹窗里给出可直接粘贴的命令。Windows 侧启动还有三个实测过的细节:GUI 安装的服务 `ProxyBridgeSvc` 与 CLI 互斥(都抢 WinDivert 句柄),所以先停服务再起 CLI(停过会记下来,停止时尝试恢复);手起或遗留的 `ProxyBridge_CLI.exe` 先结束再接管;CLI 没有日志开关,stdout 重定向到 `%TEMP%\dsh-ris-proxybridge.log`,起不来时日志尾部就是错误原因。两层兜底:ProxyBridge 没在跑时,支持代理的程序(java / git / node / curl)启动时注入**本机 CONNECT 代理** `http://127.0.0.1:11081`(`ALL_PROXY`/`HTTP(S)_PROXY` + JVM 的 `-Dhttp(s).proxyHost/Port`),每一条连接仍然要过规则里的 IP/端口白名单——注入不再等于「把上游 SOCKS 地址直接发给程序」。想让某个程序完全绕过白名单、直连上游 SOCKS,就在该行加 `"direct": true`(`proxy.json` 里的行级开关,界面暂无控件);不支持代理的客户端(Navicat / JDBC)自动映射 `127.0.0.1:同端口`——这些映射行是实现细节,不进界面。维护页「代理设置」页签上部填上游 SOCKS(host/port)与本地 CONNECT 端口,下部是规则表:`启用 · 程序 · IP 允许(1.1.1.* / 逗号)· 端口允许(1521 / 1000-1010,* 表示不限)· 状态 · 命中方式`。**全机一张表、改动直接覆盖**:没有「读取 / 保存」按钮,也没有按工作区区分——改动 700 ms 后自动校验并写表(缺程序/IP/端口或端口格式不对只提示、不写),写进去的就是整张表,未出现的行会被删掉(这也意味着 `yds stop` 能靠「不发那些行」把注入的规则撤干净);写盘后先停旧的系统层拦截再按新表重启,换拦截的两轮探测在后台跑,页面不会被它卡住。「状态」列直接回答这行现在生效没(未启用 / 缺… / 端口格式 / 待启动 / 生效)。引擎与拦截只用一个按钮管:运行中显示「停止」,停止后变「启动」(未运行/运行中的另一状态不再另设按钮);点下去到生效之间按钮显示「启动中…」/「停止中…」并暂时不可点(等提权或引擎拉起),不会看起来像没反应。`yds proxy sync` 注入的规则在 **Windows 与 WSL 两侧各一行**(`java.exe` / `java`、`git.exe` / `git`,「来源」列标 `yds·win` / `yds·wsl`)——ProxyBridge 按镜像名匹配,`java.exe` 匹配不到 WSL 里的 `java`,以前这里只注入 Windows 侧。ProxyBridge 组件安装好之后卡片只显示「已安装 · 文件 N 个」,不再给下载/上传按钮。程序列两种来源——**运行中的进程**(本侧 + Windows 侧,只列支持 SOCKS 的)或**固定程序**(文件浏览器选可执行文件,可在启动前配好;裸名按镜像名匹配,含路径则精确到那个可执行文件)。
41
37
 
42
38
  - 弹窗**没有保存按钮**:改动在停手 700ms 后自动写盘;写的时候会过一遍校验——**新建但没填完整**的行不写入(底栏提示「N 条未填完整,未写入」),**已经在文件里**的行如果被改到一半,会连同新内容写成「停用」(提示「N 条改到一半,已置为停用」),不会留下旧内容假装生效,也不会让半截规则生效。写完本机引擎立刻生效、系统层拦截静默重启;「+ 添加规则」只追加一个空行,不会弹选择器盖住表格。
43
39
  - 「选…」打开的两页签选择器:**运行中的程序**(本侧 + Windows 侧进程,只列支持 SOCKS 的)、**选择文件**;文件页签下面是**树**——点文件夹原地展开(只读被展开的那一层),点文件即选中,不再一级一级「进入目录」;顶层入口只有**根路径 `/`** 与 **Windows C:/D:**(WSL 下 `/mnt` 就是 Windows 盘,所以只有一个文件页签;在那里选中的路径会写成 `D:\…`);**没有子项的文件夹**渲染成叶子(`·`、灰一点、点不动),不会出现按下去没反应的空展开。
@@ -63,11 +59,27 @@ DSH(DeepSeek Harness)Web GUI 右侧栏里的 **RIS-IDE 本地开发面板**
63
59
  - 两个插件**互不依赖**:各自都能单独安装、单独工作;装在一起时不会重复启动隧道。
64
60
  - 工作区出现 YMS/YonBIP 工程特征时,`ris_dev_programs` 的返回里会附一句安装建议——只是推荐,不会调用它。
65
61
 
62
+ ## 可选:risd 代理 daemon
63
+
64
+ 代理引擎默认仍由插件进程托管(`Ctrl+C` 会一并停掉,与之前一致)。如果你希望代理生命周期不再绑在某个 dsh 窗口上(多开时关一个不影响其他人、窗口全部关闭后仍可按策略保留),可以打开 `daemonMode`:
65
+
66
+ - **默认开启**(`daemonMode=auto`,1.8.0 起;`daemonMode=off` 或 `DSH_RISD_MODE=off` 是一词回滚)。插件挂载时会确保 `risd` 在跑(`127.0.0.1:11082`,随机 token,状态在 `~/.dsh-ris-ide/risd.json`),并登记一个租约(owner pid + 心跳,3s 探活)。
67
+ - daemon 接管**引擎**:启动/停止代理、写规则、git 代理、系统层拦截的 reload 都经它串行执行;插件只负责转发。最后一个租约消失后,daemon 按 `session` 策略依次撤销 git → 拦截 → 引擎;随后空闲 10 分钟自动退出,下次需要时再被拉起。
68
+ - daemon 还负责写桥接心跳(不再由 dsh 进程写)并独占 janitor;升级 daemon 时用 `POST /v1/shutdown {handoff:true}` 交接,新 daemon 直接收养既有引擎(pid 不变,隧道不断)。
69
+ - daemon 还托管**程序与 JDWP**:`ris_dev_programs/start/stop/logs/debug` 在 `daemonMode=auto` 时优先问 daemon(失败自动回退本地,`ris_dev_status` 仍读本地 pidfile/日志),所以刷新页面不会丢调试会话;dsh 全部关掉后打开 `http://127.0.0.1:11082/ui` 就能启停程序、看日志、断开调试会话、重启桥接。维护页顶部居中三个页签(顺序 **开发环境 · 代理设置 · 概览**;刷新或快捷键重载后回到上次的页签与工作区,dsh 的 ⧉ 只切换工作区、不抢你正在用的页签):**概览**(守护进程状态、代理运行状态、按工作区分组的运行中程序、调试中的进程,都可停止)、**代理设置**(不依赖 dsh 的**全局**规则编辑器:规则按机器生效、不区分工作区;SOCKS/监听端口/规则行增删改**即自动保存**——700 ms 防抖 + 行校验,完整后自动启动引擎,CAS 冲突静默换 revision 重写一次;「重启系统层拦截」只在确实需要(重载失败/需要提权)时出现,鼠标悬停会说明原因)、**开发环境**(整页无留白地嵌入 dsh 的 IDE;左侧是**默认收起**的工作区面板,点 header 左侧的 `‹`/`›` 展开或收起并记住选择;按目录名显示、列表来自正在运行的 dsh,点击即切换;5 分钟没动静的工作区标「未活跃」但仍可点,选中时上方提示该窗口可能已关闭;在 iframe 外任意处点击都会把光标送回 IDE;dsh 不在时该页签自动置灰并显示原因)。
70
+ - **改完不用强刷**:插件把当前 client bundle 的指纹随 SSE `hello` 下发(另有 `GET /dsh-ris-ide/build`),并每 30s 复查一次;发现代码变了只在右下角提示「IDE 界面已更新:刷新页面后生效」(**不自动 reload,避免丢掉未保存的编辑与会话视图**,点提示再刷新)。维护页 `/ui` 同理:daemon 重启成新代码、或源码比进程新、或 token 因 daemon 重启失效,都在顶部显示横幅;**「插件版本已更新」这条点按钮就是「重启并刷新」**——daemon 先交接重启(保留正在跑的代理引擎/桥接),新进程起来后本页自动重新加载,不用自己去命令行重启。**开发环境里有未保存文件时横幅会多一个「保存所有文件」按钮**——点它先把内嵌 IDE 的脏 buffer 全部保存再整页刷新(不会悄悄丢掉编辑);没有未保存内容时直接自动刷新,刷新后回到原来的页签与工作区。代理规则未保存时也会先确认。Node 在启动时 import 的模块不会再读盘,这不是浏览器缓存,强刷也没用。
71
+ - **保存即换新**:保存规则时先把上一份表应用过的机器级副作用收回(git 条目按新表切 host 或清掉;系统层拦截若重载失败就直接停止,而不是留着旧规则继续拦截),再应用新表。若提示「旧规则可能仍在生效 / 需要提权」,提示旁有 **提权重启** 按钮:点一下即「停止 → 重载 → 启动」(Windows 弹一次 UAC;本侧 root 桥接需要 sudo,命令会显示在提示里)。
72
+ - daemon 不可达时视图与会话内动作自动回退到插件本地执行,维护页打不开时可以用 CLI;**`daemonMode=off` 即完全回到旧行为**,此时点 ⧉ 不会拉起 daemon(两个 owner 会抢同一个引擎与 janitor),而是直接打开独立 IDE 窗口。
73
+ - **入口**:dsh 顶部 ⧉ 和面板控制台的 ⧉ 都打开 **risd 维护页**(面板里不再有代理按钮:规则编辑只在这个页面),并且自动选中当前工作区(页签保持你上次的选择);**daemon 已停止或意外退出时,点 ⧉ 会先自动把它拉起**(点一次即可,失败才回退到独立窗口)。维护页「概览 → 守护进程」一行可看状态并停止 daemon;停止会同时停掉它托管的程序、调试会话和代理,页面会先弹确认列出将停止的内容。**概览底部还有「生命周期」设置**:守护进程 / 代理引擎 / 程序 / 调试会话各自可以选择是否「跟随 dsh」(最后一个 dsh 窗口退出后停)。**「跟随 daemon」是强制的**:停止 daemon 时它托管的程序、调试会话与代理一定一起停,不提供关闭项。默认是代理跟随 dsh、程序与调试不跟随 dsh,配置存在 `~/.dsh-ris-ide/risd-lifecycle.json`,保存即生效、不用重启。
74
+ - 手动体验(`risd` 命令由本包的 `bin` 暴露;`npm link` 或把 `bin/risd.mjs` 软链进 PATH 即可):`risd serve`、`risd status`、`risd health`、`risd stop`、`risd version`;日志 `~/.dsh-ris-ide/risd.log`。
75
+
76
+ 已知边界:本侧(WSL/Linux root 起的)系统层拦截仍不支持热重载(要重启);规则表的 `shadow` 端口没有内置默认值,全部来自配置与 dsh-ris-yds 的写入。
77
+
66
78
  ## 安装
67
79
 
68
80
  需要 DSH `>= 0.2.0-rc.2`,且 Web GUI 带官方右侧栏服务(`sidebarRight` / `sidebarRightTabs` / `slots`)。
69
81
 
70
- **本插件自身不依赖任何外部资源**:零运行时 npm 依赖、客户端产物(含 CodeMirror)已随包发布、不联网、不起独立端口,只使用 DSH 自带路由与 Node 内置模块。本机工具只在特定能力上需要:`git`(有则按 gitignore 过滤文件树/搜索;**没有 git 也能用**,退化为不过滤)、JDK `java`/`javap`(启动/调试 Java 程序、反汇编依赖类)、Maven(默认起 Spring 服务时会 `mvn compile`,本地仓库没缓存时会联网下载依赖)、Node/前端包管理器(启动前端 dev server)。
82
+ **本插件自身不依赖任何外部资源**:零运行时 npm 依赖、客户端产物(含 CodeMirror)已随包发布、不起独立端口,只使用 DSH 自带路由与 Node 内置模块。唯一的联网动作是用户在维护页触发的 **ProxyBridge 组件下载**(系统层拦截首次启用时;可换成内网/本地上传源),除此之外不联网。本机工具只在特定能力上需要:`git`(有则按 gitignore 过滤文件树/搜索;**没有 git 也能用**,退化为不过滤)、JDK `java`/`javap`(启动/调试 Java 程序、反汇编依赖类)、Maven(默认起 Spring 服务时会 `mvn compile`,本地仓库没缓存时会联网下载依赖)、Node/前端包管理器(启动前端 dev server)。
71
83
 
72
84
  发布到 npmjs 后:
73
85
 
@@ -6,6 +6,12 @@
6
6
  * layers. Polls that pid; when it disappears (graceful exit, crash, `kill -9`,
7
7
  * closed terminal) it performs the same cleanup the exit hook does, then exits.
8
8
  *
9
+ * Phase 1b P6 adds a handoff window: when the owner exits on purpose to let a
10
+ * successor daemon adopt the engine, its stop writes `handoffAt` into our state
11
+ * file first. In that window "owner died" must not be read as "the machine is
12
+ * free" — we wait for the successor to register itself and keep watching it
13
+ * instead of tearing the network down.
14
+ *
9
15
  * Nothing here needs dsh: it runs in its own session, with only the state files
10
16
  * (`proxy.pid`, `proxybridge.local.pid` / `proxybridge.windows.pid`,
11
17
  * `proxybridge-service.json`, `git-proxy.json`) as input.
@@ -16,10 +22,17 @@
16
22
  *
17
23
  * Usage: proxy-janitor.mjs --owner <pid> [--home <proxy home>] [--poll <ms>]
18
24
  */
19
- import { appendFileSync, mkdirSync, unlinkSync } from 'node:fs'
25
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'
20
26
  import { join } from 'node:path'
21
27
 
22
- import { JANITOR_POLL_MS, cleanupSideEffects, janitorStatePath, pendingSideEffects } from '../lib/janitor.js'
28
+ import {
29
+ JANITOR_HANDOFF_GRACE_MS,
30
+ JANITOR_POLL_MS,
31
+ cleanupSideEffects,
32
+ janitorStatePath,
33
+ pendingSideEffects,
34
+ removeOwnJanitorState,
35
+ } from '../lib/janitor.js'
23
36
 
24
37
  /** Parse `--flag value` pairs without pulling in a dependency. */
25
38
  function parse(argv) {
@@ -37,11 +50,12 @@ function parse(argv) {
37
50
  const args = parse(process.argv.slice(2))
38
51
  const owner = Number.parseInt(args.owner ?? '', 10)
39
52
  const poll = Number.parseInt(args.poll ?? '', 10) || JANITOR_POLL_MS
40
- const logPath = join(args.home ?? process.env.DSH_RIS_IDE_PROXY_HOME ?? '.', 'janitor.log')
53
+ const home = args.home ?? process.env.DSH_RIS_IDE_PROXY_HOME ?? '.'
54
+ const logPath = join(home, 'janitor.log')
41
55
 
42
56
  function log(line) {
43
57
  try {
44
- mkdirSync(join(args.home ?? process.env.DSH_RIS_IDE_PROXY_HOME ?? '.'), { recursive: true })
58
+ mkdirSync(home, { recursive: true })
45
59
  appendFileSync(logPath, `${new Date().toISOString()} [${process.pid}] ${line}\n`)
46
60
  } catch {
47
61
  /* logging must never take the janitor down */
@@ -62,13 +76,63 @@ function alive(pid) {
62
76
  }
63
77
  }
64
78
 
65
- log(`监视 dsh ${owner}(轮询 ${poll}ms,状态 ${janitorStatePath()})`)
79
+ /**
80
+ * Is the owner's exit an intentional handoff? The predecessor writes `handoffAt`
81
+ * before exiting; only a fresh stamp counts, so a stale one cannot keep the
82
+ * machine from being cleaned up forever.
83
+ * @returns {number|null} absolute deadline, null when this is not a handoff.
84
+ */
85
+ function handoffDeadline() {
86
+ try {
87
+ const raw = JSON.parse(readFileSync(janitorStatePath(), 'utf8'))
88
+ const at = typeof raw.handoffAt === 'string' ? Date.parse(raw.handoffAt) : Number.NaN
89
+ if (!Number.isFinite(at)) return null
90
+ const age = Date.now() - at
91
+ if (age < 0 || age >= JANITOR_HANDOFF_GRACE_MS) return null
92
+ return at + JANITOR_HANDOFF_GRACE_MS
93
+ } catch {
94
+ return null
95
+ }
96
+ }
66
97
 
67
- const timer = setInterval(() => {
68
- if (alive(owner)) return
69
- clearInterval(timer)
98
+ /**
99
+ * Wait for the successor's own registration, then report both pids: `owner` is the
100
+ * dsh/risd process to watch next, `watcher` is the successor's own janitor.
101
+ *
102
+ * The field is `owner` — `armJanitor()` writes `{pid, owner, log}`. Reading
103
+ * `ownerPid` (review B-P1-5) always produced NaN, so the handoff window expired
104
+ * and this watcher tore down the engine the successor had just adopted.
105
+ * @returns {Promise<{owner:number, watcher:number}|null>} pids, or null on timeout.
106
+ */
107
+ function adoptSuccessor(previousOwner, deadline) {
108
+ return new Promise((resolve) => {
109
+ const tick = () => {
110
+ if (Date.now() > deadline) {
111
+ resolve(null)
112
+ return
113
+ }
114
+ try {
115
+ const raw = JSON.parse(readFileSync(janitorStatePath(), 'utf8'))
116
+ const candidate = Number.isInteger(raw.owner) ? raw.owner : Number(raw.ownerPid)
117
+ const watcher = Number.isInteger(raw.pid) ? raw.pid : 0
118
+ if (Number.isInteger(candidate) && candidate > 0 && candidate !== previousOwner && alive(candidate)) {
119
+ resolve({ owner: candidate, watcher })
120
+ return
121
+ }
122
+ } catch {
123
+ /* the state file may be mid-rewrite; keep waiting */
124
+ }
125
+ setTimeout(tick, 250)
126
+ }
127
+ tick()
128
+ })
129
+ }
130
+
131
+ let watched = owner
132
+
133
+ function cleanup() {
70
134
  const pending = pendingSideEffects()
71
- log(`dsh ${owner} 已退出,开始清理: ${JSON.stringify(pending)}`)
135
+ log(`dsh ${watched} 已退出,开始清理: ${JSON.stringify(pending)}`)
72
136
  try {
73
137
  const done = cleanupSideEffects({ log })
74
138
  log(`清理完成: ${JSON.stringify({ engine: done.engine, bridge: done.bridge, service: done.service, git: done.git })}`)
@@ -78,11 +142,42 @@ const timer = setInterval(() => {
78
142
  try {
79
143
  // Our own state file is the last thing to go: while it exists, `yds proxy
80
144
  // status` reports a watcher, and a fresh start re-arms instead of doubling.
81
- unlinkSync(janitorStatePath())
145
+ // Only ours, though: a successor may already have armed a newer watcher and
146
+ // written its own state file by now (review B-P2-9).
147
+ removeOwnJanitorState(process.pid)
82
148
  } catch {
83
149
  /* already gone */
84
150
  }
85
151
  process.exit(0)
152
+ }
153
+
154
+ function startWatch() {
155
+ log(`监视 dsh ${watched}(轮询 ${poll}ms,状态 ${janitorStatePath()})`)
86
156
  // The interval must stay referenced: an unreferenced timer lets node exit
87
157
  // immediately, which is the opposite of a watchdog.
88
- })
158
+ const timer = setInterval(async () => {
159
+ if (alive(watched)) return
160
+ clearInterval(timer)
161
+ const deadline = handoffDeadline()
162
+ if (deadline !== null) {
163
+ log(`dsh ${watched} 已退出,处于交接窗口(剩余 ${Math.max(0, deadline - Date.now())}ms),等待继任者`)
164
+ const successor = await adoptSuccessor(watched, deadline)
165
+ if (successor !== null) {
166
+ // The successor armed its own watcher (it wrote the state file we just
167
+ // read): hand over and exit, so repeated handoffs do not accumulate
168
+ // watchers. If it failed to arm, keep watching on its behalf.
169
+ if (successor.watcher > 0 && successor.watcher !== process.pid && alive(successor.watcher)) {
170
+ log(`继任者 ${successor.owner} 已接管(其 janitor pid ${successor.watcher}),本守护退出`)
171
+ process.exit(0)
172
+ }
173
+ watched = successor.owner
174
+ startWatch()
175
+ return
176
+ }
177
+ log('交接窗口内没有继任者,按原逻辑清理')
178
+ }
179
+ cleanup()
180
+ })
181
+ }
182
+
183
+ startWatch()
package/bin/risd.mjs ADDED
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * risd — command line.
4
+ *
5
+ * risd serve [--home <dir>] [--port <n>] run the daemon (the only mode that listens)
6
+ * risd status [--home <dir>] print the stored state + a health probe
7
+ * risd health [--home <dir>] print the health JSON (for scripts)
8
+ * risd stop [--home <dir>] [--handoff] ask a running daemon to exit
9
+ * (--handoff keeps the engine for a successor)
10
+ * risd version print daemon + api version
11
+ *
12
+ * Exit codes for `serve` (what the plugin's spawn path distinguishes):
13
+ * 0 started, or another daemon already owns the port
14
+ * 3 another process speaks a different `/v1` version -> upgrade required
15
+ * 4 the port is occupied by something that is not risd
16
+ * 1 anything else (bad args, state could not be written)
17
+ *
18
+ * Kept deliberately thin: all behaviour lives in `lib/risd/*` so it is testable
19
+ * without spawning a process (the tests do both).
20
+ *
21
+ * @module dsh-risd/cli
22
+ */
23
+ import { readFileSync } from 'node:fs'
24
+ import { DEFAULT_RISD_PORT, RISD_API_VERSION, risdHomeDir, risdStatePath, readRisdState, dropStaleSpawnLock } from '../lib/risd/state.js'
25
+ import { pidAlive } from '../lib/proxy.js'
26
+ import { createRisdLogger, risdLogPath } from '../lib/risd/log.js'
27
+ import { startRisd } from '../lib/risd/server.js'
28
+ import { probeRisdHealth } from '../lib/risd/server.js'
29
+
30
+ const PACKAGE_VERSION = (() => {
31
+ try {
32
+ return JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version ?? '0.0.0'
33
+ } catch {
34
+ return '0.0.0'
35
+ }
36
+ })()
37
+
38
+ function parseArgs(argv) {
39
+ const options = { command: 'status', home: undefined, port: undefined }
40
+ const rest = []
41
+ for (let index = 0; index < argv.length; index += 1) {
42
+ const arg = argv[index]
43
+ if (arg === '--home' || arg === '-C') options.home = argv[++index]
44
+ else if (arg.startsWith('--home=')) options.home = arg.slice('--home='.length)
45
+ else if (arg === '--handoff') options.handoff = true
46
+ // m11421: successor started by POST /v1/restart — wait for the predecessor to
47
+ // exit so the port is free and the handoff stamp is on disk.
48
+ else if (arg === '--wait-pid') options.waitPid = Number(argv[++index])
49
+ else if (arg === '--port' || arg === '-p') options.port = Number(argv[++index])
50
+ else if (arg.startsWith('--port=')) options.port = Number(arg.slice('--port='.length))
51
+ else if (arg.startsWith('-')) throw new Error(`unknown option: ${arg}`)
52
+ else rest.push(arg)
53
+ }
54
+ if (rest.length > 0) options.command = rest[0]
55
+ if (options.port !== undefined && (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)) {
56
+ throw new Error(`invalid --port: ${options.port}`)
57
+ }
58
+ if (options.waitPid !== undefined && (!Number.isInteger(options.waitPid) || options.waitPid <= 0)) {
59
+ throw new Error(`invalid --wait-pid: ${options.waitPid}`)
60
+ }
61
+ return options
62
+ }
63
+
64
+ function line(text) {
65
+ process.stdout.write(`${text}\n`)
66
+ }
67
+
68
+ async function request(state, path, { method = 'GET', body = undefined, timeoutMs = 2000 } = {}) {
69
+ const response = await fetch(`${state.url}${path}`, {
70
+ method,
71
+ headers: {
72
+ authorization: `Bearer ${state.token}`,
73
+ 'x-risd-api-version': String(RISD_API_VERSION),
74
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
75
+ },
76
+ body: body === undefined ? undefined : JSON.stringify(body),
77
+ signal: AbortSignal.timeout(timeoutMs),
78
+ })
79
+ const text = await response.text()
80
+ let payload
81
+ try {
82
+ payload = JSON.parse(text)
83
+ } catch {
84
+ payload = { ok: false, code: 'bad-response', message: text.slice(0, 200) }
85
+ }
86
+ return { status: response.status, payload }
87
+ }
88
+
89
+ /** Resolve once `pid` is gone (ESRCH) or the deadline passes; never throws. */
90
+ function waitForPidExit(pid, timeoutMs) {
91
+ const deadline = Date.now() + timeoutMs
92
+ return new Promise((resolve) => {
93
+ const tick = () => {
94
+ let alive = true
95
+ try { process.kill(pid, 0) } catch (error) { alive = error.code === 'EPERM' }
96
+ if (!alive || Date.now() > deadline) { resolve(); return }
97
+ setTimeout(tick, 100)
98
+ }
99
+ tick()
100
+ })
101
+ }
102
+
103
+ async function serve(options) {
104
+ // Never assign `undefined` to process.env: it becomes the string "undefined",
105
+ // which then resolves every machine-level file (state, token, heartbeat) under
106
+ // `<cwd>/undefined/`. `risdHomeDir()` falls back to the real proxy home.
107
+ const home = risdHomeDir(options.home)
108
+ // A successor spawned by POST /v1/restart must not treat the dying predecessor as
109
+ // "already running": wait until its pid is gone, then serve (m11421).
110
+ if (options.waitPid !== undefined) await waitForPidExit(options.waitPid, 20000)
111
+ // Heartbeat, janitor state and the git-proxy entry all resolve through the
112
+ // machine-level home; a daemon started for a test home must not touch the real
113
+ // one, and the plugin always points at the same home it reads `risd.json` from.
114
+ process.env.DSH_RIS_IDE_PROXY_HOME = home
115
+ const logger = createRisdLogger(home)
116
+ logger.info(`starting: pid=${process.pid} version=${PACKAGE_VERSION}`)
117
+ dropStaleSpawnLock(home)
118
+ let stopping = false
119
+ let current = null
120
+ const stop = async (code, handoff = false) => {
121
+ if (stopping) return
122
+ stopping = true
123
+ logger.info(handoff ? 'stopping: handoff requested' : 'stopping: shutdown requested')
124
+ try {
125
+ await current?.stop({ handoff })
126
+ } finally {
127
+ process.exit(code)
128
+ }
129
+ }
130
+ const envPort = Number(process.env.DSH_RISD_PORT)
131
+ const port = options.port ?? (Number.isInteger(envPort) && envPort >= 0 ? envPort : DEFAULT_RISD_PORT)
132
+ const started = await startRisd({
133
+ home,
134
+ port,
135
+ version: PACKAGE_VERSION,
136
+ onShutdown: (handoff) => stop(0, handoff === true),
137
+ })
138
+ if (!started.ok) {
139
+ if (started.code === 'already-running') {
140
+ logger.info(`already running: pid=${started.pid} port=${started.port}`)
141
+ process.stderr.write(`risd: already running (pid ${started.pid}) on 127.0.0.1:${started.port}\n`)
142
+ process.exit(0)
143
+ }
144
+ if (started.code === 'api-mismatch') {
145
+ logger.warn(`api mismatch: found ${started.found} on port ${started.port}`)
146
+ process.stderr.write(`risd: a daemon with apiVersion ${started.found} is running on 127.0.0.1:${started.port}; this build speaks ${RISD_API_VERSION} (upgrade required)\n`)
147
+ process.exit(3)
148
+ }
149
+ if (started.code === 'home-mismatch') {
150
+ // Two homes on one port cannot both own the state file; the healthy daemon
151
+ // wins and this one explains how to run alongside it (review A-P2-9).
152
+ logger.warn(`home mismatch: ${started.found} already owns port ${started.port}`)
153
+ process.stderr.write(
154
+ `risd: 127.0.0.1:${started.port} is already served by the daemon whose home is ${started.found};\n` +
155
+ ` this process wants home ${started.home}. Stop that daemon or run with --port <n>.\n`,
156
+ )
157
+ process.exit(4)
158
+ }
159
+ if (started.code === 'port-busy') {
160
+ logger.warn(`port busy: ${started.port} is not risd`)
161
+ process.stderr.write(
162
+ `risd: 127.0.0.1:${started.port} is occupied by a process that is not risd.\n` +
163
+ ` stop it, or pick another port (risd serve --port <n>, DSH_RISD_PORT, or daemonMode stays off)\n`,
164
+ )
165
+ process.exit(4)
166
+ }
167
+ logger.error(`start failed: ${started.code} ${started.error?.message ?? ''}`)
168
+ process.stderr.write(`risd: could not start (${started.code}): ${started.error?.message ?? ''}\n`)
169
+ process.exit(1)
170
+ }
171
+ current = started
172
+ logger.info(`ready: port=${started.port} state=${risdStatePath(home)}`)
173
+ process.stderr.write(`risd: listening on http://127.0.0.1:${started.port} (pid ${process.pid})\n`)
174
+ process.stderr.write(`risd: maintenance page http://127.0.0.1:${started.port}/ui (engine/programs/logs/debug, no dsh needed)\n`)
175
+ for (const signal of ['SIGTERM', 'SIGINT']) {
176
+ process.once(signal, () => void stop(0))
177
+ }
178
+ }
179
+
180
+ async function status(options) {
181
+ const state = readRisdState(options.home)
182
+ if (state === null) {
183
+ line('risd: not running (no risd.json)')
184
+ line('hint: run `risd serve` to start it (clicking ⧉ in dsh also starts it)')
185
+ return 1
186
+ }
187
+ const probe = await probeRisdHealth(state.port, 1000)
188
+ line(`risd: ${probe?.ok === true ? 'running' : 'unreachable'}`)
189
+ if (probe?.ok !== true) line('hint: the state file is stale; run `risd serve` to restart (clicking ⧉ in dsh also starts it)')
190
+ line(` pid ${state.pid}`)
191
+ line(` port ${state.port}`)
192
+ line(` api ${state.apiVersion} (this CLI speaks ${RISD_API_VERSION})`)
193
+ line(` version ${state.version}`)
194
+ line(` startedAt ${state.startedAt}`)
195
+ line(` home ${state.home}`)
196
+ line(` log ${risdLogPath(options.home)}`)
197
+ line(` page http://127.0.0.1:${state.port}/ui`)
198
+ return probe?.ok === true ? 0 : 1
199
+ }
200
+
201
+ async function health(options) {
202
+ const state = readRisdState(options.home)
203
+ if (state === null) {
204
+ process.stderr.write('risd: not running (no risd.json)\n')
205
+ process.stderr.write('hint: run `risd serve` to start it (clicking ⧉ in dsh also starts it)\n')
206
+ return 1
207
+ }
208
+ const { status: code, payload } = await request(state, '/v1/health', { timeoutMs: 1000 }).catch((error) => ({
209
+ status: 0,
210
+ payload: { ok: false, code: 'unreachable', message: String(error?.message ?? error) },
211
+ }))
212
+ line(JSON.stringify(payload, null, 2))
213
+ return code === 200 ? 0 : 1
214
+ }
215
+
216
+ async function stop(options) {
217
+ const state = readRisdState(options.home)
218
+ if (state === null) {
219
+ line('risd: not running (no risd.json)')
220
+ return 0
221
+ }
222
+ const handoff = options.handoff === true
223
+ const { status: code, payload } = await request(state, '/v1/shutdown', { method: 'POST', body: { reason: 'cli', handoff } }).catch((error) => ({
224
+ status: 0,
225
+ payload: { ok: false, code: 'unreachable', message: String(error?.message ?? error) },
226
+ }))
227
+ if (code !== 200) {
228
+ line(`risd: shutdown failed (${code}): ${payload?.message ?? payload?.code ?? 'unknown'}`)
229
+ return 1
230
+ }
231
+ if (handoff) {
232
+ // A handoff keeps risd.json on purpose (the successor reads it). Wait for the
233
+ // pid to change instead of for the file to disappear, so "handed off" only
234
+ // means success once somebody actually took over (review A-P2-7).
235
+ for (let attempt = 0; attempt < 100; attempt += 1) {
236
+ const next = readRisdState(options.home)
237
+ if (next !== null && Number(next.pid) !== Number(state.pid) && pidAlive(next.pid)) {
238
+ line(`risd: handed off to pid ${next.pid}`)
239
+ return 0
240
+ }
241
+ await new Promise((resolve) => setTimeout(resolve, 100))
242
+ }
243
+ line('risd: handed off, but no successor picked it up yet (the janitor keeps the engine)')
244
+ return 1
245
+ }
246
+ // 10 s: shutdown stops supervised programs first and then the network layers, so
247
+ // a busy machine can legitimately need more than the old 5 s (and the generic
248
+ // "still running" answer made `risd stop` look broken).
249
+ for (let attempt = 0; attempt < 100; attempt += 1) {
250
+ // `state` may be rewritten by a successor; the pid, not the file, says whether
251
+ // OUR daemon is gone (review A-P2-7).
252
+ if (!pidAlive(state.pid)) {
253
+ line('risd: stopped')
254
+ return 0
255
+ }
256
+ await new Promise((resolve) => setTimeout(resolve, 100))
257
+ }
258
+ line('risd: shutdown accepted but the daemon is still running')
259
+ return 1
260
+ }
261
+
262
+ async function main() {
263
+ let options
264
+ try {
265
+ options = parseArgs(process.argv.slice(2))
266
+ } catch (error) {
267
+ process.stderr.write(`risd: ${error.message}\n`)
268
+ process.exit(1)
269
+ }
270
+ if (options.command === 'version' || options.command === '--version') {
271
+ line(`risd ${PACKAGE_VERSION} (apiVersion ${RISD_API_VERSION})`)
272
+ return 0
273
+ }
274
+ if (options.command === 'serve') {
275
+ await serve(options)
276
+ return 0
277
+ }
278
+ if (options.command === 'status') return status(options)
279
+ if (options.command === 'health') return health(options)
280
+ if (options.command === 'stop') return stop(options)
281
+ process.stderr.write(`risd: unknown command "${options.command}" (serve|status|health|stop|version)\n`)
282
+ return 1
283
+ }
284
+
285
+ main().then((code) => {
286
+ process.exitCode = typeof code === 'number' ? code : 0
287
+ })
@@ -1,4 +1,4 @@
1
- #requires -Version 5.1
1
+ #requires -Version 5.1
2
2
  <#
3
3
  .SYNOPSIS
4
4
  dsh-ris-ide 的 Windows wrapper:把服务输出写进日志、写 pidfile、让面板能停能查。
@@ -15,7 +15,11 @@
15
15
  - spring : 依次 `mvn -Pdev compile`、`mvn -Pdev dependency:build-classpath …`,
16
16
  然后 `java -DJM.LOG.PATH=… -Dcsp.sentinel.log.dir=… <jvmArgs> -cp "target\classes;<cp>" <mainClass> <args>`;
17
17
  - frontend : `<pnpm|npm|yarn>.cmd run <script>`;
18
- - command : 用户的 `startCommand`,交给 `cmd.exe /d /s /c` 执行。
18
+ - command : 用户的 `startCommand`,交给 `cmd.exe /d /s /c "<命令原样>"` 执行;
19
+ bash 方言($()、${...}、exec)会直接启动失败并在日志里提示改用 runtime:"bash"。
20
+
21
+ 本文件必须以 UTF-8 with BOM 保存:Windows PowerShell 5.1 对没有 BOM 的文件按 ANSI
22
+ 解码,中文注释会与换行拼错行(真机已复现),导致代码行被吞掉。
19
23
 
20
24
  pidfile 与 .sh 一致:`<log>.pid` 一行 `<servicePid> <wrapperPid> <epochMs> [<stopGraceMs>]`。
21
25
  停止由宿主 `taskkill /PID <wrapperPid> /T /F` 完成(Windows 没有 POSIX 信号/进程组,
@@ -47,6 +51,29 @@ function Quote-WinArg([string]$Value) {
47
51
  return '"' + ($Value -replace '"', '\"') + '"'
48
52
  }
49
53
 
54
+ <#
55
+ startCommand is a command for the CURRENT runtime's shell: with runtime=powershell
56
+ it goes to cmd.exe /d /s /c, with runtime=bash it goes to bash -lc. Bash syntax
57
+ ($(...), ${...}, exec) is not expanded/understood by cmd; failing with a clear hint
58
+ beats silently running a broken command line. ${JDWP_ARGS} has already been
59
+ substituted by the host, so a remaining ${...} is a suspicious bash expansion.
60
+
61
+ Keep these messages ASCII: Windows PowerShell 5.1 reads a BOM-less file as ANSI,
62
+ so non-ASCII string literals would be garbled in the log.
63
+ #>
64
+ function Assert-CommandDialect([string]$Command) {
65
+ $Hint = ' This program runs with runtime "powershell" on Windows, so the startCommand is executed by cmd.exe.'
66
+ if ($Command -match '\$\(') {
67
+ throw ('startCommand uses bash command substitution $(...), which cmd cannot run.' + $Hint + ' Set runtime to "bash" for this program (requires Git Bash) or rewrite it as a cmd command. command: ' + $Command)
68
+ }
69
+ if ($Command -match '\$\{[^}]*\}') {
70
+ throw ('startCommand uses ${...} variable expansion, which is bash syntax.' + $Hint + ' Use %VAR% or set runtime to "bash". command: ' + $Command)
71
+ }
72
+ if ($Command -match '(^|\s|&&|\|\|)exec\s+') {
73
+ throw ('startCommand uses the bash exec builtin.' + $Hint + ' Drop exec (Windows starts the process directly) or set runtime to "bash". command: ' + $Command)
74
+ }
75
+ }
76
+
50
77
  $SpecJson = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($SpecBase64))
51
78
  $Spec = $SpecJson | ConvertFrom-Json
52
79
 
@@ -67,6 +94,8 @@ Write-Log $LogFile ('--- kind: ' + $Kind + ' dir: ' + $WorkDir + ' ---')
67
94
 
68
95
  $Exe = $null
69
96
  $ArgList = @()
97
+ # kind=command sets this to a raw cmd.exe argument line instead of a quoted argv.
98
+ $RawArgs = $null
70
99
 
71
100
  try {
72
101
  switch ($Kind) {
@@ -105,9 +134,15 @@ try {
105
134
  $ArgList = @('run', $Script)
106
135
  }
107
136
  default {
137
+ $Command = [string]$Spec.command
138
+ if ([string]::IsNullOrWhiteSpace($Command)) { throw 'startCommand is empty (nothing to run)' }
139
+ Assert-CommandDialect $Command
108
140
  $Exe = Resolve-CommandPath @('cmd.exe')
109
141
  if ($null -eq $Exe) { throw 'cmd.exe not found' }
110
- $ArgList = @('/d', '/s', '/c', [string]$Spec.command)
142
+ # 命令交给 cmd.exe /d /s /c;`/s` 至多剥掉首尾各一个引号,所以整条命令包一层
143
+ # 引号、内部引号原样保留才是 cmd 的语义。旧的 argv+Quote-WinArg 组装会把内部
144
+ # " 变成 cmd 不认识的 \"(cmd 不是 .NET 参数解析器)。
145
+ $RawArgs = '/d /s /c "' + $Command + '"'
111
146
  }
112
147
  }
113
148
  } catch {
@@ -115,7 +150,10 @@ try {
115
150
  exit 1
116
151
  }
117
152
 
118
- Write-Log $LogFile ('--- exec: ' + $Exe + ' ' + (($ArgList | ForEach-Object { Quote-WinArg ([string]$_) }) -join ' ') + ' ---')
153
+ # kind=command 用 cmd.exe 的原始参数行(见上);其余 kind 都是结构化 argv,逐项引用。
154
+ $ExecArgs = if ($null -ne $RawArgs) { $RawArgs } else { (($ArgList | ForEach-Object { Quote-WinArg ([string]$_) }) -join ' ') }
155
+
156
+ Write-Log $LogFile ('--- exec: ' + $Exe + ' ' + $ExecArgs + ' ---')
119
157
 
120
158
  $StartInfo = New-Object System.Diagnostics.ProcessStartInfo
121
159
  $StartInfo.FileName = $Exe
@@ -124,7 +162,7 @@ $StartInfo.UseShellExecute = $false
124
162
  $StartInfo.RedirectStandardOutput = $true
125
163
  $StartInfo.RedirectStandardError = $true
126
164
  $StartInfo.CreateNoWindow = $true
127
- $StartInfo.Arguments = (($ArgList | ForEach-Object { Quote-WinArg ([string]$_) }) -join ' ')
165
+ $StartInfo.Arguments = $ExecArgs
128
166
 
129
167
  $Process = New-Object System.Diagnostics.Process
130
168
  $Process.StartInfo = $StartInfo