pi-web-ui 0.114.0 → 0.114.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +187 -187
  3. package/README.zh-CN.md +227 -227
  4. package/README.zh-TW.md +227 -227
  5. package/bin/device-hub-cli.mjs +577 -577
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -9
  8. package/bin/pi-web-ui.mjs +4081 -4073
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service.js +131 -55
  12. package/dist/server/attachments.js +51 -5
  13. package/dist/server/canvas/canvas-agent-tool.js +3 -3
  14. package/dist/server/canvas/canvas-cards.js +1 -1
  15. package/dist/server/canvas/canvas-orchestrator.js +3 -3
  16. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  17. package/dist/server/canvas/canvas-validation.js +1 -1
  18. package/dist/server/client-state.js +6 -2
  19. package/dist/server/compaction-instructions.js +8 -8
  20. package/dist/server/device-center/connector.js +33 -14
  21. package/dist/server/device-center/desktop-page.js +228 -228
  22. package/dist/server/device-center/hub-page.js +64 -64
  23. package/dist/server/device-center/hub.js +2 -1
  24. package/dist/server/device-center/local-hub.js +92 -0
  25. package/dist/server/device-center/local.js +60 -7
  26. package/dist/server/device-center/native-desktop/macos.js +190 -190
  27. package/dist/server/device-center/native-desktop/windows.js +116 -116
  28. package/dist/server/device-center/path-portal.js +1 -1
  29. package/dist/server/device-center/relay.js +45 -8
  30. package/dist/server/dispatch-domain-handlers.js +1 -0
  31. package/dist/server/dsh/dsh-agent-service.js +5 -1
  32. package/dist/server/dsh/runtime/cordis.yml +1 -1
  33. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  34. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  35. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  36. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  37. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  38. package/dist/server/engine-probe.js +36 -6
  39. package/dist/server/eval-tool.js +135 -135
  40. package/dist/server/global-loader.js +40 -2
  41. package/dist/server/index.js +56 -32
  42. package/dist/server/patch-bash-process.js +125 -0
  43. package/dist/server/patch-tool.js +9 -9
  44. package/dist/server/patch-turn-end-boundary.js +3 -3
  45. package/dist/server/persona-chain.js +8 -8
  46. package/dist/server/plugins.js +26 -2
  47. package/dist/server/preset-fields.js +7 -0
  48. package/dist/server/preset-share.js +1 -0
  49. package/dist/server/prompt-templates.js +106 -0
  50. package/dist/server/protocol-version.js +1 -1
  51. package/dist/server/remote-ssh-service.js +39 -39
  52. package/dist/server/resolve-global-sdk.js +2 -0
  53. package/dist/server/schedule-agent-tool.js +39 -21
  54. package/dist/server/scheduler-tasks.js +45 -9
  55. package/dist/server/scm-commitmsg.js +10 -10
  56. package/dist/server/settings-service.js +6 -0
  57. package/dist/server/setup-page.js +620 -620
  58. package/dist/server/text-quote.js +9 -0
  59. package/dist/server/tool-manager.js +2 -1
  60. package/dist/server/universal/drivers/claude-code.js +5 -0
  61. package/dist/server/universal/drivers/codex.js +336 -0
  62. package/dist/server/universal/index.js +1 -0
  63. package/dist/server/universal/universal-attachments.js +24 -1
  64. package/dist/server/universal/universal-session.js +23 -0
  65. package/dist/server/vision-bridge.js +18 -18
  66. package/docs/device-center.md +148 -142
  67. package/docs/device-desktop.md +48 -48
  68. package/docs/dsh-engine.md +493 -493
  69. package/extensions/webui.ts +335 -335
  70. package/package.json +2 -2
  71. package/plugin-sdk/README.md +174 -174
  72. package/plugin-sdk/client-utils.mjs +279 -279
  73. package/plugin-sdk/import-check.mjs +210 -210
  74. package/plugin-sdk/index.d.ts +698 -698
  75. package/plugin-sdk/index.mjs +696 -696
  76. package/plugin-sdk/package.json +13 -13
  77. package/plugin-sdk/ssh-host-trust.mjs +225 -225
  78. package/plugins/catalog.json +10 -0
  79. package/themes/aetheris.css +501 -501
  80. package/themes/ayu-light.css +116 -116
  81. package/themes/bases/flow-base.css +1357 -1357
  82. package/themes/bases/obsidian-base.css +895 -895
  83. package/themes/bases/statusbar-flat-base.css +112 -112
  84. package/themes/bases/zhujian-base.css +688 -688
  85. package/themes/bases/zhupi-base.css +660 -660
  86. package/themes/catppuccin-latte.css +119 -119
  87. package/themes/catppuccin.css +116 -116
  88. package/themes/claude-code-dark.css +147 -147
  89. package/themes/codex.css +114 -114
  90. package/themes/cyberpunk.css +50 -50
  91. package/themes/dark-teal.css +264 -264
  92. package/themes/dazzle.css +38 -38
  93. package/themes/everforest-light.css +115 -115
  94. package/themes/flow-light.css +164 -164
  95. package/themes/flow.css +161 -161
  96. package/themes/geist.css +114 -114
  97. package/themes/gruvbox-light.css +115 -115
  98. package/themes/kanagawa-lotus.css +115 -115
  99. package/themes/md-preview.css +24 -24
  100. package/themes/mist.css +166 -166
  101. package/themes/nord.css +107 -107
  102. package/themes/one-dark.css +106 -106
  103. package/themes/paper.css +174 -174
  104. package/themes/rose-pine-dawn.css +114 -114
  105. package/themes/sakura.css +166 -166
  106. package/themes/solarized-light.css +114 -114
  107. package/themes/tokyo-night.css +115 -115
  108. package/themes/translucent.css +85 -85
  109. package/themes/transparent.css +116 -116
  110. package/themes/vs-code-dark.css +147 -147
  111. package/themes/wallpaper-flow.css +382 -382
  112. package/themes/wallpaper-obsidian.css +74 -74
  113. package/themes/white.css +164 -164
  114. package/themes/zhujian-dark.css +115 -115
  115. package/themes/zhujian.css +114 -114
  116. package/themes/zhupi-dark.css +115 -115
  117. package/themes/zhupi.css +114 -114
  118. package/web/dist/.build-assets.json +1 -1
  119. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  120. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  121. package/web/dist/assets/{CanvasStudio-BEJZE5BI.js → CanvasStudio-PI9pid0Y.js} +3 -3
  122. package/web/dist/assets/{CanvasStudio-CgUNHqos.js → CanvasStudio-nf5-HxLM.js} +3 -3
  123. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  124. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  125. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  126. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  127. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  128. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  129. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  130. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  131. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  132. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  133. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  134. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  135. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  136. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  137. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  138. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  139. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  140. package/web/dist/assets/{TerminalPanel-DL20uKgU.js → TerminalPanel-BBuM_Sez.js} +2 -2
  141. package/web/dist/assets/{TerminalPanel-D6cPRFei.js → TerminalPanel-D6x6xz8Q.js} +2 -2
  142. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  143. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  144. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  145. package/web/dist/assets/{desktop-DPyTy4M3.js → desktop-YguLbrX1.js} +1 -1
  146. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  147. package/web/dist/assets/index-BPvpea8t.js +85 -0
  148. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  149. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  150. package/web/dist/assets/{plugin-host-CqA4yW6w.js → plugin-host-BRBg6zmQ.js} +1 -1
  151. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  152. package/web/dist/index.html +37 -36
  153. package/web/dist/sw.js +179 -179
  154. package/web/public/sw.js +179 -179
  155. package/dist/gh-comment-781.md +0 -5
  156. package/dist/server/device-center/local-page.js +0 -17
  157. package/dist/server/device-center/smoke-preview.js +0 -3
  158. package/dist/server/durable/durable-capabilities.js +0 -11
  159. package/dist/server/markers/builtins/services.js +0 -123
  160. package/dist/server/markers/builtins/todo.js +0 -189
  161. package/dist/server/markers-list-tool.js +0 -34
  162. package/dist/server/orchestrator.js +0 -109
  163. package/dist/server/system-prompt-soul.js +0 -41
  164. package/dist/server/univer-service.js +0 -448
  165. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  166. package/dist/test-artifact.md +0 -9
  167. package/dist/test-preview-modal.md +0 -11
  168. package/dist/test-report.html +0 -20
  169. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +0 -1
  170. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +0 -1
  171. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +0 -3
  172. package/web/dist/assets/DeviceCenter-CVblvhNX.js +0 -3
  173. package/web/dist/assets/Dropdown-Oug0DDte.js +0 -1
  174. package/web/dist/assets/FilePreview-CvdX6nr6.js +0 -2
  175. package/web/dist/assets/FilePreview-kCZhfBAF.js +0 -2
  176. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +0 -1
  177. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +0 -1
  178. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +0 -1
  179. package/web/dist/assets/GroupConversation-DZ71jEi8.js +0 -1
  180. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +0 -2
  181. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +0 -1
  182. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +0 -1
  183. package/web/dist/assets/SCMPanel-BP1TUT-V.js +0 -2
  184. package/web/dist/assets/SCMPanel-BscPm9kf.js +0 -2
  185. package/web/dist/assets/SettingsModal-C8UgMjVM.js +0 -20
  186. package/web/dist/assets/SettingsModal-VynB7jNb.js +0 -20
  187. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +0 -1
  188. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +0 -1
  189. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +0 -1
  190. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +0 -1
  191. package/web/dist/assets/app-globals-CnO6KlEM.js +0 -325
  192. package/web/dist/assets/index-CPgAH5q7.js +0 -83
  193. package/web/dist/assets/index-Cje8iugL.js +0 -83
  194. package/web/dist/assets/index-DnKeiDbj.css +0 -1
  195. package/web/dist/assets/theme-BqdAjEjF.js +0 -1
