pi-web-ui 0.64.0 → 0.64.2

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 (45) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +504 -504
  3. package/README.zh-CN.md +427 -427
  4. package/bin/pi-web-ui.mjs +1809 -1809
  5. package/deploy/com.xingshuyin.pi-web-ui.plist +48 -48
  6. package/deploy/nginx-subpath.conf +88 -88
  7. package/deploy/pi-web-ui-task.xml +54 -54
  8. package/deploy/pi-web-ui.service +31 -31
  9. package/dist/server/agent-service.js +45 -22
  10. package/dist/server/attachments.js +16 -11
  11. package/dist/server/dsh/dsh-agent-service.js +27 -7
  12. package/dist/server/dsh/runtime/cordis.yml +1 -1
  13. package/dist/server/dsh/runtime/goal-rpc.mjs +645 -645
  14. package/dist/server/dsh/runtime/launcher.mjs +164 -164
  15. package/dist/server/dsh/runtime/override.patch.yml +71 -71
  16. package/dist/server/dsh/runtime/runtime-root.mjs +86 -86
  17. package/dist/server/files-service.js +235 -43
  18. package/dist/server/goal-service.js +4 -1
  19. package/dist/server/index.js +48 -13
  20. package/dist/server/marker-service.js +8 -3
  21. package/dist/server/markers/builtins/rename.js +3 -3
  22. package/dist/server/model-admin.js +12 -6
  23. package/dist/server/plugins.js +4 -4
  24. package/dist/server/slash-commands.js +3 -0
  25. package/dist/server/terminals.js +25 -15
  26. package/dist/server/vision-bridge.js +9 -9
  27. package/dist/server/webui-context.js +2 -2
  28. package/extensions/webui.ts +190 -190
  29. package/package.json +109 -109
  30. package/themes/cyberpunk.css +81 -81
  31. package/themes/dazzle.css +81 -81
  32. package/themes/md-preview.css +98 -98
  33. package/themes/white.css +160 -160
  34. package/web/dist/assets/TerminalPanel-BXISCcrQ.js +6 -0
  35. package/web/dist/assets/index-BxuvIAJQ.js +326 -0
  36. package/web/dist/assets/{index-CMgDryBL.css → index-DVnuQrK5.css} +1 -1
  37. package/web/dist/favicon.svg +8 -8
  38. package/web/dist/index.html +21 -21
  39. package/web/dist/manifest.webmanifest +50 -50
  40. package/web/dist/sw.js +126 -126
  41. package/web/public/favicon.svg +8 -8
  42. package/web/public/manifest.webmanifest +50 -50
  43. package/web/public/sw.js +126 -126
  44. package/web/dist/assets/TerminalPanel-DNkAT34Z.js +0 -2
  45. package/web/dist/assets/index-_1vyEugI.js +0 -326
