pi-web-ui 0.100.0 → 0.101.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 (77) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/README.md +46 -44
  3. package/README.zh-CN.md +41 -39
  4. package/bin/pi-web-ui.mjs +4 -10
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9883 -12935
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +41 -167
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/bash-tool.js +83 -0
  13. package/dist/server/browser-page-tool.js +207 -0
  14. package/dist/server/client-id-utils.js +51 -0
  15. package/dist/server/client-state.js +23 -2
  16. package/dist/server/compaction-markers.js +34 -1
  17. package/dist/server/context-budget-runner.js +43 -0
  18. package/dist/server/dangling-tools.js +18 -5
  19. package/dist/server/delegate-mode.js +1 -0
  20. package/dist/server/dispatch-domain-handlers.js +631 -0
  21. package/dist/server/dispatch-plugin-handlers.js +300 -0
  22. package/dist/server/dsh/dsh-agent-service.js +9 -1
  23. package/dist/server/goal-evidence.js +9 -2
  24. package/dist/server/goal-service.js +1 -1
  25. package/dist/server/hashline-engine.js +1 -1
  26. package/dist/server/index.js +191 -969
  27. package/dist/server/left-panel-running.js +115 -0
  28. package/dist/server/lsp-tool.js +40 -12
  29. package/dist/server/markers-list-tool.js +34 -0
  30. package/dist/server/market-service.js +277 -0
  31. package/dist/server/mcp-bridge.js +137 -30
  32. package/dist/server/mcp-hot-reload.js +84 -27
  33. package/dist/server/mcp-manager.js +215 -0
  34. package/dist/server/message-entry-resolver.js +32 -0
  35. package/dist/server/orphan-manager.js +44 -0
  36. package/dist/server/persona-chain.js +63 -0
  37. package/dist/server/plan-mode.js +2 -0
  38. package/dist/server/plan-update-tool.js +96 -0
  39. package/dist/server/plugin-api-catalog.js +20 -0
  40. package/dist/server/plugin-facilities.js +13 -3
  41. package/dist/server/plugin-ui-slots.js +39 -0
  42. package/dist/server/plugins.js +71 -38
  43. package/dist/server/preset-fields.js +7 -0
  44. package/dist/server/preset-share.js +1 -0
  45. package/dist/server/process-utils.js +30 -0
  46. package/dist/server/prompt-assembler.js +80 -0
  47. package/dist/server/scm-commitmsg.js +74 -0
  48. package/dist/server/serialize.js +97 -7
  49. package/dist/server/session-branch.js +367 -0
  50. package/dist/server/session-parser.js +235 -0
  51. package/dist/server/session-search.js +158 -0
  52. package/dist/server/settings-service.js +13 -1
  53. package/dist/server/skill-content-filler.js +33 -0
  54. package/dist/server/subagent-handoff.js +18 -0
  55. package/dist/server/subagent-helpers.js +88 -0
  56. package/dist/server/terminals.js +155 -58
  57. package/dist/server/tool-guards.js +527 -0
  58. package/dist/server/tool-host-factories.js +217 -0
  59. package/dist/server/tool-manager.js +30 -5
  60. package/dist/server/wait-subscription-scan.js +46 -1
  61. package/dist/server/workspace-snapshot.js +18 -0
  62. package/extensions/webui.ts +90 -24
  63. package/package.json +1 -1
  64. package/plugin-sdk/README.md +17 -0
  65. package/plugin-sdk/index.d.ts +17 -0
  66. package/plugin-sdk/index.mjs +5 -0
  67. package/plugins/catalog.json +20 -0
  68. package/themes/aetheris.css +3 -1
  69. package/themes/translucent.css +8 -1
  70. package/themes/transparent.css +9 -1
  71. package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-DD7I5_aC.js} +1 -1
  72. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  73. package/web/dist/assets/index-nKn87VuM.js +678 -0
  74. package/web/dist/index.html +2 -2
  75. package/web/dist/sw.js +1 -1
  76. package/web/dist/assets/index-B-E2EM_0.css +0 -1
  77. package/web/dist/assets/index-BYumAaGi.js +0 -379