@@ -1,335 +1,335 @@
1
- /**
2
- * pi-web-ui 的 pi 扩展 —— 提供命令行集成。
3
- *
4
- * 能力:
5
- * /webui 启动本机 pi-web-ui 服务器,打开浏览器访问
6
- * /webui --port 9000 指定端口启动
7
- * /webui --no-browser 启动但不开浏览器
8
- * /webui stop 停止已启动的服务器
9
- * /webui status 查看运行状态 / URL
10
- *
11
- * 实现说明:
12
- * - 不依赖全局 bin(pi install 后 pi-web-ui 命令不一定在 PATH),直接用
13
- * node 调包内 dist/server/index.js,通过环境变量 PORT / PI_WEB_CWD /
14
- * PI_WEB_DATA_DIR 控制。
15
- * - 工作目录默认用当前 pi 会话的 ctx.cwd;可用 --cwd / path 覆盖。
16
- * - 服务器作为子进程后台运行,/webui 不阻塞 pi。
17
- * - 每个 pi 会话管理一个子进程;session_shutdown 时清理,避免孤儿进程。
18
- */
19
-
20
- import { spawn, execSync } from "node:child_process";
21
- import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
22
- import { homedir } from "node:os";
23
- import { dirname, join, resolve } from "node:path";
24
- import { fileURLToPath, pathToFileURL } from "node:url";
25
- import net from "node:net";
26
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
27
-
28
- // 本文件位于 <pkg>/extensions/webui.ts → 包根在上一级
29
- const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
30
- const SERVER_ENTRY = join(PKG_ROOT, "dist", "server", "index.js");
31
-
32
- /**
33
- * 解析真实的 node 可执行路径。
34
- *
35
- * pi 0.87+ 的 TUI 版本是 Bun 打包的二进制(pi.exe),此时 process.execPath 指向
36
- * pi.exe 而非 node。用 pi.exe 去 spawn(index.js) 会静默失败(pi.exe 不能当
37
- * node 执行脚本)。此函数在 Bun 环境或 execPath 非 node 时,从 PATH 和常见安装
38
- * 位置回退查找真实 node。
39
- */
40
- function resolveNode(): string {
41
- const base = process.execPath.toLowerCase();
42
- // 普通 node 直接返回(未被 Bun 接管)
43
- if (!(process as any).isBun && /(^|[/\\])(node|nodejs)(\.exe)?$/.test(base)) {
44
- return process.execPath;
45
- }
46
-
47
- const candidates: string[] = [];
48
- // 1. 从 PATH 里找(跨平台:Windows 用 where,其余用 which)
49
- try {
50
- const cmd = process.platform === "win32" ? "where node" : "which node";
51
- const out = execSync(cmd, { windowsHide: true }).toString().trim();
52
- for (const line of out.split(/\r?\n/)) {
53
- const p = line.trim();
54
- // 过滤掉 pi 自身
55
- if (p && !/pi[/\\]pi(\.exe)?$/i.test(p)) candidates.push(p);
56
- }
57
- } catch {
58
- /* node 不在 PATH */
59
- }
60
-
61
- // 2. 常见安装位置兜底(Windows 为主,也兼顾 Unix)
62
- const home = homedir();
63
- const extra: string[] = [];
64
- if (process.env.PNPM_HOME) extra.push(join(process.env.PNPM_HOME, "node.exe"));
65
- for (const rel of [
66
- "scoop/apps/nodejs/current/node.exe",
67
- "AppData/Roaming/nvm/current/node.exe",
68
- ".nvm/versions/node/current/bin/node",
69
- ".local/share/pnpm/node.exe",
70
- ".local/bin/node",
71
- ]) {
72
- extra.push(join(home, ...rel.split("/")));
73
- }
74
- for (const c of extra) {
75
- if (existsSync(c) && !/pi[/\\]pi(\.exe)?$/i.test(c)) candidates.push(c);
76
- }
77
-
78
- if (candidates.length > 0) return candidates[0];
79
-
80
- console.warn(
81
- "[webui] 未找到真实 node(当前 process.execPath 指向非 node 进程,疑似 Bun 环境)。" +
82
- "将退回 process.execPath,子进程可能无法启动。请确保 node 在 PATH 中。",
83
- );
84
- return process.execPath;
85
- }
86
-
87
- const NODE = resolveNode();
88
-
89
- /** 每个会话的服务器子进程 + 元数据 */
90
- interface RunningServer {
91
- proc: ReturnType<typeof spawn>;
92
- port: number;
93
- cwd: string;
94
- url: string;
95
- logFile?: string;
96
- stop: () => void;
97
- }
98
-
99
- // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
100
- const running = new Map<string, RunningServer>();
101
-
102
- /**
103
- * 组装子进程参数。
104
- * hookPath(resolve-global-sdk.js)必须以 file:// URL 形式传给 --import,
105
- * 否则在 Windows 上传裸盘符路径(如 C:\...)会触发 Node ESM 的 ERR_UNSUPPORTED_ESM_URL_SCHEME 异常(issue #420 / #580)。
106
- */
107
- export function buildNodeArgs(
108
- entry: string,
109
- hookPath?: string,
110
- hookExists = hookPath ? existsSync(hookPath) : false,
111
- ): string[] {
112
- return hookPath && hookExists ? ["--import", pathToFileURL(hookPath).href, entry] : [entry];
113
- }
114
-
115
- export { running };
116
-
117
- /** 找一个空闲端口 */
118
- function findFreePort(from = 8787): Promise<number> {
119
- return new Promise((resolve_, reject) => {
120
- const srv = net.createServer();
121
- srv.listen(from, () => {
122
- const port = (srv.address() as net.AddressInfo).port;
123
- srv.close(() => resolve_(port));
124
- });
125
- srv.on("error", () => {
126
- // 端口被占则顺延
127
- findFreePort(from + 1).then(resolve_, reject);
128
- });
129
- });
130
- }
131
-
132
- /** 解析 --key value / --flag 参数 */
133
- function parseArgs(args: string): { port?: number; cwd?: string; noBrowser: boolean } {
134
- const out: { port?: number; cwd?: string; noBrowser: boolean } = { noBrowser: false };
135
- const toks = args.split(/\s+/).filter(Boolean);
136
- for (let i = 0; i < toks.length; i++) {
137
- const t = toks[i];
138
- if ((t === "--port" || t === "-p") && toks[i + 1]) {
139
- const n = Number(toks[++i]);
140
- if (Number.isInteger(n) && n > 0 && n < 65536) out.port = n;
141
- } else if (t === "--cwd" && toks[i + 1]) {
142
- out.cwd = resolve(toks[++i]);
143
- } else if (t === "--no-browser") {
144
- out.noBrowser = true;
145
- }
146
- }
147
- return out;
148
- }
149
-
150
- /** 打开浏览器 */
151
- async function openBrowser(url: string): Promise<void> {
152
- const { platform } = process;
153
- const [cmd, ...rest] =
154
- platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
155
- // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
156
- // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
157
- // Windows 下 detached 子进程会新建控制台闪窗;改为不 detached 并 windowsHide。
158
- spawn(cmd, rest, { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true })
159
- .on("error", (err) => {
160
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
161
- console.warn(
162
- `[webui] 未找到浏览器打开器 (${(err as NodeJS.ErrnoException).path || "command not found"}),请用 --no-browser 关闭自动打开`,
163
- );
164
- } else {
165
- console.warn("[webui] 打开浏览器失败:", err.message);
166
- }
167
- })
168
- .unref();
169
- }
170
-
171
- export default function (pi: ExtensionAPI): void {
172
- pi.registerCommand("webui", {
173
- description: "启动本机 pi-web-ui Web 界面(/webui [--port N] [--cwd PATH] [--no-browser] | stop | status)",
174
- handler: async (args: string, ctx: ExtensionCommandContext) => {
175
- const sid = ctx.sessionManager.getSessionId();
176
- const opts = parseArgs(args);
177
- const action = (args.split(/\s+/)[0] || "start").toLowerCase();
178
-
179
- // 停止
180
- if (action === "stop" || action === "kill") {
181
- const inst = running.get(sid);
182
- const alive = inst && inst.proc.exitCode === null && inst.proc.signalCode === null;
183
- if (!inst || !alive) {
184
- running.delete(sid);
185
- ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
186
- return;
187
- }
188
- inst.stop();
189
- running.delete(sid);
190
- ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
191
- return;
192
- }
193
-
194
- // 状态
195
- if (action === "status") {
196
- const inst = running.get(sid);
197
- if (!inst) {
198
- ctx.ui.notify("本机 pi-web-ui 未运行", "info");
199
- return;
200
- }
201
- const alive = inst.proc.exitCode === null && inst.proc.signalCode === null;
202
- if (alive) {
203
- ctx.ui.notify(
204
- `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}${inst.logFile ? `\n日志: ${inst.logFile}` : ""}`,
205
- "info",
206
- );
207
- } else {
208
- const exit =
209
- inst.proc.exitCode !== null
210
- ? `exit=${inst.proc.exitCode}`
211
- : inst.proc.signalCode
212
- ? `signal=${inst.proc.signalCode}`
213
- : "unknown";
214
- ctx.ui.notify(`pi-web-ui 已退出 (${exit})${inst.logFile ? ` · 日志: ${inst.logFile}` : ""}`, "warning");
215
- }
216
- return;
217
- }
218
-
219
- // 默认 start
220
- if (action !== "start" && action !== "run") {
221
- ctx.ui.notify(`未知动作 ${action}(可用 start|stop|status)`, "warning");
222
- return;
223
- }
224
-
225
- // 已运行则提示
226
- const existing = running.get(sid);
227
- if (existing && existing.proc.exitCode === null && existing.proc.signalCode === null) {
228
- ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
229
- return;
230
- }
231
-
232
- // 检查是否已构建
233
- if (!existsSync(SERVER_ENTRY)) {
234
- ctx.ui.notify(
235
- "缺少 dist/ 产物(当前安装未包含已构建前端)。请运行 `npm run build` 后重试,或用 pi-web-ui 官方 npm 包。",
236
- "warning",
237
- );
238
- return;
239
- }
240
-
241
- const port = opts.port ?? (await findFreePort());
242
- const cwd = opts.cwd ?? ctx.cwd;
243
- const url = `http://localhost:${port}`;
244
-
245
- // 探测并向子进程显式透传宿主 Pi SDK 路径(issue #482)
246
- let hostSdkDir: string | undefined;
247
- try {
248
- const resolved = import.meta.resolve?.("@earendil-works/pi-coding-agent");
249
- if (resolved) {
250
- let p = resolved.startsWith("file:") ? fileURLToPath(resolved) : resolved;
251
- if (p.endsWith("index.js") || p.endsWith("index.mjs")) p = dirname(p);
252
- if (existsSync(join(p, "package.json"))) hostSdkDir = p;
253
- }
254
- } catch {}
255
-
256
- const dataDir = process.env.PI_WEB_DATA_DIR ? resolve(process.env.PI_WEB_DATA_DIR) : join(cwd, ".pi-web");
257
- const env = {
258
- ...process.env,
259
- PORT: String(port),
260
- PI_WEB_PORT: String(port), // server/index.js 读取 PI_WEB_PORT
261
- PI_WEB_CWD: cwd,
262
- ...(hostSdkDir ? { PI_WEB_SDK_DIR: hostSdkDir } : {}),
263
- PI_WEB_DATA_DIR: dataDir,
264
- };
265
- const hookPath = join(PKG_ROOT, "dist", "server", "resolve-global-sdk.js");
266
- const nodeArgs = buildNodeArgs(SERVER_ENTRY, hookPath);
267
-
268
- let logFile: string | undefined;
269
- let logFd: number | "ignore" = "ignore";
270
- try {
271
- mkdirSync(dataDir, { recursive: true });
272
- logFile = join(dataDir, "webui.log");
273
- logFd = openSync(logFile, "a");
274
- } catch {
275
- /* 无法创建日志目录或文件时静默回退 ignore */
276
- }
277
-
278
- const proc = spawn(NODE, nodeArgs, {
279
- cwd,
280
- env,
281
- stdio: ["ignore", logFd, logFd],
282
- detached: process.platform !== "win32",
283
- windowsHide: true,
284
- });
285
- if (typeof logFd === "number") {
286
- try {
287
- closeSync(logFd);
288
- } catch {}
289
- }
290
- proc.unref();
291
-
292
- let stoppedManually = false;
293
- const startTime = Date.now();
294
- const inst: RunningServer = {
295
- proc,
296
- port,
297
- cwd,
298
- url,
299
- logFile,
300
- stop: () => {
301
- stoppedManually = true;
302
- proc.kill("SIGTERM");
303
- },
304
- };
305
- running.set(sid, inst);
306
-
307
- proc.on("error", (err) => {
308
- ctx.ui.notify(`pi-web-ui 启动失败: ${err.message}${logFile ? `\n日志: ${logFile}` : ""}`, "error");
309
- });
310
-
311
- proc.on("exit", (code, signal) => {
312
- const duration = Date.now() - startTime;
313
- // 启动后 15 秒内非手动停止的异常退出,向用户告警
314
- if (!stoppedManually && (code !== 0 || signal !== null) && duration < 15000) {
315
- const reason = code !== null ? `exit=${code}` : `signal=${signal}`;
316
- ctx.ui.notify(`pi-web-ui 启动异常退出 (${reason})。\n${logFile ? `查看日志: ${logFile}` : ""}`, "error");
317
- }
318
- });
319
-
320
- ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
321
-
322
- if (!opts.noBrowser) await openBrowser(url);
323
- },
324
- });
325
-
326
- // 会话结束清理子进程,避免孤儿
327
- pi.on("session_shutdown", async (_event, ctx) => {
328
- const sid = ctx.sessionManager.getSessionId();
329
- const inst = running.get(sid);
330
- if (inst && inst.proc.exitCode === null && inst.proc.signalCode === null) {
331
- inst.stop();
332
- }
333
- running.delete(sid);
334
- });
335
- }
1
+ /**
2
+ * pi-web-ui 的 pi 扩展 —— 提供命令行集成。
3
+ *
4
+ * 能力:
5
+ * /webui 启动本机 pi-web-ui 服务器,打开浏览器访问
6
+ * /webui --port 9000 指定端口启动
7
+ * /webui --no-browser 启动但不开浏览器
8
+ * /webui stop 停止已启动的服务器
9
+ * /webui status 查看运行状态 / URL
10
+ *
11
+ * 实现说明:
12
+ * - 不依赖全局 bin(pi install 后 pi-web-ui 命令不一定在 PATH),直接用
13
+ * node 调包内 dist/server/index.js,通过环境变量 PORT / PI_WEB_CWD /
14
+ * PI_WEB_DATA_DIR 控制。
15
+ * - 工作目录默认用当前 pi 会话的 ctx.cwd;可用 --cwd / path 覆盖。
16
+ * - 服务器作为子进程后台运行,/webui 不阻塞 pi。
17
+ * - 每个 pi 会话管理一个子进程;session_shutdown 时清理,避免孤儿进程。
18
+ */
19
+
20
+ import { spawn, execSync } from "node:child_process";
21
+ import { closeSync, existsSync, mkdirSync, openSync } from "node:fs";
22
+ import { homedir } from "node:os";
23
+ import { dirname, join, resolve } from "node:path";
24
+ import { fileURLToPath, pathToFileURL } from "node:url";
25
+ import net from "node:net";
26
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
27
+
28
+ // 本文件位于 <pkg>/extensions/webui.ts → 包根在上一级
29
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
30
+ const SERVER_ENTRY = join(PKG_ROOT, "dist", "server", "index.js");
31
+
32
+ /**
33
+ * 解析真实的 node 可执行路径。
34
+ *
35
+ * pi 0.87+ 的 TUI 版本是 Bun 打包的二进制(pi.exe),此时 process.execPath 指向
36
+ * pi.exe 而非 node。用 pi.exe 去 spawn(index.js) 会静默失败(pi.exe 不能当
37
+ * node 执行脚本)。此函数在 Bun 环境或 execPath 非 node 时,从 PATH 和常见安装
38
+ * 位置回退查找真实 node。
39
+ */
40
+ function resolveNode(): string {
41
+ const base = process.execPath.toLowerCase();
42
+ // 普通 node 直接返回(未被 Bun 接管)
43
+ if (!(process as any).isBun && /(^|[/\\])(node|nodejs)(\.exe)?$/.test(base)) {
44
+ return process.execPath;
45
+ }
46
+
47
+ const candidates: string[] = [];
48
+ // 1. 从 PATH 里找(跨平台:Windows 用 where,其余用 which)
49
+ try {
50
+ const cmd = process.platform === "win32" ? "where node" : "which node";
51
+ const out = execSync(cmd, { windowsHide: true }).toString().trim();
52
+ for (const line of out.split(/\r?\n/)) {
53
+ const p = line.trim();
54
+ // 过滤掉 pi 自身
55
+ if (p && !/pi[/\\]pi(\.exe)?$/i.test(p)) candidates.push(p);
56
+ }
57
+ } catch {
58
+ /* node 不在 PATH */
59
+ }
60
+
61
+ // 2. 常见安装位置兜底(Windows 为主,也兼顾 Unix)
62
+ const home = homedir();
63
+ const extra: string[] = [];
64
+ if (process.env.PNPM_HOME) extra.push(join(process.env.PNPM_HOME, "node.exe"));
65
+ for (const rel of [
66
+ "scoop/apps/nodejs/current/node.exe",
67
+ "AppData/Roaming/nvm/current/node.exe",
68
+ ".nvm/versions/node/current/bin/node",
69
+ ".local/share/pnpm/node.exe",
70
+ ".local/bin/node",
71
+ ]) {
72
+ extra.push(join(home, ...rel.split("/")));
73
+ }
74
+ for (const c of extra) {
75
+ if (existsSync(c) && !/pi[/\\]pi(\.exe)?$/i.test(c)) candidates.push(c);
76
+ }
77
+
78
+ if (candidates.length > 0) return candidates[0];
79
+
80
+ console.warn(
81
+ "[webui] 未找到真实 node(当前 process.execPath 指向非 node 进程,疑似 Bun 环境)。" +
82
+ "将退回 process.execPath,子进程可能无法启动。请确保 node 在 PATH 中。",
83
+ );
84
+ return process.execPath;
85
+ }
86
+
87
+ const NODE = resolveNode();
88
+
89
+ /** 每个会话的服务器子进程 + 元数据 */
90
+ interface RunningServer {
91
+ proc: ReturnType<typeof spawn>;
92
+ port: number;
93
+ cwd: string;
94
+ url: string;
95
+ logFile?: string;
96
+ stop: () => void;
97
+ }
98
+
99
+ // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
100
+ const running = new Map<string, RunningServer>();
101
+
102
+ /**
103
+ * 组装子进程参数。
104
+ * hookPath(resolve-global-sdk.js)必须以 file:// URL 形式传给 --import,
105
+ * 否则在 Windows 上传裸盘符路径(如 C:\...)会触发 Node ESM 的 ERR_UNSUPPORTED_ESM_URL_SCHEME 异常(issue #420 / #580)。
106
+ */
107
+ export function buildNodeArgs(
108
+ entry: string,
109
+ hookPath?: string,
110
+ hookExists = hookPath ? existsSync(hookPath) : false,
111
+ ): string[] {
112
+ return hookPath && hookExists ? ["--import", pathToFileURL(hookPath).href, entry] : [entry];
113
+ }
114
+
115
+ export { running };
116
+
117
+ /** 找一个空闲端口 */
118
+ function findFreePort(from = 8787): Promise<number> {
119
+ return new Promise((resolve_, reject) => {
120
+ const srv = net.createServer();
121
+ srv.listen(from, () => {
122
+ const port = (srv.address() as net.AddressInfo).port;
123
+ srv.close(() => resolve_(port));
124
+ });
125
+ srv.on("error", () => {
126
+ // 端口被占则顺延
127
+ findFreePort(from + 1).then(resolve_, reject);
128
+ });
129
+ });
130
+ }
131
+
132
+ /** 解析 --key value / --flag 参数 */
133
+ function parseArgs(args: string): { port?: number; cwd?: string; noBrowser: boolean } {
134
+ const out: { port?: number; cwd?: string; noBrowser: boolean } = { noBrowser: false };
135
+ const toks = args.split(/\s+/).filter(Boolean);
136
+ for (let i = 0; i < toks.length; i++) {
137
+ const t = toks[i];
138
+ if ((t === "--port" || t === "-p") && toks[i + 1]) {
139
+ const n = Number(toks[++i]);
140
+ if (Number.isInteger(n) && n > 0 && n < 65536) out.port = n;
141
+ } else if (t === "--cwd" && toks[i + 1]) {
142
+ out.cwd = resolve(toks[++i]);
143
+ } else if (t === "--no-browser") {
144
+ out.noBrowser = true;
145
+ }
146
+ }
147
+ return out;
148
+ }
149
+
150
+ /** 打开浏览器 */
151
+ async function openBrowser(url: string): Promise<void> {
152
+ const { platform } = process;
153
+ const [cmd, ...rest] =
154
+ platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
155
+ // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
156
+ // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
157
+ // Windows 下 detached 子进程会新建控制台闪窗;改为不 detached 并 windowsHide。
158
+ spawn(cmd, rest, { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true })
159
+ .on("error", (err) => {
160
+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
161
+ console.warn(
162
+ `[webui] 未找到浏览器打开器 (${(err as NodeJS.ErrnoException).path || "command not found"}),请用 --no-browser 关闭自动打开`,
163
+ );
164
+ } else {
165
+ console.warn("[webui] 打开浏览器失败:", err.message);
166
+ }
167
+ })
168
+ .unref();
169
+ }
170
+
171
+ export default function (pi: ExtensionAPI): void {
172
+ pi.registerCommand("webui", {
173
+ description: "启动本机 pi-web-ui Web 界面(/webui [--port N] [--cwd PATH] [--no-browser] | stop | status)",
174
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
175
+ const sid = ctx.sessionManager.getSessionId();
176
+ const opts = parseArgs(args);
177
+ const action = (args.split(/\s+/)[0] || "start").toLowerCase();
178
+
179
+ // 停止
180
+ if (action === "stop" || action === "kill") {
181
+ const inst = running.get(sid);
182
+ const alive = inst && inst.proc.exitCode === null && inst.proc.signalCode === null;
183
+ if (!inst || !alive) {
184
+ running.delete(sid);
185
+ ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
186
+ return;
187
+ }
188
+ inst.stop();
189
+ running.delete(sid);
190
+ ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
191
+ return;
192
+ }
193
+
194
+ // 状态
195
+ if (action === "status") {
196
+ const inst = running.get(sid);
197
+ if (!inst) {
198
+ ctx.ui.notify("本机 pi-web-ui 未运行", "info");
199
+ return;
200
+ }
201
+ const alive = inst.proc.exitCode === null && inst.proc.signalCode === null;
202
+ if (alive) {
203
+ ctx.ui.notify(
204
+ `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}${inst.logFile ? `\n日志: ${inst.logFile}` : ""}`,
205
+ "info",
206
+ );
207
+ } else {
208
+ const exit =
209
+ inst.proc.exitCode !== null
210
+ ? `exit=${inst.proc.exitCode}`
211
+ : inst.proc.signalCode
212
+ ? `signal=${inst.proc.signalCode}`
213
+ : "unknown";
214
+ ctx.ui.notify(`pi-web-ui 已退出 (${exit})${inst.logFile ? ` · 日志: ${inst.logFile}` : ""}`, "warning");
215
+ }
216
+ return;
217
+ }
218
+
219
+ // 默认 start
220
+ if (action !== "start" && action !== "run") {
221
+ ctx.ui.notify(`未知动作 ${action}(可用 start|stop|status)`, "warning");
222
+ return;
223
+ }
224
+
225
+ // 已运行则提示
226
+ const existing = running.get(sid);
227
+ if (existing && existing.proc.exitCode === null && existing.proc.signalCode === null) {
228
+ ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
229
+ return;
230
+ }
231
+
232
+ // 检查是否已构建
233
+ if (!existsSync(SERVER_ENTRY)) {
234
+ ctx.ui.notify(
235
+ "缺少 dist/ 产物(当前安装未包含已构建前端)。请运行 `npm run build` 后重试,或用 pi-web-ui 官方 npm 包。",
236
+ "warning",
237
+ );
238
+ return;
239
+ }
240
+
241
+ const port = opts.port ?? (await findFreePort());
242
+ const cwd = opts.cwd ?? ctx.cwd;
243
+ const url = `http://localhost:${port}`;
244
+
245
+ // 探测并向子进程显式透传宿主 Pi SDK 路径(issue #482)
246
+ let hostSdkDir: string | undefined;
247
+ try {
248
+ const resolved = import.meta.resolve?.("@earendil-works/pi-coding-agent");
249
+ if (resolved) {
250
+ let p = resolved.startsWith("file:") ? fileURLToPath(resolved) : resolved;
251
+ if (p.endsWith("index.js") || p.endsWith("index.mjs")) p = dirname(p);
252
+ if (existsSync(join(p, "package.json"))) hostSdkDir = p;
253
+ }
254
+ } catch {}
255
+
256
+ const dataDir = process.env.PI_WEB_DATA_DIR ? resolve(process.env.PI_WEB_DATA_DIR) : join(cwd, ".pi-web");
257
+ const env = {
258
+ ...process.env,
259
+ PORT: String(port),
260
+ PI_WEB_PORT: String(port), // server/index.js 读取 PI_WEB_PORT
261
+ PI_WEB_CWD: cwd,
262
+ ...(hostSdkDir ? { PI_WEB_SDK_DIR: hostSdkDir } : {}),
263
+ PI_WEB_DATA_DIR: dataDir,
264
+ };
265
+ const hookPath = join(PKG_ROOT, "dist", "server", "resolve-global-sdk.js");
266
+ const nodeArgs = buildNodeArgs(SERVER_ENTRY, hookPath);
267
+
268
+ let logFile: string | undefined;
269
+ let logFd: number | "ignore" = "ignore";
270
+ try {
271
+ mkdirSync(dataDir, { recursive: true });
272
+ logFile = join(dataDir, "webui.log");
273
+ logFd = openSync(logFile, "a");
274
+ } catch {
275
+ /* 无法创建日志目录或文件时静默回退 ignore */
276
+ }
277
+
278
+ const proc = spawn(NODE, nodeArgs, {
279
+ cwd,
280
+ env,
281
+ stdio: ["ignore", logFd, logFd],
282
+ detached: process.platform !== "win32",
283
+ windowsHide: true,
284
+ });
285
+ if (typeof logFd === "number") {
286
+ try {
287
+ closeSync(logFd);
288
+ } catch {}
289
+ }
290
+ proc.unref();
291
+
292
+ let stoppedManually = false;
293
+ const startTime = Date.now();
294
+ const inst: RunningServer = {
295
+ proc,
296
+ port,
297
+ cwd,
298
+ url,
299
+ logFile,
300
+ stop: () => {
301
+ stoppedManually = true;
302
+ proc.kill("SIGTERM");
303
+ },
304
+ };
305
+ running.set(sid, inst);
306
+
307
+ proc.on("error", (err) => {
308
+ ctx.ui.notify(`pi-web-ui 启动失败: ${err.message}${logFile ? `\n日志: ${logFile}` : ""}`, "error");
309
+ });
310
+
311
+ proc.on("exit", (code, signal) => {
312
+ const duration = Date.now() - startTime;
313
+ // 启动后 15 秒内非手动停止的异常退出,向用户告警
314
+ if (!stoppedManually && (code !== 0 || signal !== null) && duration < 15000) {
315
+ const reason = code !== null ? `exit=${code}` : `signal=${signal}`;
316
+ ctx.ui.notify(`pi-web-ui 启动异常退出 (${reason})。\n${logFile ? `查看日志: ${logFile}` : ""}`, "error");
317
+ }
318
+ });
319
+
320
+ ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
321
+
322
+ if (!opts.noBrowser) await openBrowser(url);
323
+ },
324
+ });
325
+
326
+ // 会话结束清理子进程,避免孤儿
327
+ pi.on("session_shutdown", async (_event, ctx) => {
328
+ const sid = ctx.sessionManager.getSessionId();
329
+ const inst = running.get(sid);
330
+ if (inst && inst.proc.exitCode === null && inst.proc.signalCode === null) {
331
+ inst.stop();
332
+ }
333
+ running.delete(sid);
334
+ });
335
+ }