pi-web-ui 0.63.4 → 0.64.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.
- package/LICENSE +21 -21
- package/README.md +504 -504
- package/README.zh-CN.md +427 -427
- package/bin/pi-web-ui.mjs +1809 -1809
- package/deploy/com.xingshuyin.pi-web-ui.plist +48 -48
- package/deploy/nginx-subpath.conf +88 -88
- package/deploy/pi-web-ui-task.xml +54 -54
- package/deploy/pi-web-ui.service +31 -31
- package/dist/server/agent-service.js +18 -10
- package/dist/server/attachments.js +3 -3
- package/dist/server/dsh/dsh-agent-service.js +3 -0
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/goal-rpc.mjs +645 -645
- package/dist/server/dsh/runtime/launcher.mjs +164 -164
- package/dist/server/dsh/runtime/override.patch.yml +71 -71
- package/dist/server/dsh/runtime/runtime-root.mjs +86 -86
- package/dist/server/files-service.js +42 -0
- package/dist/server/index.js +3 -0
- package/dist/server/marker-service.js +2 -1
- package/dist/server/markers/builtins/rename.js +1 -3
- package/dist/server/markers/builtins/services.js +6 -2
- package/dist/server/markers/builtins/todo.js +8 -4
- package/dist/server/settings-service.js +5 -1
- package/dist/server/terminals.js +4 -4
- package/dist/server/vision-bridge.js +9 -9
- package/extensions/webui.ts +190 -190
- package/package.json +1 -1
- package/themes/cyberpunk.css +81 -81
- package/themes/dazzle.css +81 -81
- package/themes/md-preview.css +98 -98
- package/themes/white.css +160 -160
- package/web/dist/assets/{TerminalPanel-BFrV6B8W.js → TerminalPanel-DNkAT34Z.js} +1 -1
- package/web/dist/assets/index-CMgDryBL.css +10 -0
- package/web/dist/assets/index-_1vyEugI.js +326 -0
- package/web/dist/favicon.svg +8 -8
- package/web/dist/index.html +21 -21
- package/web/dist/manifest.webmanifest +50 -50
- package/web/dist/sw.js +126 -126
- package/web/public/favicon.svg +8 -8
- package/web/public/manifest.webmanifest +50 -50
- package/web/public/sw.js +126 -126
- package/web/dist/assets/index-BFoSybNe.js +0 -324
- package/web/dist/assets/index-D9G_7fPE.css +0 -10
|
@@ -710,6 +710,48 @@ export class FilesService {
|
|
|
710
710
|
emitErr(`上传文件失败:${err.message}`);
|
|
711
711
|
}
|
|
712
712
|
}
|
|
713
|
+
/**
|
|
714
|
+
* Create a folder. Accepts absolute, ~-prefixed or session-relative paths
|
|
715
|
+
* (same expansion rules as completePath — the cwd picker may browse outside
|
|
716
|
+
* the session root, and set_cwd itself accepts any directory). Answers
|
|
717
|
+
* with a notice; the picker refreshes its listing on its own.
|
|
718
|
+
*/
|
|
719
|
+
async makeDir(input) {
|
|
720
|
+
try {
|
|
721
|
+
const fs = await import("node:fs/promises");
|
|
722
|
+
const { resolve, sep, isAbsolute } = await import("node:path");
|
|
723
|
+
const { homedir } = await import("node:os");
|
|
724
|
+
const home = homedir();
|
|
725
|
+
let expanded = input.trim();
|
|
726
|
+
if (!expanded)
|
|
727
|
+
throw new Error("路径为空");
|
|
728
|
+
if (expanded === "~" || expanded === "~\\") {
|
|
729
|
+
expanded = home;
|
|
730
|
+
}
|
|
731
|
+
else if (expanded.startsWith("~/") || expanded.startsWith("~\\")) {
|
|
732
|
+
expanded = home + sep + expanded.slice(2);
|
|
733
|
+
}
|
|
734
|
+
else if (!isAbsolute(expanded)) {
|
|
735
|
+
expanded = resolve(this.host.getCwd(), expanded);
|
|
736
|
+
}
|
|
737
|
+
const abs = resolve(expanded);
|
|
738
|
+
await fs.mkdir(abs, { recursive: true });
|
|
739
|
+
this.host.emit({
|
|
740
|
+
type: "notice",
|
|
741
|
+
level: "info",
|
|
742
|
+
text: `已创建文件夹:${abs}`,
|
|
743
|
+
textEn: `Folder created: ${abs}`,
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
catch (err) {
|
|
747
|
+
this.host.emit({
|
|
748
|
+
type: "notice",
|
|
749
|
+
level: "error",
|
|
750
|
+
text: `创建文件夹失败:${err.message}`,
|
|
751
|
+
textEn: `Failed to create folder: ${err.message}`,
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
}
|
|
713
755
|
/**
|
|
714
756
|
* Path completion for the cwd input: expand ~/relative paths, list the parent
|
|
715
757
|
* directory, and return prefix matches (dirs first, capped).
|
package/dist/server/index.js
CHANGED
|
@@ -33,7 +33,8 @@ export class MarkerService {
|
|
|
33
33
|
return false;
|
|
34
34
|
if ((name === "rename" || name === "title") && this.settings.disabledMarkers.includes("conv"))
|
|
35
35
|
return false;
|
|
36
|
-
if (name === "conv" &&
|
|
36
|
+
if (name === "conv" &&
|
|
37
|
+
(this.settings.disabledMarkers.includes("rename") || this.settings.disabledMarkers.includes("title")))
|
|
37
38
|
return false;
|
|
38
39
|
return !this.settings.disabledMarkers.includes(name);
|
|
39
40
|
}
|
|
@@ -56,9 +56,7 @@ export const renameMarker = {
|
|
|
56
56
|
/** 别名:[[rename:set:标题]] 等同 [[conv:rename:标题]],方便模型直觉书写。 */
|
|
57
57
|
export const renameAliasMarker = {
|
|
58
58
|
name: "rename",
|
|
59
|
-
guidance: [
|
|
60
|
-
"- [[rename:set:<新标题>]] 同 [[conv:rename:<新标题>]]:重命名当前对话。",
|
|
61
|
-
],
|
|
59
|
+
guidance: ["- [[rename:set:<新标题>]] 同 [[conv:rename:<新标题>]]:重命名当前对话。"],
|
|
62
60
|
async apply(token, ctx) {
|
|
63
61
|
// 兼容任意 op:只要能取到标题就重命名
|
|
64
62
|
const title = extractTitle(token) || token.op?.trim() || "";
|
|
@@ -21,7 +21,9 @@ function findService(state, id) {
|
|
|
21
21
|
return state.services.find((s) => s.id === id);
|
|
22
22
|
}
|
|
23
23
|
function lineOf(s) {
|
|
24
|
-
const meta = [s.pid !== undefined ? `pid ${s.pid}` : "", s.port !== undefined ? `:${s.port}` : ""]
|
|
24
|
+
const meta = [s.pid !== undefined ? `pid ${s.pid}` : "", s.port !== undefined ? `:${s.port}` : ""]
|
|
25
|
+
.filter(Boolean)
|
|
26
|
+
.join(" ");
|
|
25
27
|
return `${s.stopped ? "[x]" : "[ ]"} #${s.id}: ${s.name}${meta ? ` (${meta})` : ""}${s.command ? ` — ${s.command}` : ""}`;
|
|
26
28
|
}
|
|
27
29
|
export function describeServices(state) {
|
|
@@ -53,7 +55,9 @@ export const servicesMarker = {
|
|
|
53
55
|
stopped: false,
|
|
54
56
|
};
|
|
55
57
|
state.services.push(svc);
|
|
56
|
-
const meta = [svc.pid !== undefined ? `pid ${svc.pid}` : "", svc.port !== undefined ? `:${svc.port}` : ""]
|
|
58
|
+
const meta = [svc.pid !== undefined ? `pid ${svc.pid}` : "", svc.port !== undefined ? `:${svc.port}` : ""]
|
|
59
|
+
.filter(Boolean)
|
|
60
|
+
.join(" ");
|
|
57
61
|
return { applied: true, feedback: `Registered #${svc.id}: ${name}${meta ? ` (${meta})` : ""}` };
|
|
58
62
|
}
|
|
59
63
|
case "stop": {
|
|
@@ -16,10 +16,14 @@ function parseId(raw) {
|
|
|
16
16
|
}
|
|
17
17
|
function formatStatus(s) {
|
|
18
18
|
switch (s) {
|
|
19
|
-
case "pending":
|
|
20
|
-
|
|
21
|
-
case "
|
|
22
|
-
|
|
19
|
+
case "pending":
|
|
20
|
+
return "pending";
|
|
21
|
+
case "in_progress":
|
|
22
|
+
return "in_progress";
|
|
23
|
+
case "completed":
|
|
24
|
+
return "completed";
|
|
25
|
+
default:
|
|
26
|
+
return s;
|
|
23
27
|
}
|
|
24
28
|
}
|
|
25
29
|
export function describeTodos(state, includeDeleted = false) {
|
|
@@ -212,7 +212,11 @@ export class SettingsService {
|
|
|
212
212
|
presets: this.presets.map((p) => ({ ...p })),
|
|
213
213
|
...(this.host.getMarkerState
|
|
214
214
|
? this.host.getMarkerState()
|
|
215
|
-
: {
|
|
215
|
+
: {
|
|
216
|
+
markersEnabled: true,
|
|
217
|
+
disabledMarkers: [],
|
|
218
|
+
markers: [],
|
|
219
|
+
}),
|
|
216
220
|
subagentTemplates: this.templates.list(),
|
|
217
221
|
subagentDefaultTemplates: DEFAULT_TEMPLATES.map((t) => t.name),
|
|
218
222
|
},
|
package/dist/server/terminals.js
CHANGED
|
@@ -1532,10 +1532,10 @@ export const TERMINAL_TOOL_NAMES = [
|
|
|
1532
1532
|
/** System-prompt guidance teaching the model WHEN to prefer the terminal tools
|
|
1533
1533
|
* over one-shot bash. Without it models almost never pick them — bash returns
|
|
1534
1534
|
* 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.
|
|
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.
|
|
1539
1539
|
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
1540
|
/** Build the agent-facing persistent terminal tools for one conversation. */
|
|
1541
1541
|
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.
|
package/extensions/webui.ts
CHANGED
|
@@ -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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-web-ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.64.0",
|
|
4
4
|
"description": "Web chat interface for the pi coding agent, powered by the pi SDK (@earendil-works/pi-coding-agent) — one-command run, Docker/systemd/launchd deployable",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|