@@ -0,0 +1,44 @@
1
+ /**
2
+ * orphan-manager — 残留会话认领与同工作区比对工具。
3
+ *
4
+ * 负责:
5
+ * - pickAdoptableOrphan: 选一个断开连接的残留会话给新标签页认领(纯函数)
6
+ * - sameCwd: 跨平台工作区路径一致性比对(纯函数)
7
+ *
8
+ * 从 agent-service.ts 抽出为独立模块。
9
+ */
10
+ import { normalizePathKey } from "./client-state.js";
11
+ /**
12
+ * 选一个断开的残留会话给新标签认领(纯函数):
13
+ * - 还有别的在线浏览器(非伪客户端且 live)→ 不认领(新标签是第二块屏,
14
+ * issue #10 的隔离必须保留,跑着的对话继续走 elsewhere 只读感知)。
15
+ * - 否则在断开 + 非伪 + 有内容的候选中按(streaming 多 → 最近活跃)取最优;
16
+ * 没有返回 null(调用方走正常新建流程)。
17
+ */
18
+ export function pickAdoptableOrphan(cands) {
19
+ if (cands.some((c) => !c.pseudo && c.live))
20
+ return null;
21
+ let best = null;
22
+ for (const c of cands) {
23
+ if (c.pseudo || c.live || !c.adoptable)
24
+ continue;
25
+ if (!best || c.streaming > best.streaming || (c.streaming === best.streaming && c.activity > best.activity)) {
26
+ best = c;
27
+ }
28
+ }
29
+ return best?.id ?? null;
30
+ }
31
+ /** 同项目判定(纯函数):调度视口回退与 id 唤醒的 cwd 护栏用。
32
+ * Windows 大小写/分隔符差异归一,空串永不相等。 */
33
+ export function sameCwd(a, b) {
34
+ const x = String(a ?? "").trim();
35
+ const y = String(b ?? "").trim();
36
+ if (!x || !y)
37
+ return false;
38
+ try {
39
+ return normalizePathKey(x) === normalizePathKey(y);
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * persona-chain — 内联人设注入、扩展提示词包裹剥离与平台人设补丁。
3
+ *
4
+ * 负责:
5
+ * - INLINE_PERSONA_EXT: 自家内联扩展名标识
6
+ * - splitAgentStartPrompt: 剥离先前扩展对 SDK 原始系统提示词的首尾增补
7
+ * - PI_DOC_PATHS: 本地 pi SDK 文档路径发现
8
+ * - WINDOWS_PERSONA: Windows 平台特有人设补丁(超时/非交互 TTY/GBK 编码)
9
+ *
10
+ * 从 agent-service.ts 抽出为独立模块。
11
+ */
12
+ import { createRequire } from "node:module";
13
+ import { dirname, join } from "node:path";
14
+ import { splitExtensionWrap } from "./prompt-composer.js";
15
+ /** 自家内联扩展名(组合模板渲染,见 prompt-composer.ts)。SDK 以其
16
+ * "<inline:<name>>" 作为 path;扩展白名单/禁用过滤必须放行它。 */
17
+ export const INLINE_PERSONA_EXT = "<inline:pi-webui-persona>";
18
+ /** 本次 run 的 SDK 原始提示词 + 早前扩展的首尾增补(见 splitExtensionWrap)。
19
+ * 导出仅为单测(tests/unit/persona-prompt-chain.test.ts)可达。
20
+ * systemPromptOptions 就是 runner 里那个共享可变对象,forceSystemPrompt 有值即
21
+ * 说明前面有扩展替换过提示词;临时清掉再读 event.systemPrompt 就拿到原始基线
22
+ * (公开字段,不碰 SDK 内部)。没人动过时零开销,直接返回当前文本。 */
23
+ export function splitAgentStartPrompt(event) {
24
+ const current = event.systemPrompt;
25
+ const opts = event.systemPromptOptions;
26
+ const forced = opts?.forceSystemPrompt;
27
+ if (!opts || typeof forced !== "string")
28
+ return { pre: "", core: current, post: "" };
29
+ try {
30
+ opts.forceSystemPrompt = undefined;
31
+ return splitExtensionWrap(event.systemPrompt, current);
32
+ }
33
+ finally {
34
+ opts.forceSystemPrompt = forced;
35
+ }
36
+ }
37
+ /** Pi 包文档路径(composer 的 {{pi_docs}} 自动内容用)。随安装位置解析一次。 */
38
+ export const PI_DOC_PATHS = (() => {
39
+ try {
40
+ const requireLocal = createRequire(import.meta.url);
41
+ const root = dirname(requireLocal.resolve("@earendil-works/pi-coding-agent/package.json"));
42
+ return { readme: join(root, "README.md"), docs: join(root, "docs"), examples: join(root, "examples") };
43
+ }
44
+ catch {
45
+ return { readme: "", docs: "", examples: "" };
46
+ }
47
+ })();
48
+ /** Windows persona appendix — appended to the SDK system prompt on win32 only.
49
+ * Two failure modes it guards against: (1) the SDK bash tool has NO default
50
+ * timeout, so a long-running command hangs the whole conversation forever;
51
+ * (2) the in-app terminal is an interactive TTY where heredocs / interactive
52
+ * programs wait for input that never comes. Legacy Chinese files are often
53
+ * GBK/GB2312 — read them with the right encoding, never paste mojibake into
54
+ * reasoning/answers. */
55
+ export const WINDOWS_PERSONA = `You are a coding agent running on Windows. The bash tool runs Git Bash (bash.exe), not PowerShell. Follow these rules to avoid hanging the session:
56
+
57
+
58
+
59
+ - ALWAYS pass a timeout parameter to the bash tool (in seconds). There is NO default timeout — a command that never finishes (servers, watchers, infinite loops, slow downloads/installs) will hang the entire conversation indefinitely. Pick a generous timeout for long-running work, but never omit it.
60
+ - NEVER run interactive or foreground long-running commands through the bash tool (vi, less, top, python -, node -, npm run dev, sleep 10000). For servers/daemons use background execution with output redirected to a log file, then poll the log; stop them when done.
61
+ - In the interactive terminal (TTY) — which is Git Bash too, not PowerShell — NEVER use heredocs (<<'EOF' ... EOF) or here-strings, and NEVER start interactive programs (vi, less, python -, node -, npm init): they wait for keyboard input that never arrives and hang the terminal forever. Prefer writing a temp script file (e.g. .pi-tmp.sh) and running it non-interactively. ALWAYS pass a timeout to long-running commands (e.g. \`timeout 120 npm run dev\`).
62
+
63
+ Many legacy Chinese text files (.html/.txt/.md/.log, exported documents) are GBK/GB2312 encoded: the read tool decodes UTF-8 only and will show mojibake (乱码) for them. If a file's content looks garbled, read it through the terminal instead: in Git Bash use \`cat file | iconv -f GBK -t UTF-8\` (or \`iconv -f GBK -t UTF-8 file\`); in cmd use \`chcp 65001 && type file\`; in PowerShell use \`Get-Content -Encoding Default file\`. Never paste mojibake into your reasoning or answer — describe the decoded content instead.`;
@@ -49,6 +49,8 @@ const BLOCKED_TOOLS = new Set([
49
49
  // 代码求值(eval 沙箱的 execute 直接 kernel.execute,可写真实文件系统;
50
50
  // 默认关但用户可开,开了就是一条写路径 —— #436)
51
51
  "eval",
52
+ // QuickJS 沙箱代码执行(可嵌套调用写工具/命令,计划模式禁止任意代码执行)
53
+ "codemode",
52
54
  // 形态变换(会重写整个文件树)
53
55
  "format",
54
56
  "prettier",
@@ -0,0 +1,96 @@
1
+ /**
2
+ * plan_update customTool:结构化任务执行计划更新工具(Plan Mode / Step State Machine)。
3
+ *
4
+ * 跟踪决策就绪步骤、文件改动清单(File Touch List)与状态机流转。
5
+ * 从 agent-service.ts 抽出为独立模块。
6
+ */
7
+ import { Type } from "typebox";
8
+ import { PLAN_UPDATE_TOOL_NAME } from "./tool-manager.js";
9
+ /**
10
+ * 将 SoL-Pi 的 update_plan 步骤结构({ id, goal, status })标准化为 pi-web-ui 的 PlanStep[] 结构。
11
+ */
12
+ export function normalizeSolPlanToPlanSteps(steps) {
13
+ if (!Array.isArray(steps))
14
+ return { steps: [] };
15
+ let activeStepId = null;
16
+ const normalizedSteps = steps.map((s, idx) => {
17
+ const step = (s && typeof s === "object" ? s : {});
18
+ const id = typeof step.id === "string" && step.id ? step.id : String(idx + 1);
19
+ const rawTitle = typeof step.goal === "string" ? step.goal : typeof step.title === "string" ? step.title : `Step ${id}`;
20
+ const rawStatus = typeof step.status === "string" ? step.status : "pending";
21
+ let status = "pending";
22
+ if (rawStatus === "completed" || rawStatus === "done") {
23
+ status = "done";
24
+ }
25
+ else if (rawStatus === "in_progress") {
26
+ status = "in_progress";
27
+ if (!activeStepId)
28
+ activeStepId = id;
29
+ }
30
+ else if (rawStatus === "failed") {
31
+ status = "failed";
32
+ }
33
+ const description = typeof step.description === "string" ? step.description : undefined;
34
+ return { id, title: rawTitle, status, ...(description ? { description } : {}) };
35
+ });
36
+ return { steps: normalizedSteps, activeStepId };
37
+ }
38
+ /**
39
+ * 结构化任务执行计划更新工具(plan_update)— Plan Mode / Step State Machine。
40
+ */
41
+ export function makePlanUpdateTool(planManager, getActiveConvTarget, emit, flushSnapshot, onPersist) {
42
+ return {
43
+ name: PLAN_UPDATE_TOOL_NAME,
44
+ label: "plan_update",
45
+ description: "Update the structured task plan / step state machine (Plan Mode) and track progress (pending -> in_progress -> done/failed).",
46
+ promptSnippet: "track decision-ready steps, file touch list, and live status",
47
+ promptGuidelines: [
48
+ "Use plan_update early on non-trivial tasks to outline decision-ready steps before coding",
49
+ "Per step: discovery conclusions, files to be touched (File Touch List), rollback strategy",
50
+ "Update step status as work progresses for real-time visibility",
51
+ ],
52
+ parameters: Type.Object({
53
+ steps: Type.Array(Type.Object({
54
+ id: Type.String({ description: "Unique step ID, e.g. '1', 'step-1'" }),
55
+ title: Type.String({ description: "Short step title" }),
56
+ status: Type.Optional(Type.Unsafe({
57
+ type: "string",
58
+ enum: ["pending", "in_progress", "done", "failed"],
59
+ description: "Step status: pending | in_progress | done | failed (default: pending)",
60
+ })),
61
+ description: Type.Optional(Type.String({
62
+ description: "Optional step detail: acceptance criteria, files touched, rollback note.",
63
+ })),
64
+ }), { description: "List of plan steps" }),
65
+ activeStepId: Type.Optional(Type.String({ description: "ID of the step currently being executed" })),
66
+ }),
67
+ execute: async (toolCallId, params) => {
68
+ const target = getActiveConvTarget();
69
+ const convId = typeof target === "string" ? target : target.id;
70
+ const sessionId = typeof target === "string" ? undefined : target.sessionId;
71
+ const p = params;
72
+ const plan = planManager.setPlan(convId, p.steps, p.activeStepId, sessionId);
73
+ if (typeof target !== "string" && target.sessionManager) {
74
+ try {
75
+ const sm = target.sessionManager;
76
+ sm?.appendCustomEntry?.("plan/update", { plan });
77
+ }
78
+ catch {
79
+ // 转录追加失败不影响主流程
80
+ }
81
+ }
82
+ onPersist?.(convId, plan);
83
+ emit({
84
+ type: "plan_updated",
85
+ conversationId: convId,
86
+ plan,
87
+ });
88
+ flushSnapshot();
89
+ const summary = planManager.describePlan(convId);
90
+ return {
91
+ content: [{ type: "text", text: `Plan updated successfully.\n\n${summary}` }],
92
+ details: { plan },
93
+ };
94
+ },
95
+ };
96
+ }
@@ -11,10 +11,18 @@ export const SLOT_EXAMPLES = {
11
11
  "contextmenu.topbar": `{ "ui": { "contextmenu.topbar": [{ "id": "m", "label": "顶栏菜单", "kind": "action", "action": "my:m" }] } }`,
12
12
  "contextmenu.message": `{ "ui": { "contextmenu.message": [{ "id": "m", "label": "消息菜单", "kind": "action", "action": "my:m" }] } }`,
13
13
  "contextmenu.session": `{ "ui": { "contextmenu.session": [{ "id": "m", "label": "会话菜单", "kind": "action", "action": "my:m" }] } }`,
14
+ "contextmenu.project": `{ "ui": { "contextmenu.project": [{ "id": "m", "label": "项目菜单", "kind": "action", "action": "my:m" }] } }`,
14
15
  "contextmenu.file": `{ "contextmenu.file": [{ "id": "mail", "label": "发到邮箱", "kind": "action", "action": "my:send" }] }`,
15
16
  "contextmenu.toolcall": `{ "ui": { "contextmenu.toolcall": [{ "id": "m", "label": "工具菜单", "kind": "action", "action": "my:m" }] } }`,
16
17
  "settings.pages": `{ "settings": [{ "id": "conf", "label": "邮箱设置", "kind": "page" }] }`,
17
18
  "tasks.panel": `{ "ui": { "tasks.panel": [{ "id": "pm2", "label": "pm2 托管的应用", "kind": "view" }] } }`,
19
+ "leftpanel.projects.actions": `{ "ui": { "leftpanel.projects.actions": [{ "id": "m", "label": "项目标题按钮", "kind": "action", "action": "my:m" }] } }`,
20
+ "leftpanel.project": `{ "ui": { "leftpanel.project": [{ "id": "m", "label": "项目行", "kind": "action", "action": "my:m" }] } }`,
21
+ "leftpanel.running.actions": `{ "ui": { "leftpanel.running.actions": [{ "id": "m", "label": "运行标题按钮", "kind": "action", "action": "my:m" }] } }`,
22
+ "leftpanel.history.actions": `{ "ui": { "leftpanel.history.actions": [{ "id": "m", "label": "历史标题按钮", "kind": "action", "action": "my:m" }] } }`,
23
+ "leftpanel.sections": `{ "ui": { "leftpanel.sections": [{ "id": "m", "label": "我的分区", "kind": "view" }] } }`,
24
+ "leftpanel.running": `{ "ui": { "leftpanel.running": [{ "id": "m", "label": "运行行", "kind": "action", "action": "my:m" }] } }`,
25
+ "leftpanel.history": `{ "ui": { "leftpanel.history": [{ "id": "m", "label": "历史行", "kind": "action", "action": "my:m" }] } }`,
18
26
  "leftpanel.sessions": `{ "ui": { "leftpanel.sessions": [{ "id": "m", "label": "会话区", "kind": "action", "action": "my:m" }] } }`,
19
27
  "chat.header": `{ "ui": { "chat.header": [{ "id": "m", "label": "会话题头", "kind": "action", "action": "my:m" }] } }`,
20
28
  "chat.empty": `{ "ui": { "chat.empty": [{ "id": "m", "label": "空态", "kind": "action", "action": "my:m" }] } }`,
@@ -30,6 +38,18 @@ export const SLOT_EXAMPLES = {
30
38
  /** 宿主方法表(与 server/plugins.ts#PluginHost 同语义的精简版:只收发现用的注册/调用面)。
31
39
  * needs="-" = 观察/基础设施类(无需能力声明);其余走 can() 门控。 */
32
40
  export const HOST_METHODS = [
41
+ {
42
+ name: "leftPanel.setRunning",
43
+ needs: "ui",
44
+ summary: "左栏「运行的对话」登记插件运行条目(整体替换即心跳;ttlMs 缺省 60s 无心跳自动清空)",
45
+ example: `host.leftPanel.setRunning([{ id: "sync-1", title: "同步邮件", status: "running", hint: "3/10" }])`,
46
+ },
47
+ {
48
+ name: "leftPanel.clear",
49
+ needs: "ui",
50
+ summary: "立即清空本插件在左栏的运行条目",
51
+ example: `host.leftPanel.clear()`,
52
+ },
33
53
  {
34
54
  name: "ui.register",
35
55
  needs: "ui",
@@ -370,9 +370,19 @@ export function ensurePluginDeps(pluginDir, specs, onProgress) {
370
370
  catch { }
371
371
  }
372
372
  onProgress?.(`正在安装依赖:${missing.join(", ")}…(首次约需几分钟)`);
373
- // win32 的 npm 是 .cmd——spawnSync 直接跑会被 EINVAL 拒绝,必须走 shell;
374
- // posix 不用 shell(路径不含空格假设成立,与宿主其它 spawn 一致)。
375
- const res = spawnSync(process.platform === "win32" ? "npm.cmd" : "npm", ["install", "--no-audit", "--no-fund", ...missing], { cwd: pluginDir, timeout: DEP_TIMEOUT_MS, shell: process.platform === "win32", encoding: "utf8" });
373
+ // win32 的 npm 是 .cmd——spawnSync 直接跑会被 EINVAL 拒绝;走 cmd.exe /d /s /c
374
+ // 规避 DEP0190 与命令行注入,posix 不用 shell(路径不含空格假设成立,与宿主其它 spawn 一致)。
375
+ const isWin = process.platform === "win32";
376
+ const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : "npm";
377
+ const spawnArgs = isWin
378
+ ? ["/d", "/s", "/c", "npm.cmd", "install", "--no-audit", "--no-fund", ...missing]
379
+ : ["install", "--no-audit", "--no-fund", ...missing];
380
+ const res = spawnSync(spawnCmd, spawnArgs, {
381
+ cwd: pluginDir,
382
+ timeout: DEP_TIMEOUT_MS,
383
+ windowsHide: true,
384
+ encoding: "utf8",
385
+ });
376
386
  if (res.error || res.status !== 0) {
377
387
  console.error(`[plugin-deps] ${join(pluginDir)} npm install 失败:`, res.error ?? res.stderr?.slice(0, 500));
378
388
  return false;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * UI_SLOTS — 宿主支持的全部挂载点集合,用于运行态校验。
3
+ * 抽离到独立文件以打破 client-state.ts 与 plugins.ts 之间的循环依赖。
4
+ */
5
+ export const UI_SLOTS = new Set([
6
+ "topbar.primary",
7
+ "topbar.overflow",
8
+ "bottombar",
9
+ "composer.leading",
10
+ "composer.actions",
11
+ "message.actions",
12
+ "rightpanel.tabs",
13
+ "contextmenu.topbar",
14
+ "contextmenu.message",
15
+ "contextmenu.session",
16
+ "contextmenu.project",
17
+ "contextmenu.file",
18
+ "contextmenu.toolcall",
19
+ "settings.pages",
20
+ "tasks.panel",
21
+ "leftpanel.projects.actions",
22
+ "leftpanel.project",
23
+ "leftpanel.running.actions",
24
+ "leftpanel.history.actions",
25
+ "leftpanel.running",
26
+ "leftpanel.sections",
27
+ "leftpanel.history",
28
+ "leftpanel.sessions",
29
+ "chat.header",
30
+ "chat.empty",
31
+ "file.preview.toolbar",
32
+ "terminal.toolbar",
33
+ "scm.toolbar",
34
+ "goalbar.actions",
35
+ "notice.actions",
36
+ "modal.dialog",
37
+ "sidebar.left",
38
+ "sidebar.right",
39
+ ]);
@@ -20,6 +20,9 @@ import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"
20
20
  import { cpSync, existsSync, readFileSync, readdirSync, renameSync, watch as fsWatch, writeFileSync } from "node:fs";
21
21
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
22
22
  import { pathToFileURL, fileURLToPath } from "node:url";
23
+ import {} from "./protocol.js";
24
+ import { UI_SLOTS } from "./plugin-ui-slots.js";
25
+ import { LeftPanelRunningStore } from "./left-panel-running.js";
23
26
  import { pick } from "./i18n.js";
24
27
  import { PluginStorage, PluginSecrets, ensurePluginDeps, WorkspaceFS, withFileRmwLock } from "./plugin-facilities.js";
25
28
  import { parseCronSpec, armDelay, nextCronFire, loadScheduleRecords, saveScheduleRecords, } from "./plugin-schedule.js";
@@ -277,33 +280,7 @@ const SETTING_OPTIONS_FROM = new Set(["models", "thinkingLevels"]);
277
280
  * 不认识的 slot / kind / when 直接丢弃(旧宿主读到新字段也不会崩,新宿主读到旧字段同理)。
278
281
  * 归属由宿主决定:全局 id = `<pluginId>:<itemId>`。
279
282
  */
280
- export const UI_SLOTS = new Set([
281
- "topbar.primary",
282
- "topbar.overflow",
283
- "bottombar",
284
- "composer.leading",
285
- "composer.actions",
286
- "message.actions",
287
- "rightpanel.tabs",
288
- "contextmenu.topbar",
289
- "contextmenu.message",
290
- "contextmenu.session",
291
- "contextmenu.file",
292
- "contextmenu.toolcall",
293
- "settings.pages",
294
- "tasks.panel",
295
- "leftpanel.sessions",
296
- "chat.header",
297
- "chat.empty",
298
- "file.preview.toolbar",
299
- "terminal.toolbar",
300
- "scm.toolbar",
301
- "goalbar.actions",
302
- "notice.actions",
303
- "modal.dialog",
304
- "sidebar.left",
305
- "sidebar.right",
306
- ]);
283
+ export { UI_SLOTS };
307
284
  /** manifest 里可以写更自然的简写(作者少踩坑):解析时映射到完整 slot 名。 */
308
285
  export const UI_SLOT_ALIASES = {
309
286
  topbar: "topbar.primary",
@@ -887,10 +864,6 @@ function readStoredSettings(dir) {
887
864
  }
888
865
  return {};
889
866
  }
890
- function storedSettingsValues(dir, schema, secrets, overlay = {}) {
891
- // 浏览器侧 secret 只看到有无(布尔),明文永不下发;无 secrets 上下文(如单测)回落 false。
892
- return resolveSettingsValues(schema, readStoredSettings(dir), overlay, secrets ? { has: (k) => secrets.has(k) } : undefined).values;
893
- }
894
867
  /** 插件运行时视角的设置值:非 secret 与 storedSettingsValues 同口径;secret 返回真值
895
868
  * (无则回落默认值/空串)。只给插件服务端代码用,绝不下发浏览器。 */
896
869
  function runtimeSettingsValues(dir, schema, secrets, overlay = {}) {
@@ -1031,6 +1004,10 @@ export class PluginManager {
1031
1004
  pluginBgTasks = new Map();
1032
1005
  /** 任务集合变化回调(index.ts 接到 AgentService,重推 bg_servers)。 */
1033
1006
  onBgTasksChanged = undefined;
1007
+ /** P3:左栏插件运行条目(见 left-panel-running.ts)。 */
1008
+ panelRunning = new LeftPanelRunningStore();
1009
+ panelPushTimer = null;
1010
+ panelSweepTimer = null;
1034
1011
  /** 服务端重载纪元:每次 reload() +1,前端用作 import 缓存击穿参数。 */
1035
1012
  epochCounter = 0;
1036
1013
  /** 插件市场列表纪元:每次 add/remove +1,前端据此重渲。 */
@@ -1500,7 +1477,7 @@ export class PluginManager {
1500
1477
  }
1501
1478
  /** agent-service 调(P1-5):bash/read 执行前的守卫求值。首个 deny/ask 胜出;
1502
1479
  * 守卫抛错/超时一律按弃权(不阻断)。无守卫时回 allow,调用方可直接放行。 */
1503
- async evaluateToolPre(req, lang = "en") {
1480
+ async evaluateToolPre(req, _lang = "en") {
1504
1481
  const frozen = {
1505
1482
  toolName: req.toolName,
1506
1483
  params: freezeParams(req.params),
@@ -1623,7 +1600,7 @@ export class PluginManager {
1623
1600
  activatingGates = new Map();
1624
1601
  /** 会话统计扇出(异常隔离;订阅者崩了只记日志)。发送方(如定期推送快照统计处)负责节流。 */
1625
1602
  emitStats(s) {
1626
- for (const h of [...this.statsHandlers]) {
1603
+ for (const h of this.statsHandlers) {
1627
1604
  try {
1628
1605
  h(s);
1629
1606
  }
@@ -1634,7 +1611,7 @@ export class PluginManager {
1634
1611
  }
1635
1612
  /** 流式增量透传(异常隔离;宿主不做节流,由发送方保证频率)。 */
1636
1613
  emitStreaming(ev) {
1637
- for (const h of [...this.streamingHandlers]) {
1614
+ for (const h of this.streamingHandlers) {
1638
1615
  try {
1639
1616
  h(ev);
1640
1617
  }
@@ -1754,7 +1731,7 @@ export class PluginManager {
1754
1731
  * run_end 顺带唤醒 host.chatWait 的等待者(按 conversationId 匹配)。 */
1755
1732
  emitRunEvent(ev) {
1756
1733
  if (ev.type === "run_end" && ev.conversationId) {
1757
- for (const w of [...this.chatWaiters]) {
1734
+ for (const w of this.chatWaiters) {
1758
1735
  if (w.conversationId !== ev.conversationId)
1759
1736
  continue;
1760
1737
  try {
@@ -2001,6 +1978,35 @@ export class PluginManager {
2001
1978
  }
2002
1979
  }
2003
1980
  }
1981
+ /** P3:节流广播左栏运行条目(同一窗口内的多次变更合并成一条,约 500ms)。 */
1982
+ schedulePanelPush() {
1983
+ if (this.panelPushTimer)
1984
+ return;
1985
+ this.panelPushTimer = setTimeout(() => {
1986
+ this.panelPushTimer = null;
1987
+ this.deliverAll({ type: "plugin_panel_items", groups: this.panelRunning.groups() });
1988
+ }, 500);
1989
+ this.panelPushTimer.unref?.();
1990
+ }
1991
+ /** P3:心跳扫描(有条目才跑,每 5 秒):过期即清空并广播;条目全无则停表。 */
1992
+ ensurePanelSweep() {
1993
+ if (this.panelSweepTimer)
1994
+ return;
1995
+ this.panelSweepTimer = setInterval(() => {
1996
+ const expired = this.panelRunning.sweep();
1997
+ if (expired.length)
1998
+ this.schedulePanelPush();
1999
+ if (this.panelRunning.size === 0 && this.panelSweepTimer) {
2000
+ clearInterval(this.panelSweepTimer);
2001
+ this.panelSweepTimer = null;
2002
+ }
2003
+ }, 5000);
2004
+ this.panelSweepTimer.unref?.();
2005
+ }
2006
+ /** P3:attach 时补发的全量(index.ts 用)。 */
2007
+ panelGroups() {
2008
+ return this.panelRunning.groups();
2009
+ }
2004
2010
  /** 当前目录清单(重扫 manifest,不重新 import)。 */
2005
2011
  async list(lang) {
2006
2012
  return this.scan(lang);
@@ -2167,7 +2173,7 @@ export class PluginManager {
2167
2173
  }
2168
2174
  }
2169
2175
  // ③ 兜底:清掉插件名下的代理前缀(该插件名下但未经栈登记的残留)。
2170
- for (const prefix of [...this.proxyRoutes.keys()]) {
2176
+ for (const prefix of this.proxyRoutes.keys()) {
2171
2177
  if (pluginIds.has(this.proxyRoutes.get(prefix).pluginId))
2172
2178
  this.proxyRoutes.delete(prefix);
2173
2179
  }
@@ -2507,7 +2513,7 @@ export class PluginManager {
2507
2513
  const hit = [];
2508
2514
  for (;;) {
2509
2515
  let changed = false;
2510
- for (const [id, p] of [...this.loaded]) {
2516
+ for (const [id, p] of this.loaded) {
2511
2517
  if (p.info.error)
2512
2518
  continue;
2513
2519
  const req = byId.get(id)?.requires ?? p.info.requires;
@@ -2591,6 +2597,7 @@ export class PluginManager {
2591
2597
  const cwdHandlers = new Set();
2592
2598
  const httpRoutes = new Map();
2593
2599
  const bgTaskTable = new Map();
2600
+ let leftPanelOwned = false;
2594
2601
  const settingsHandlers = new Set();
2595
2602
  // 可逆副作用栈:本插件的全部注册面(工具/命令/路由/代理/watch/定时/后台任务/
2596
2603
  // UI 条目/事件订阅…)都经 effects.add 登记,反激活时**逆序**回卷 —— 插件忘写
@@ -3277,6 +3284,32 @@ export class PluginManager {
3277
3284
  return createProject(spec, { onProgress: (line) => self.notifyAll("info", line) });
3278
3285
  },
3279
3286
  },
3287
+ leftPanel: {
3288
+ setRunning: (items, opts) => {
3289
+ if (!can("ui"))
3290
+ return;
3291
+ if (!leftPanelOwned) {
3292
+ leftPanelOwned = true;
3293
+ effects.add("leftPanel", () => {
3294
+ leftPanelOwned = false;
3295
+ if (self.panelRunning.clear(info.id))
3296
+ self.schedulePanelPush();
3297
+ });
3298
+ }
3299
+ const outcome = self.panelRunning.set(info.id, info.name || info.id, items, opts);
3300
+ for (const d of outcome.diags)
3301
+ self.pushRuntimeDiag(info.id, d);
3302
+ if (outcome.changed)
3303
+ self.schedulePanelPush();
3304
+ self.ensurePanelSweep();
3305
+ },
3306
+ clear: () => {
3307
+ if (!can("ui"))
3308
+ return;
3309
+ if (self.panelRunning.clear(info.id))
3310
+ self.schedulePanelPush();
3311
+ },
3312
+ },
3280
3313
  registerBackgroundTask: (task) => {
3281
3314
  const id = String(task?.id ?? "").trim();
3282
3315
  if (!id || bgTaskTable.has(id)) {
@@ -3771,7 +3804,7 @@ export class PluginManager {
3771
3804
  const handlers = self.busHandlers.get(t);
3772
3805
  if (!handlers)
3773
3806
  return;
3774
- for (const h of [...handlers]) {
3807
+ for (const h of handlers) {
3775
3808
  try {
3776
3809
  h(ev);
3777
3810
  }
@@ -74,6 +74,7 @@ export const PRESET_FIELD_GROUPS = {
74
74
  "thinkingWrap",
75
75
  "toolsWrap",
76
76
  "toolImagesEnabled",
77
+ "keepRecentMessages",
77
78
  "bgAutoCleanupMin",
78
79
  "quickPhrases",
79
80
  "quickPhrasesEnabled",
@@ -378,6 +379,12 @@ export const PRESET_FIELD_META = {
378
379
  hintZh: "直接在工具卡片内渲染输出的图片文件",
379
380
  hintEn: "Render image output directly in tool cards",
380
381
  },
382
+ keepRecentMessages: {
383
+ labelZh: "常驻渲染消息数",
384
+ labelEn: "Messages Kept In Full",
385
+ hintZh: "消息列表尾部保持完整渲染的消息条数;更早的折叠为摘要行",
386
+ hintEn: "Recent messages rendered in full; older ones collapse to summary rows",
387
+ },
381
388
  quickPhrases: {
382
389
  labelZh: "快捷短语列表",
383
390
  labelEn: "Quick Phrases List",
@@ -277,6 +277,7 @@ const PRESET_FIELD_KINDS = {
277
277
  thinkingWrap: "bool",
278
278
  toolsWrap: "bool",
279
279
  toolImagesEnabled: "bool",
280
+ keepRecentMessages: "number",
280
281
  quickPhrases: "list",
281
282
  quickPhrasesEnabled: "bool",
282
283
  devNoCache: "bool",
@@ -1,3 +1,4 @@
1
+ import { resolve } from "node:path";
1
2
  /**
2
3
  * process-utils — 跨平台进程工具:监听端口快照、进程树查杀、进程名查询。
3
4
  * 后台任务面板(bgServers)用它们检测/停止 agent 在后台拉起的服务。
@@ -161,3 +162,32 @@ export async function lookupProcessName(pid) {
161
162
  return undefined;
162
163
  }
163
164
  }
165
+ /**
166
+ * 超时杀进程树的决策(纯函数,可单测)。runAsync 的超时兜底用:
167
+ * - win32:shell:true 实际起的是 cmd.exe,p.kill() 只杀 cmd 本身,npm/git 的
168
+ * 孙进程照活 —— 必须走 `taskkill /PID <pid> /T /F` 才能整树带走;
169
+ * - posix:配合 spawn 的 detached:true,向负 pid(整组)发 SIGTERM。
170
+ * 返回决策而不是直接执行,执行留在调用方(便于注入/测试)。
171
+ */
172
+ export function processTreeKillPlan(platform, pid) {
173
+ if (!pid || pid <= 0)
174
+ return { kind: "none" };
175
+ if (platform === "win32")
176
+ return { kind: "taskkill", cmd: "taskkill", args: ["/PID", String(pid), "/T", "/F"] };
177
+ return { kind: "group-signal", signal: "SIGTERM" };
178
+ }
179
+ /**
180
+ * /cwd 目标解析(纯函数,可单测):
181
+ * - 相对路径以**当前会话 cwd** 为基准(/cwd src = 当前项目的 src),不按 server
182
+ * 进程 cwd 解析 —— 两者经常不同,按进程 cwd 切必错位。绝对路径不受基准影响
183
+ * (resolve 遇到绝对段会丢弃前面的基准)。
184
+ * - win32 裸盘符("C:"):resolve 会按该盘当前目录解析,必须显式指到盘根;仅
185
+ * win32 生效——posix 下 "C:" 仍是普通相对路径,避免误伤同名目录。
186
+ */
187
+ export function resolveCwdTarget(raw, sessionCwd, platform = process.platform) {
188
+ const trimmed = String(raw ?? "").trim();
189
+ if (platform === "win32" && /^[A-Za-z]:$/.test(trimmed)) {
190
+ return `${trimmed.toUpperCase()}\\`;
191
+ }
192
+ return resolve(sessionCwd, trimmed);
193
+ }