@@ -47,8 +47,8 @@ export function resolveCommandCwd(cwd, pwd) {
47
47
  /** Read the command list; missing file → empty list; malformed → empty list + warning text. */
48
48
  export async function loadCommands(workspaceRoot) {
49
49
  const path = commandsFilePath(workspaceRoot);
50
- const { commands, warning } = await readCommandsFile(path);
51
- return { commands, path, warning };
50
+ const { commands, warning, warningEn } = await readCommandsFile(path);
51
+ return { commands, path, warning, warningEn };
52
52
  }
53
53
  async function readCommandsFile(path) {
54
54
  if (!existsSync(path))
@@ -61,6 +61,7 @@ async function readCommandsFile(path) {
61
61
  return {
62
62
  commands: [],
63
63
  warning: `读取命令文件失败:${err.message}`,
64
+ warningEn: `Failed to read commands file: ${err.message}`,
64
65
  };
65
66
  }
66
67
  let parsed;
@@ -68,7 +69,11 @@ async function readCommandsFile(path) {
68
69
  parsed = JSON.parse(raw);
69
70
  }
70
71
  catch {
71
- return { commands: [], warning: `命令文件不是有效 JSON:${path}` };
72
+ return {
73
+ commands: [],
74
+ warning: `命令文件不是有效 JSON:${path}`,
75
+ warningEn: `Commands file is not valid JSON: ${path}`,
76
+ };
72
77
  }
73
78
  if (Array.isArray(parsed)) {
74
79
  // Tolerate a bare array: [{name, command, cwd}]
@@ -92,7 +97,7 @@ async function readCommandsFile(path) {
92
97
  .map((c) => ({ name: c.name, command: c.command, cwd: c.cwd })),
93
98
  };
94
99
  }
95
- return { commands: [], warning: `命令文件格式不正确:${path}` };
100
+ return { commands: [], warning: `命令文件格式不正确:${path}`, warningEn: `Commands file has a bad format: ${path}` };
96
101
  }
97
102
  /** Persist the command list, creating .pi/ if needed. */
98
103
  export async function saveCommandsFile(workspaceRoot, commands) {
@@ -104,7 +109,11 @@ export async function saveCommandsFile(workspaceRoot, commands) {
104
109
  return { path };
105
110
  }
106
111
  catch (err) {
107
- return { path, error: `保存命令文件失败:${err.message}` };
112
+ return {
113
+ path,
114
+ error: `保存命令文件失败:${err.message}`,
115
+ errorEn: `Failed to save commands file: ${err.message}`,
116
+ };
108
117
  }
109
118
  }
110
119
  const isWindows = process.platform === "win32";
@@ -278,6 +287,7 @@ export function queryTerminalOutput(output, q, running = false, exitCode = null)
278
287
  .filter((l) => {
279
288
  const t = l.trim();
280
289
  return (!/^\[pi-exit:\d+\]$/.test(t) &&
290
+ !/^\[pi-term-exit:-?\d+\]$/.test(t) &&
281
291
  !t.startsWith("[进程已退出") &&
282
292
  !t.startsWith("[Process exited") &&
283
293
  !/^\[.*(已退出|exited)/.test(t));
@@ -1173,13 +1183,13 @@ export class TerminalManager {
1173
1183
  if (!entry || entry.exited)
1174
1184
  return;
1175
1185
  this.disarmIdleWatch(entry);
1176
- // Flush queued output BEFORE the exit banner so ordering is preserved.
1186
+ // Flush queued output BEFORE the exit marker so ordering is preserved.
1187
+ // Banner text is CLIENT-rendered (live locale); the stream carries only
1188
+ // a machine sentinel the client strips and replaces.
1177
1189
  this.flushPending(entry);
1178
- const banner = entry.locale === "en"
1179
- ? `\r\n\x1b[90m[Process exited with code ${exitCode}]\x1b[0m\r\n`
1180
- : `\r\n\x1b[90m[进程已退出,退出码 ${exitCode}]\x1b[0m\r\n`;
1181
- this.appendOutput(entry, banner);
1182
- this.emit({ type: "terminal_output", terminalId: id, data: banner });
1190
+ const marker = `\r\n[pi-term-exit:${exitCode}]\r\n`;
1191
+ this.appendOutput(entry, marker);
1192
+ this.emit({ type: "terminal_output", terminalId: id, data: marker });
1183
1193
  entry.exited = true;
1184
1194
  // 终端退出 → 未命中的输出观察器以 null 回调(宿主可据此通知「终端已关闭」)。
1185
1195
  const pendingWatches = entry.watches;
@@ -1532,10 +1542,10 @@ export const TERMINAL_TOOL_NAMES = [
1532
1542
  /** System-prompt guidance teaching the model WHEN to prefer the terminal tools
1533
1543
  * over one-shot bash. Without it models almost never pick them — bash returns
1534
1544
  * complete output in a single call, so it always wins on convenience. */
1535
- export const TERMINAL_TOOLS_GUIDANCE = `Persistent interactive terminal tools are available (terminal_create / terminal_list / terminal_close / terminal_input / terminal_key / terminal_read / terminal_wait). The bash tool stays the DEFAULT for ordinary commands - it runs in a visible terminal and returns the full output (persist=false, one-shot terminal that exits when the command finishes). Switch to the bash tool's persist=true, or to the terminal tools, when:
1536
- - The program is interactive or TUI-based (REPLs like python/node, vim/htop, installers asking y/n, anything waiting on stdin). For these, prefer bash({ persist: true }) which runs it in the persistent 'ai-bash' terminal and returns immediately; then drive it with terminal_input / terminal_key (and terminal_read) on terminalId='ai-bash'.
1537
- - You start a long-running server or watcher and want to keep watching its output (terminal_read with waitMs), send keys to it later (e.g. interrupt via terminal_key with Ctrl+c), or block until a backgrounded command finishes without polling (terminal_wait).
1538
- - The user explicitly asks you to work in the visible terminal panel.
1545
+ export const TERMINAL_TOOLS_GUIDANCE = `Persistent interactive terminal tools are available (terminal_create / terminal_list / terminal_close / terminal_input / terminal_key / terminal_read / terminal_wait). The bash tool stays the DEFAULT for ordinary commands - it runs in a visible terminal and returns the full output (persist=false, one-shot terminal that exits when the command finishes). Switch to the bash tool's persist=true, or to the terminal tools, when:
1546
+ - The program is interactive or TUI-based (REPLs like python/node, vim/htop, installers asking y/n, anything waiting on stdin). For these, prefer bash({ persist: true }) which runs it in the persistent 'ai-bash' terminal and returns immediately; then drive it with terminal_input / terminal_key (and terminal_read) on terminalId='ai-bash'.
1547
+ - You start a long-running server or watcher and want to keep watching its output (terminal_read with waitMs), send keys to it later (e.g. interrupt via terminal_key with Ctrl+c), or block until a backgrounded command finishes without polling (terminal_wait).
1548
+ - The user explicitly asks you to work in the visible terminal panel.
1539
1549
  Use head/tail on bash to trim verbose output instead of piping through head/tail. Liveness watchdog: terminals you touched (create/input/key) are monitored - if one goes silent with no new output while you are working (default 15s), an automatic system reminder is injected into the conversation. Treat it as a prompt to check that terminal (terminal_read), respond to an input prompt (terminal_input / terminal_key), or close it (terminal_close) if it is no longer needed.`;
1540
1550
  /** Build the agent-facing persistent terminal tools for one conversation. */
1541
1551
  export function makePersistentTerminalTools(terminals, cwd) {
@@ -35,15 +35,15 @@ export function findVisionModels(runtime) {
35
35
  * Exported so the settings panel can offer a custom prompt (append to this
36
36
  * default or replace it entirely).
37
37
  */
38
- export const SYSTEM_PROMPT = `You are a vision bridge for a text-only language model. You receive one or more images and must transcribe them into precise, structured text evidence so another model that cannot see images can answer questions about them accurately.
39
-
40
- Follow these rules:
41
- 1. Transcribe ALL visible text verbatim, preserving wording, spelling, punctuation and line breaks. This is the most important part — the reader relies on your transcription, not on the image.
42
- 2. Describe the layout in reading order: headers, paragraphs, lists, tables, buttons, panels — say what appears where.
43
- 3. For tables/charts/diagrams: read axes, scales (note log scale), legend entries, series names, highlighted points and their coordinates, and any data values you can discern.
44
- 4. Name entities: people, products, companies, colors, style, objects, actions.
45
- 5. If part of the image is too blurry/low-resolution to read, say "(读不清)" or "unclear" for that part — NEVER invent or guess content you cannot see.
46
- 6. If there are multiple images, address them in order (图 1 / Image 1, 图 2 / Image 2, ...).
38
+ export const SYSTEM_PROMPT = `You are a vision bridge for a text-only language model. You receive one or more images and must transcribe them into precise, structured text evidence so another model that cannot see images can answer questions about them accurately.
39
+
40
+ Follow these rules:
41
+ 1. Transcribe ALL visible text verbatim, preserving wording, spelling, punctuation and line breaks. This is the most important part — the reader relies on your transcription, not on the image.
42
+ 2. Describe the layout in reading order: headers, paragraphs, lists, tables, buttons, panels — say what appears where.
43
+ 3. For tables/charts/diagrams: read axes, scales (note log scale), legend entries, series names, highlighted points and their coordinates, and any data values you can discern.
44
+ 4. Name entities: people, products, companies, colors, style, objects, actions.
45
+ 5. If part of the image is too blurry/low-resolution to read, say "(读不清)" or "unclear" for that part — NEVER invent or guess content you cannot see.
46
+ 6. If there are multiple images, address them in order (图 1 / Image 1, 图 2 / Image 2, ...).
47
47
  7. Output only the transcript. No preamble, no commentary about the image itself.`;
48
48
  /**
49
49
  * Assemble the final vision-model system prompt from the settings-panel prefs.
@@ -115,8 +115,8 @@ export class WebUIContext {
115
115
  });
116
116
  }
117
117
  // -- notifications --------------------------------------------------------
118
- notify = (message, type) => {
119
- this.emit({ type: "notice", level: type ?? "info", text: message });
118
+ notify = (message, type, messageEn) => {
119
+ this.emit({ type: "notice", level: type ?? "info", text: message, textEn: messageEn });
120
120
  };
121
121
  // -- footer status (pi-lens "LSP Inactive", pi-cache-optimizer cache stats) --
122
122
  statuses = new Map();
@@ -1,190 +1,190 @@
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 } from "node:child_process";
21
- import { existsSync } from "node:fs";
22
- import { dirname, join, resolve } from "node:path";
23
- import { fileURLToPath } from "node:url";
24
- import net from "node:net";
25
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
26
-
27
- // 本文件位于 <pkg>/extensions/webui.ts → 包根在上一级
28
- const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
29
- const SERVER_ENTRY = join(PKG_ROOT, "dist", "server", "index.js");
30
- const NODE = process.execPath;
31
-
32
- /** 每个会话的服务器子进程 + 元数据 */
33
- interface RunningServer {
34
- proc: ReturnType<typeof spawn>;
35
- port: number;
36
- cwd: string;
37
- url: string;
38
- }
39
-
40
- // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
41
- const running = new Map<string, RunningServer>();
42
-
43
- /** 找一个空闲端口 */
44
- function findFreePort(from = 8787): Promise<number> {
45
- return new Promise((resolve_, reject) => {
46
- const srv = net.createServer();
47
- srv.listen(from, () => {
48
- const port = (srv.address() as net.AddressInfo).port;
49
- srv.close(() => resolve_(port));
50
- });
51
- srv.on("error", () => {
52
- // 端口被占则顺延
53
- findFreePort(from + 1).then(resolve_, reject);
54
- });
55
- });
56
- }
57
-
58
- /** 解析 --key value / --flag 参数 */
59
- function parseArgs(args: string): { port?: number; cwd?: string; noBrowser: boolean } {
60
- const out: { port?: number; cwd?: string; noBrowser: boolean } = { noBrowser: false };
61
- const toks = args.split(/\s+/).filter(Boolean);
62
- for (let i = 0; i < toks.length; i++) {
63
- const t = toks[i];
64
- if ((t === "--port" || t === "-p") && toks[i + 1]) {
65
- const n = Number(toks[++i]);
66
- if (Number.isInteger(n) && n > 0 && n < 65536) out.port = n;
67
- } else if (t === "--cwd" && toks[i + 1]) {
68
- out.cwd = resolve(toks[++i]);
69
- } else if (t === "--no-browser") {
70
- out.noBrowser = true;
71
- }
72
- }
73
- return out;
74
- }
75
-
76
- /** 打开浏览器 */
77
- async function openBrowser(url: string): Promise<void> {
78
- const { platform } = process;
79
- const [cmd, ...rest] =
80
- platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
81
- // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
82
- // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
83
- spawn(cmd, rest, { stdio: "ignore", detached: true })
84
- .on("error", (err) => {
85
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
86
- console.warn(
87
- `[webui] 未找到浏览器打开器 (${(err as NodeJS.ErrnoException).path || "command not found"}),请用 --no-browser 关闭自动打开`,
88
- );
89
- } else {
90
- console.warn("[webui] 打开浏览器失败:", err.message);
91
- }
92
- })
93
- .unref();
94
- }
95
-
96
- export default function (pi: ExtensionAPI): void {
97
- pi.registerCommand("webui", {
98
- description: "启动本机 pi-web-ui Web 界面(/webui [--port N] [--cwd PATH] [--no-browser] | stop | status)",
99
- handler: async (args: string, ctx: ExtensionCommandContext) => {
100
- const sid = ctx.sessionManager.getSessionId();
101
- const opts = parseArgs(args);
102
- const action = (args.split(/\s+/)[0] || "start").toLowerCase();
103
-
104
- // 停止
105
- if (action === "stop" || action === "kill") {
106
- const inst = running.get(sid);
107
- if (!inst) {
108
- ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
109
- return;
110
- }
111
- inst.proc.kill("SIGTERM");
112
- running.delete(sid);
113
- ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
114
- return;
115
- }
116
-
117
- // 状态
118
- if (action === "status") {
119
- const inst = running.get(sid);
120
- if (!inst) {
121
- ctx.ui.notify("本机 pi-web-ui 未运行", "info");
122
- return;
123
- }
124
- const alive = inst.proc.exitCode === null;
125
- ctx.ui.notify(
126
- alive
127
- ? `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}`
128
- : `已退出(exit=${inst.proc.exitCode})`,
129
- alive ? "info" : "warning",
130
- );
131
- return;
132
- }
133
-
134
- // 默认 start
135
- if (action !== "start" && action !== "run") {
136
- ctx.ui.notify(`未知动作 ${action}(可用 start|stop|status)`, "warning");
137
- return;
138
- }
139
-
140
- // 已运行则提示
141
- const existing = running.get(sid);
142
- if (existing && existing.proc.exitCode === null) {
143
- ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
144
- return;
145
- }
146
-
147
- // 检查是否已构建
148
- if (!existsSync(SERVER_ENTRY)) {
149
- ctx.ui.notify(
150
- "缺少 dist/ 产物(当前安装未包含已构建前端)。请运行 `npm run build` 后重试,或用 pi-web-ui 官方 npm 包。",
151
- "warning",
152
- );
153
- return;
154
- }
155
-
156
- const port = opts.port ?? (await findFreePort());
157
- const cwd = opts.cwd ?? ctx.cwd;
158
- const url = `http://localhost:${port}`;
159
-
160
- const env = {
161
- ...process.env,
162
- PORT: String(port),
163
- PI_WEB_CWD: cwd,
164
- ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
165
- };
166
- const proc = spawn(NODE, [SERVER_ENTRY], { cwd, env, stdio: "ignore", detached: true });
167
- proc.unref();
168
- running.set(sid, { proc, port, cwd, url });
169
-
170
- ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
171
-
172
- if (!opts.noBrowser) await openBrowser(url);
173
-
174
- // 进程退出时清理
175
- proc.on("exit", () => {
176
- if (running.get(sid)?.proc === proc) running.delete(sid);
177
- });
178
- },
179
- });
180
-
181
- // 会话结束清理子进程,避免孤儿
182
- pi.on("session_shutdown", async (_event, ctx) => {
183
- const sid = ctx.sessionManager.getSessionId();
184
- const inst = running.get(sid);
185
- if (inst && inst.proc.exitCode === null) {
186
- inst.proc.kill("SIGTERM");
187
- running.delete(sid);
188
- }
189
- });
190
- }
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 } from "node:child_process";
21
+ import { existsSync } from "node:fs";
22
+ import { dirname, join, resolve } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import net from "node:net";
25
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
26
+
27
+ // 本文件位于 <pkg>/extensions/webui.ts → 包根在上一级
28
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
29
+ const SERVER_ENTRY = join(PKG_ROOT, "dist", "server", "index.js");
30
+ const NODE = process.execPath;
31
+
32
+ /** 每个会话的服务器子进程 + 元数据 */
33
+ interface RunningServer {
34
+ proc: ReturnType<typeof spawn>;
35
+ port: number;
36
+ cwd: string;
37
+ url: string;
38
+ }
39
+
40
+ // 会话 → 运行实例(模块级 Map;每会话一个会话对象,无需清理全局)
41
+ const running = new Map<string, RunningServer>();
42
+
43
+ /** 找一个空闲端口 */
44
+ function findFreePort(from = 8787): Promise<number> {
45
+ return new Promise((resolve_, reject) => {
46
+ const srv = net.createServer();
47
+ srv.listen(from, () => {
48
+ const port = (srv.address() as net.AddressInfo).port;
49
+ srv.close(() => resolve_(port));
50
+ });
51
+ srv.on("error", () => {
52
+ // 端口被占则顺延
53
+ findFreePort(from + 1).then(resolve_, reject);
54
+ });
55
+ });
56
+ }
57
+
58
+ /** 解析 --key value / --flag 参数 */
59
+ function parseArgs(args: string): { port?: number; cwd?: string; noBrowser: boolean } {
60
+ const out: { port?: number; cwd?: string; noBrowser: boolean } = { noBrowser: false };
61
+ const toks = args.split(/\s+/).filter(Boolean);
62
+ for (let i = 0; i < toks.length; i++) {
63
+ const t = toks[i];
64
+ if ((t === "--port" || t === "-p") && toks[i + 1]) {
65
+ const n = Number(toks[++i]);
66
+ if (Number.isInteger(n) && n > 0 && n < 65536) out.port = n;
67
+ } else if (t === "--cwd" && toks[i + 1]) {
68
+ out.cwd = resolve(toks[++i]);
69
+ } else if (t === "--no-browser") {
70
+ out.noBrowser = true;
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** 打开浏览器 */
77
+ async function openBrowser(url: string): Promise<void> {
78
+ const { platform } = process;
79
+ const [cmd, ...rest] =
80
+ platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
81
+ // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
82
+ // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
83
+ spawn(cmd, rest, { stdio: "ignore", detached: true })
84
+ .on("error", (err) => {
85
+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
86
+ console.warn(
87
+ `[webui] 未找到浏览器打开器 (${(err as NodeJS.ErrnoException).path || "command not found"}),请用 --no-browser 关闭自动打开`,
88
+ );
89
+ } else {
90
+ console.warn("[webui] 打开浏览器失败:", err.message);
91
+ }
92
+ })
93
+ .unref();
94
+ }
95
+
96
+ export default function (pi: ExtensionAPI): void {
97
+ pi.registerCommand("webui", {
98
+ description: "启动本机 pi-web-ui Web 界面(/webui [--port N] [--cwd PATH] [--no-browser] | stop | status)",
99
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
100
+ const sid = ctx.sessionManager.getSessionId();
101
+ const opts = parseArgs(args);
102
+ const action = (args.split(/\s+/)[0] || "start").toLowerCase();
103
+
104
+ // 停止
105
+ if (action === "stop" || action === "kill") {
106
+ const inst = running.get(sid);
107
+ if (!inst) {
108
+ ctx.ui.notify("没有正在运行的本机 pi-web-ui 服务器", "info");
109
+ return;
110
+ }
111
+ inst.proc.kill("SIGTERM");
112
+ running.delete(sid);
113
+ ctx.ui.notify(`已停止 pi-web-ui (${inst.url})`, "info");
114
+ return;
115
+ }
116
+
117
+ // 状态
118
+ if (action === "status") {
119
+ const inst = running.get(sid);
120
+ if (!inst) {
121
+ ctx.ui.notify("本机 pi-web-ui 未运行", "info");
122
+ return;
123
+ }
124
+ const alive = inst.proc.exitCode === null;
125
+ ctx.ui.notify(
126
+ alive
127
+ ? `pi-web-ui 运行中 → ${inst.url}\n端口 ${inst.port} · cwd ${inst.cwd}`
128
+ : `已退出(exit=${inst.proc.exitCode})`,
129
+ alive ? "info" : "warning",
130
+ );
131
+ return;
132
+ }
133
+
134
+ // 默认 start
135
+ if (action !== "start" && action !== "run") {
136
+ ctx.ui.notify(`未知动作 ${action}(可用 start|stop|status)`, "warning");
137
+ return;
138
+ }
139
+
140
+ // 已运行则提示
141
+ const existing = running.get(sid);
142
+ if (existing && existing.proc.exitCode === null) {
143
+ ctx.ui.notify(`pi-web-ui 已在运行 → ${existing.url}`, "info");
144
+ return;
145
+ }
146
+
147
+ // 检查是否已构建
148
+ if (!existsSync(SERVER_ENTRY)) {
149
+ ctx.ui.notify(
150
+ "缺少 dist/ 产物(当前安装未包含已构建前端)。请运行 `npm run build` 后重试,或用 pi-web-ui 官方 npm 包。",
151
+ "warning",
152
+ );
153
+ return;
154
+ }
155
+
156
+ const port = opts.port ?? (await findFreePort());
157
+ const cwd = opts.cwd ?? ctx.cwd;
158
+ const url = `http://localhost:${port}`;
159
+
160
+ const env = {
161
+ ...process.env,
162
+ PORT: String(port),
163
+ PI_WEB_CWD: cwd,
164
+ ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
165
+ };
166
+ const proc = spawn(NODE, [SERVER_ENTRY], { cwd, env, stdio: "ignore", detached: true });
167
+ proc.unref();
168
+ running.set(sid, { proc, port, cwd, url });
169
+
170
+ ctx.ui.notify(`pi-web-ui 启动中 → ${url}\n端口 ${port} · cwd ${cwd}\n(几秒后可用,/webui status 查看)`);
171
+
172
+ if (!opts.noBrowser) await openBrowser(url);
173
+
174
+ // 进程退出时清理
175
+ proc.on("exit", () => {
176
+ if (running.get(sid)?.proc === proc) running.delete(sid);
177
+ });
178
+ },
179
+ });
180
+
181
+ // 会话结束清理子进程,避免孤儿
182
+ pi.on("session_shutdown", async (_event, ctx) => {
183
+ const sid = ctx.sessionManager.getSessionId();
184
+ const inst = running.get(sid);
185
+ if (inst && inst.proc.exitCode === null) {
186
+ inst.proc.kill("SIGTERM");
187
+ running.delete(sid);
188
+ }
189
+ });
190
+ }