pi-web-ui 0.99.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 (109) hide show
  1. package/CHANGELOG.md +90 -1
  2. package/README.md +48 -45
  3. package/README.zh-CN.md +43 -40
  4. package/bin/pi-web-ui.mjs +172 -40
  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 +9851 -11892
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +130 -184
  10. package/dist/server/ask-user-question-tool.js +94 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/attachments.js +55 -0
  13. package/dist/server/bash-tool.js +83 -0
  14. package/dist/server/bg-servers.js +82 -2
  15. package/dist/server/browser-page-tool.js +207 -0
  16. package/dist/server/claim-files-tool.js +4 -4
  17. package/dist/server/client-id-utils.js +51 -0
  18. package/dist/server/client-state.js +63 -1
  19. package/dist/server/compact-context-tool.js +10 -9
  20. package/dist/server/compaction-markers.js +34 -1
  21. package/dist/server/context-budget-runner.js +43 -0
  22. package/dist/server/conversation-read-tool.js +7 -8
  23. package/dist/server/conversation-touches.js +19 -0
  24. package/dist/server/dangling-tools.js +18 -5
  25. package/dist/server/delegate-mode.js +1 -0
  26. package/dist/server/delegate-task.js +10 -14
  27. package/dist/server/dispatch-domain-handlers.js +631 -0
  28. package/dist/server/dispatch-plugin-handlers.js +300 -0
  29. package/dist/server/dsh/dsh-agent-service.js +125 -13
  30. package/dist/server/edit-soft-tool.js +10 -12
  31. package/dist/server/eval-tool.js +4 -5
  32. package/dist/server/goal-evidence.js +180 -0
  33. package/dist/server/goal-service.js +49 -9
  34. package/dist/server/hashline-engine.js +199 -32
  35. package/dist/server/index.js +212 -944
  36. package/dist/server/left-panel-running.js +115 -0
  37. package/dist/server/load-tools-tool.js +100 -0
  38. package/dist/server/lsp-tool.js +50 -28
  39. package/dist/server/marker-service.js +53 -12
  40. package/dist/server/markers/builtins/action.js +108 -0
  41. package/dist/server/markers/index.js +4 -1
  42. package/dist/server/markers-list-tool.js +34 -0
  43. package/dist/server/market-service.js +277 -0
  44. package/dist/server/mcp-bridge.js +137 -30
  45. package/dist/server/mcp-hot-reload.js +84 -27
  46. package/dist/server/mcp-manager.js +215 -0
  47. package/dist/server/message-entry-resolver.js +32 -0
  48. package/dist/server/orphan-manager.js +44 -0
  49. package/dist/server/patch-remote-catalog.js +28 -10
  50. package/dist/server/patch-tool.js +9 -8
  51. package/dist/server/persona-chain.js +63 -0
  52. package/dist/server/plan-mode.js +9 -6
  53. package/dist/server/plan-update-tool.js +96 -0
  54. package/dist/server/plugin-api-catalog.js +30 -3
  55. package/dist/server/plugin-conversation-view.js +47 -0
  56. package/dist/server/plugin-facilities.js +13 -3
  57. package/dist/server/plugin-ui-slots.js +39 -0
  58. package/dist/server/plugins.js +183 -63
  59. package/dist/server/present-files-tool.js +10 -11
  60. package/dist/server/preset-fields.js +700 -0
  61. package/dist/server/preset-share.js +1179 -0
  62. package/dist/server/process-utils.js +30 -0
  63. package/dist/server/prompt-assembler.js +80 -0
  64. package/dist/server/prompt-composer.js +23 -9
  65. package/dist/server/protocol-version.js +1 -1
  66. package/dist/server/read-tool.js +8 -10
  67. package/dist/server/resolve-global-sdk.js +80 -18
  68. package/dist/server/schedule-agent-tool.js +147 -146
  69. package/dist/server/scm-commitmsg.js +74 -0
  70. package/dist/server/sdk-origin.js +125 -37
  71. package/dist/server/serialize.js +97 -7
  72. package/dist/server/session-branch.js +367 -0
  73. package/dist/server/session-parser.js +235 -0
  74. package/dist/server/session-search.js +158 -0
  75. package/dist/server/settings-service.js +115 -84
  76. package/dist/server/skill-content-filler.js +33 -0
  77. package/dist/server/skill-tool.js +3 -4
  78. package/dist/server/subagent-handoff.js +18 -0
  79. package/dist/server/subagent-helpers.js +88 -0
  80. package/dist/server/subagents.js +15 -22
  81. package/dist/server/terminals.js +171 -91
  82. package/dist/server/tool-approval.js +3 -1
  83. package/dist/server/tool-guards.js +527 -0
  84. package/dist/server/tool-host-factories.js +217 -0
  85. package/dist/server/tool-manager.js +84 -23
  86. package/dist/server/tool-prompt-overrides.js +158 -0
  87. package/dist/server/tool-prompts.js +42 -0
  88. package/dist/server/tool-signature.js +104 -0
  89. package/dist/server/wait-subscription-scan.js +46 -1
  90. package/dist/server/workspace-snapshot.js +60 -11
  91. package/extensions/webui.ts +90 -24
  92. package/package.json +5 -3
  93. package/plugin-sdk/README.md +25 -4
  94. package/plugin-sdk/import-check.mjs +210 -0
  95. package/plugin-sdk/index.d.ts +21 -1
  96. package/plugin-sdk/index.mjs +6 -0
  97. package/plugins/catalog.json +53 -2
  98. package/themes/aetheris.css +3 -1
  99. package/themes/translucent.css +8 -1
  100. package/themes/transparent.css +9 -1
  101. package/themes/zhupi-dark.css +1 -1
  102. package/themes/zhupi.css +1 -1
  103. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
  104. package/web/dist/assets/index-CpjA1YdT.css +1 -0
  105. package/web/dist/assets/index-nKn87VuM.js +678 -0
  106. package/web/dist/index.html +2 -2
  107. package/web/dist/sw.js +1 -1
  108. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  109. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -704,3 +704,58 @@ ${transcript}
704
704
  }
705
705
  return out;
706
706
  }
707
+ /**
708
+ * 判断一个会话 entry 是否是提问前置注入的 aside 卡片(附件/并行提醒等)。
709
+ * 这些消息由服务端的 prompt 前置阶段通过 sendCustomMessage 注入在用户提问消息之前。
710
+ */
711
+ export function isPromptAsideEntry(entry) {
712
+ if (!entry || typeof entry !== "object")
713
+ return false;
714
+ const e = entry;
715
+ const customType = e.customType ?? (e.type === "message" && e.message?.role === "custom" ? e.message.customType : undefined);
716
+ return ((e.type === "custom_message" || (e.type === "message" && e.message?.role === "custom")) &&
717
+ (customType === "file" || customType === "parallel-work-reminder"));
718
+ }
719
+ /**
720
+ * 判断一个 entry 是否为用户提问消息。
721
+ */
722
+ export function isUserMessageEntry(entry) {
723
+ if (!entry || typeof entry !== "object")
724
+ return false;
725
+ const e = entry;
726
+ return (e.type === "message" && e.message?.role === "user") || e.type === "user" || e.role === "user";
727
+ }
728
+ /**
729
+ * 从给定的 entry 节点开始,向上追溯属于该轮提问的前置附件 aside 节点(customType === "file" 等),
730
+ * 返回该轮提问之前的基准 entry id(作为 fork/分支截断点)。
731
+ * 如果追溯到会话根(即该提问是会话第一轮提问),返回 null。
732
+ */
733
+ export function findTurnBaseEntryId(sm, entryId) {
734
+ const target = sm.getEntry(entryId);
735
+ if (!target)
736
+ return null;
737
+ // 只有针对用户消息,才需要向上跳过属于该提问的前置附件 aside 卡片
738
+ if (!isUserMessageEntry(target)) {
739
+ const parentId = target.parentId;
740
+ return parentId ?? null;
741
+ }
742
+ let currentId = entryId;
743
+ while (currentId) {
744
+ const entry = sm.getEntry(currentId);
745
+ if (!entry)
746
+ break;
747
+ const parentId = entry.parentId;
748
+ if (!parentId)
749
+ return null;
750
+ const parentEntry = sm.getEntry(parentId);
751
+ if (!parentEntry)
752
+ return null;
753
+ if (isPromptAsideEntry(parentEntry)) {
754
+ currentId = parentId;
755
+ }
756
+ else {
757
+ return parentId;
758
+ }
759
+ }
760
+ return null;
761
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * bash-tool — bash 工具的原生可中断版本与动态终端分流版本。
3
+ *
4
+ * - makeKillableBashTool: 包装 SDK 原生进程版 bash,带 AbortController 集合与 head/tail 后处理。
5
+ * - makeAdaptiveBashTool: 根据用户设置在进程版与可见终端版之间动态分流执行。
6
+ *
7
+ * 从 agent-service.ts 抽出为独立模块。
8
+ */
9
+ import { createBashToolDefinition, createLocalBashOperations, } from "@earendil-works/pi-coding-agent";
10
+ import { applyHeadTail } from "./terminals.js";
11
+ import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
12
+ /**
13
+ * Killable bash tool: wraps the SDK bash tool (native process spawn, NO terminal).
14
+ * Used when the「默认 bash 覆盖」setting is OFF. Registers its own AbortController
15
+ * into a client-level set (kills) so abortBash() kills only these commands while the
16
+ * agent run and the conversation continue. Exposes persist (ignored — native has no
17
+ * terminal) plus head/tail (post-processed on the returned output) so the parameter
18
+ * schema stays consistent with the terminal-backed tool.
19
+ */
20
+ export function makeKillableBashTool(cwd, kills,
21
+ /** per-call 返回文本的服务端语言(默认英文);工具 definition 为纯英文。 */
22
+ lang = () => "en") {
23
+ const base = createLocalBashOperations();
24
+ const tool = createBashToolDefinition(cwd, {
25
+ operations: {
26
+ exec: async (command, c, opts) => {
27
+ const ac = new AbortController();
28
+ kills.add(ac);
29
+ try {
30
+ const signals = [opts.signal, ac.signal].filter((s) => s !== undefined);
31
+ return await base.exec(command, c, {
32
+ ...opts,
33
+ signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0],
34
+ });
35
+ }
36
+ finally {
37
+ kills.delete(ac);
38
+ }
39
+ },
40
+ },
41
+ });
42
+ // Keep the SDK definition so execute receives the current session context.
43
+ return {
44
+ name: tool.name,
45
+ label: tool.label,
46
+ description: BASH_DESCRIPTION,
47
+ promptSnippet: BASH_PROMPT_SNIPPET,
48
+ promptGuidelines: BASH_PROMPT_GUIDELINES,
49
+ parameters: BASH_PARAMETERS,
50
+ prepareArguments: tool.prepareArguments,
51
+ executionMode: tool.executionMode,
52
+ execute: async (toolCallId, params, signal, onUpdate, ctx) => {
53
+ const result = (await tool.execute(toolCallId, params, signal, onUpdate, ctx));
54
+ // head/tail 后处理(native 无终端,直接截返回行即可)。
55
+ const p = params;
56
+ if ((p?.head || p?.tail) && result?.content?.[0]?.text != null) {
57
+ result.content[0].text = applyHeadTail(result.content[0].text, p.head, p.tail, lang());
58
+ }
59
+ return result;
60
+ },
61
+ };
62
+ }
63
+ /**
64
+ * 动态分流 bash:按「默认 bash 覆盖」设置(terminalBash)在调用时决定走哪套——
65
+ * 关 = 原生 SDK bash(纯进程、不开终端);开 = 终端接管 bash(persist 决定一次性/
66
+ * 持久)。开关因此即时生效(customTools 固定于 runtime 创建,不能在创建时二选一)。
67
+ *
68
+ * 提示词不在此覆盖:两条路径共用 server/tool-prompts.ts 的那一份(单源),
69
+ * 覆盖 description 正是当年终端版文案被写死却不生效的成因。
70
+ */
71
+ export function makeAdaptiveBashTool(killable, terminalBacked, useTerminal) {
72
+ return {
73
+ ...killable,
74
+ execute: (id, params, signal, onUpdate, ctx) => {
75
+ const p = params;
76
+ // Windows 下 ConPTY 架构限制(MSYS2 全局控制台上限 128,且高频创建销毁容易句柄耗尽/卡顿):
77
+ // 一次性命令(persist !== true)走原生 spawn(基于 pipe,无需分配控制台,速度快 60 倍且免死锁,issue #269);
78
+ // 只有明确需要持久交互(persist === true)才进可见终端 ai-bash。
79
+ const shouldUseTerminal = useTerminal() && (process.platform !== "win32" || p?.persist === true);
80
+ return (shouldUseTerminal ? terminalBacked : killable).execute(id, params, signal, onUpdate, ctx);
81
+ },
82
+ };
83
+ }
@@ -2,6 +2,22 @@ import { killPidTree, lookupProcessName, lookupProcessCommandLine, snapshotListe
2
2
  const BG_REFRESH_INTERVAL_MS = 30_000;
3
3
  /** bash 结束后等这么久再拍「后」快照——给后台服务绑定端口的时间。 */
4
4
  const BG_BIND_WAIT_MS = 1500;
5
+ /** 自动清理时「闲置多久算遗留」的兜底阈值(分钟)——手动「立即清理」在策略为关时用它。 */
6
+ export const BG_CLEANUP_FALLBACK_MIN = 30;
7
+ /**
8
+ * 从当前列表里挑出「该被自动清理」的条目(纯函数,好测):
9
+ * - **钉住的(keep)不碰** —— 用户明确说要留的,永远不动;
10
+ * - 插件注册的任务不参与(它们不在这个列表里,由插件的 stop 回调负责);
11
+ * - 只看 `since`(宿主首次发现它的时间)与阈值,与是否还在跑无关(还在跑才会在列表里)。
12
+ * @param entries `{port, pid, since, keep?}` 列表
13
+ * @param opts `{ now, thresholdMs }`;thresholdMs ≤ 0 = 不清理
14
+ * @returns 待清理的条目(原样引用)
15
+ */
16
+ export function staleLeftovers(entries, opts) {
17
+ if (!Number.isFinite(opts.thresholdMs) || opts.thresholdMs <= 0)
18
+ return [];
19
+ return entries.filter((e) => !e.keep && Number.isFinite(e.since) && opts.now - e.since >= opts.thresholdMs);
20
+ }
5
21
  /**
6
22
  * 基本不可能由 AI 启动的常驻桌面软件进程名(小写)。命中即跳过,避免面板被
7
23
  * 微信/QQ 等本地软件的动态监听端口污染。注意 Chrome 不进黑名单:AI 会用
@@ -78,11 +94,19 @@ export class BgServerTracker {
78
94
  constructor(opts) {
79
95
  this.opts = opts;
80
96
  }
81
- /** 启动周期性存活检查(死项静默剔除)。 */
97
+ /** 启动周期性存活检查(死项静默剔除)+ 按策略自动清理遗留实例。 */
82
98
  start() {
83
- this.refreshTimer = setInterval(() => void this.refresh(), BG_REFRESH_INTERVAL_MS);
99
+ this.refreshTimer = setInterval(() => void this.tick(), BG_REFRESH_INTERVAL_MS);
84
100
  this.refreshTimer.unref?.();
85
101
  }
102
+ /** 一轮定时任务:先剔死项,再按策略清遗留(策略为 0 = 关,只剔不杀)。 */
103
+ async tick() {
104
+ await this.refresh();
105
+ const minutes = Number(this.opts.cleanupMinutes?.() ?? 0);
106
+ if (!Number.isFinite(minutes) || minutes <= 0)
107
+ return;
108
+ await this.cleanStale(minutes * 60_000, { manual: false });
109
+ }
86
110
  stop() {
87
111
  if (this.refreshTimer) {
88
112
  clearInterval(this.refreshTimer);
@@ -171,6 +195,7 @@ export class BgServerTracker {
171
195
  since: v.since,
172
196
  ...(v.name ? { name: v.name } : {}),
173
197
  ...(v.command ? { command: v.command } : {}),
198
+ ...(v.keep ? { keep: true } : {}),
174
199
  }))
175
200
  .sort((a, b) => a.since - b.since);
176
201
  for (const t of this.opts.pluginTasks?.() ?? [])
@@ -258,6 +283,61 @@ export class BgServerTracker {
258
283
  this.opts.flushSnapshot();
259
284
  return true;
260
285
  }
286
+ /** 钉住 / 取消钉住一个实例(自动清理跳过钉住的)。端口不在列表里 → 回一条 info 通知。 */
287
+ setKeep(port, keep) {
288
+ const entry = this.servers.get(port);
289
+ if (!entry) {
290
+ this.opts.emit({
291
+ type: "notice",
292
+ level: "info",
293
+ text: `端口 ${port} 不在后台任务列表中(可能已自行退出)`,
294
+ textEn: `Port ${port} is not in the background task list (it may have exited)`,
295
+ });
296
+ this.opts.flushSnapshot();
297
+ return false;
298
+ }
299
+ if (keep)
300
+ entry.keep = true;
301
+ else
302
+ delete entry.keep;
303
+ this.push();
304
+ return true;
305
+ }
306
+ /**
307
+ * 按阈值清理遗留实例:先复核端口→pid 归属(同 killOne,不对就剔条目绝不误杀),
308
+ * 再杀**未钉住**且闲置超阈值的那些,最后推一条汇总通知。
309
+ * @param manual 手动点「立即清理」:即使没东西可清也给一句反馈(否则点了像没反应)。
310
+ */
311
+ async cleanStale(thresholdMs, opts) {
312
+ await this.verifyBeforeKill();
313
+ const picked = staleLeftovers([...this.servers.entries()].map(([port, v]) => ({ port, ...v })), { now: Date.now(), thresholdMs });
314
+ if (picked.length === 0) {
315
+ if (opts.manual) {
316
+ this.opts.emit({
317
+ type: "notice",
318
+ level: "info",
319
+ text: `没有需要清理的遗留实例(阈值 ${Math.round(thresholdMs / 60_000)} 分钟,已钉住的不算)`,
320
+ textEn: `No leftover instance to clean (threshold ${Math.round(thresholdMs / 60_000)} min; kept ones excluded)`,
321
+ });
322
+ }
323
+ return [];
324
+ }
325
+ const killed = [];
326
+ for (const item of picked) {
327
+ killPidTree(item.pid);
328
+ this.servers.delete(item.port);
329
+ killed.push(item.port);
330
+ }
331
+ this.push();
332
+ this.opts.emit({
333
+ type: "notice",
334
+ level: "info",
335
+ text: `已清理 ${killed.length} 个遗留后台实例:端口 ${killed.join("、")}(闲置超 ${Math.round(thresholdMs / 60_000)} 分钟;可在面板里钉住想留的)`,
336
+ textEn: `Cleaned ${killed.length} leftover background instance(s): port ${killed.join(", ")} (idle over ${Math.round(thresholdMs / 60_000)} min; pin the ones you want to keep)`,
337
+ });
338
+ this.opts.flushSnapshot();
339
+ return killed;
340
+ }
261
341
  /** Kill every background server the agent started; returns the freed ports. */
262
342
  async killAll() {
263
343
  if (this.servers.size === 0)
@@ -0,0 +1,207 @@
1
+ /**
2
+ * 浏览器页面工具(标准 pi 引擎的 browser_page customTool)
3
+ *
4
+ * 模型调 browser_page → 服务端发 page_request 给浏览器 → 前端转 page-picker
5
+ * 扩展 → 扩展操作目标页面 → 前端回 page_response → 工具结果回到模型。
6
+ *
7
+ * op 的语义(read/click/type/…)属于**扩展侧**,服务端只透传,不解读也不校验
8
+ * ——所以参数说明写在 tool description 里让模型知道怎么用,不在这里分支处理。
9
+ *
10
+ * 从 agent-service.ts 抽出为独立模块。
11
+ */
12
+ import { Type } from "typebox";
13
+ import { BROWSER_PAGE_TOOL_NAME } from "./tool-manager.js";
14
+ /** timeoutMs 默认值。对面是扩展不是人,超时必须自己兜住。 */
15
+ const PAGE_CALL_DEFAULT_TIMEOUT_MS = 30_000;
16
+ /** 夹取区间:太小会误杀慢页面(拿不到结果还白跑一趟),太大就把模型拖到
17
+ * 工具看门狗(20 分钟)附近了。 */
18
+ const PAGE_CALL_MIN_TIMEOUT_MS = 1_000;
19
+ const PAGE_CALL_MAX_TIMEOUT_MS = 120_000;
20
+ /** timeoutMs 归一:非有限数字/缺省 → 默认;其余夹在 [1000, 120000]。
21
+ * 工具入口与页桥(pageCall)共用,防手写脏值绕过 schema。 */
22
+ export function normalizePageCallTimeoutMs(v) {
23
+ const n = typeof v === "number" && Number.isFinite(v) ? Math.floor(v) : PAGE_CALL_DEFAULT_TIMEOUT_MS;
24
+ return Math.min(PAGE_CALL_MAX_TIMEOUT_MS, Math.max(PAGE_CALL_MIN_TIMEOUT_MS, n));
25
+ }
26
+ /** 除 op/target/timeoutMs 外的扁平参数名(保持扩展侧原名:what/selector/…)。
27
+ * 列表即 schema 里的可选字段——改 schema 忘改这里,单测会炸(见
28
+ * tests/unit/browser-page-tool.test.ts)。 */
29
+ const BROWSER_PAGE_ARG_KEYS = ["what", "selector", "text", "url", "code", "all", "index", "maxEdge"];
30
+ /** 只收模型**确实传了**的参数:undefined 不入包,否则扩展拿到一堆
31
+ * `"selector": undefined` 会覆盖自己的默认值。 */
32
+ export function collectBrowserPageArgs(params) {
33
+ const args = {};
34
+ for (const k of BROWSER_PAGE_ARG_KEYS) {
35
+ if (params[k] !== undefined)
36
+ args[k] = params[k];
37
+ }
38
+ return args;
39
+ }
40
+ /** 页面调用结果 → 给模型的文本:字符串原样(read 的正文就是这样,别再加引号),
41
+ * 其余 JSON 缩进;空结果给一句说明,免得模型以为工具没输出。 */
42
+ export function formatPageCallResult(result) {
43
+ if (typeof result === "string")
44
+ return result.length > 0 ? result : "(empty)";
45
+ if (result === undefined || result === null)
46
+ return "(no result)";
47
+ try {
48
+ return JSON.stringify(result, null, 2) ?? String(result);
49
+ }
50
+ catch {
51
+ // 循环引用/含大整数等不可序列化结果:别让格式化把工具调用炸掉。
52
+ return String(result);
53
+ }
54
+ }
55
+ /** 失败文本:带上 op 与原因,再补一句**可执行的**下一步(模型只有知道该让
56
+ * 用户干什么,才不会再盲目重试同一个调用)。 */
57
+ export function formatBrowserPageError(op, error) {
58
+ return [
59
+ `browser_page "${op}" failed: ${error}`,
60
+ `browser_page "${op}" 失败:${error}`,
61
+ 'Next: make sure a pi-web-ui page is open with the page-picker extension enabled and paired, then try op:"pages" to see which pages are available. If the target page is not allowed yet, ask the user to allow it in the extension.',
62
+ '下一步:确认 pi-web-ui 页面已打开、page-picker 扩展已启用并与该页面配对,再用 op:"pages" 看有哪些可操作页面;若目标页面尚未授权,请让用户先在扩展里授权。',
63
+ ].join("\n");
64
+ }
65
+ /**
66
+ * 标准 pi 引擎的 browser_page 工具:模型调用时把请求桥到用户浏览器里的
67
+ * pi-web-ui 页面(page_request/page_response 协议),由 page-picker 扩展真正
68
+ * 操作用户授权的页面。
69
+ *
70
+ * 与 ask_user_question 同样以 customTool 注册(标准 SDK 没有这个工具;DSH 引擎
71
+ * 走自己的运行时,也不经此)。写法严格比照 makeAskUserQuestionTool。
72
+ *
73
+ * pageCall 签名同样带 {aborted} 快照而非完整 AbortSignal(customTool 的 execute
74
+ * 信号服务于整个 agent 生命周期,这里只要「已中止即失败」的最小语义)。
75
+ */
76
+ export function makeBrowserPageTool(clientSession,
77
+ /** 本 runtime 所属会话(语义与 ask_user_question 的 ownerId 一致)。 */
78
+ ownerId) {
79
+ return {
80
+ name: BROWSER_PAGE_TOOL_NAME,
81
+ label: "Browser page",
82
+ description: [
83
+ "Read or act on a page in the USER'S OWN browser via the pi-web-ui page-picker extension (the server only forwards).",
84
+ "Only the parameters below exist — an op option that is not a field here (e.g. type's submit) is unavailable.",
85
+ "ops: pages | read (what? selector? all?) | click (selector? index?) | type (selector text) | scroll (selector?) | goto (url) | wait (selector? text? timeoutMs?) | eval (code) | shot (maxEdge?)",
86
+ ].join("\n"),
87
+ promptSnippet: "operate a page in the user's browser (page-picker extension)",
88
+ promptGuidelines: [
89
+ "Only use browser_page when the user asked you to read or act on a page in their browser; " +
90
+ "never click or type on their pages on your own initiative",
91
+ 'Start with op:"pages"; the target page must already be allowed in the page-picker extension — ' +
92
+ "if it fails, tell the user what to enable instead of retrying.",
93
+ ],
94
+ parameters: Type.Object({
95
+ op: Type.String({
96
+ description: "Action to perform (extension-side).",
97
+ }),
98
+ target: Type.Optional(Type.String({
99
+ description: "Target page origin (e.g. https://example.com). Only needed when several pages are allowed.",
100
+ })),
101
+ what: Type.Optional(Type.String({ description: 'For op:read — "text" | "html" | "title" | "url" | "query" (default: text).' })),
102
+ selector: Type.Optional(Type.String({ description: "CSS selector, for op:read / click / type / scroll / wait." })),
103
+ text: Type.Optional(Type.String({ description: "For op:type — the text to enter; for op:wait — the text to wait for." })),
104
+ url: Type.Optional(Type.String({ description: "For op:goto — the absolute URL to navigate to." })),
105
+ code: Type.Optional(Type.String({
106
+ description: "For op:eval — JS to run in the page (extension-side switch, disabled by default).",
107
+ })),
108
+ all: Type.Optional(Type.Boolean({ description: "For op:read — return every match instead of only the first one." })),
109
+ index: Type.Optional(Type.Number({ description: "For op:click — which match to click (default: 0)." })),
110
+ maxEdge: Type.Optional(Type.Number({
111
+ description: "For op:shot — max px of the longer side (320-1568, default 1280).",
112
+ })),
113
+ timeoutMs: Type.Optional(Type.Number({
114
+ description: "How long the server waits for the browser (1000-120000 ms, default 30000).",
115
+ })),
116
+ }),
117
+ execute: async (_id, params, signal) => {
118
+ const p = (params ?? {});
119
+ const op = typeof p.op === "string" ? p.op.trim() : "";
120
+ if (!op) {
121
+ throw new Error('browser_page requires a non-empty `op` (e.g. "pages", "read", "click").\nbrowser_page 需要非空的 op(如 pages/read/click)。');
122
+ }
123
+ const resolved = await clientSession.pageCall({
124
+ op,
125
+ args: collectBrowserPageArgs(p),
126
+ target: typeof p.target === "string" && p.target.length > 0 ? p.target : undefined,
127
+ timeoutMs: normalizePageCallTimeoutMs(p.timeoutMs),
128
+ }, {
129
+ aborted: signal?.aborted,
130
+ }, ownerId);
131
+ if (!resolved.ok) {
132
+ // 抛 Error 而不是回一段失败文本:模型需要看到「工具失败」才会改策略。
133
+ throw new Error(formatBrowserPageError(op, resolved.error));
134
+ }
135
+ const shot = extractShotImage(resolved.result);
136
+ if (!shot) {
137
+ // 工具结果:read 的正文原样给模型,结构化结果 JSON 缩进;details 留 UI/轨迹。
138
+ return {
139
+ content: [{ type: "text", text: formatPageCallResult(resolved.result) }],
140
+ details: { op, args: collectBrowserPageArgs(p), target: p.target, result: resolved.result },
141
+ };
142
+ }
143
+ // 截图:**主模型能看图就直接把图给回去**(当轮就能看到,不用等下一轮);
144
+ // 看不到图(纯文本模型)就交给视觉桥转写成文字证据 —— 与用户粘贴图片走同一套
145
+ // 选择逻辑与提示词,设置里开着就自动生效,模型侧不需要任何额外配置。
146
+ const where = `${p.target ?? "the page"}${shot.selector ? ` (element ${shot.selector})` : ""}`;
147
+ const caption = [
148
+ `Screenshot of ${where} — ${shot.width ?? "?"}×${shot.height ?? "?"} px.`,
149
+ `页面截图:${where} — ${shot.width ?? "?"}×${shot.height ?? "?"} px。`,
150
+ ].join("\n");
151
+ const details = {
152
+ op,
153
+ args: collectBrowserPageArgs(p),
154
+ target: p.target,
155
+ result: { ...resolved.result, image: "[image]" },
156
+ };
157
+ if (clientSession.canSeeImages?.() === true) {
158
+ return {
159
+ content: [
160
+ { type: "text", text: caption },
161
+ { type: "image", data: shot.data, mimeType: shot.mimeType },
162
+ ],
163
+ details,
164
+ };
165
+ }
166
+ const bridged = await clientSession.transcribeToolImage?.(shot, signal);
167
+ const note = bridged?.text
168
+ ? `\n\n<vision-bridge>\n${bridged.text}\n</vision-bridge>`
169
+ : [
170
+ `\n\n(当前模型看不到图片:${bridged?.reason ?? "视觉桥不可用"} —— 可让用户改用支持识图的模型,或在模型配置里加一个支持图片的模型)`,
171
+ `(The current model cannot see images: ${bridged?.reason ?? "vision bridge unavailable"})`,
172
+ ].join("\n");
173
+ return {
174
+ content: [{ type: "text", text: caption + note }],
175
+ details,
176
+ };
177
+ },
178
+ };
179
+ }
180
+ /**
181
+ * 从扩展的截图结果里取出图片。
182
+ *
183
+ * 扩展回的是 `{ image: { dataUrl, mimeType, width, height }, selector?, rect?, viewport? }`;
184
+ * dataUrl 带 `data:image/jpeg;base64,` 前缀,而模型 API 要的是**纯 base64** —— 剥前缀这一步
185
+ * 很容易忘(忘了就是「图片解析失败」)。
186
+ */
187
+ export function extractShotImage(result) {
188
+ if (!result || typeof result !== "object")
189
+ return undefined;
190
+ const image = result.image;
191
+ if (!image || typeof image !== "object")
192
+ return undefined;
193
+ const src = image;
194
+ if (typeof src.dataUrl !== "string")
195
+ return undefined;
196
+ const match = /^data:([^;,]+);base64,(.+)$/s.exec(src.dataUrl);
197
+ if (!match)
198
+ return undefined;
199
+ const selector = result.selector;
200
+ return {
201
+ data: match[2],
202
+ mimeType: typeof src.mimeType === "string" && src.mimeType ? src.mimeType : match[1],
203
+ ...(typeof src.width === "number" ? { width: src.width } : {}),
204
+ ...(typeof src.height === "number" ? { height: src.height } : {}),
205
+ ...(typeof selector === "string" && selector ? { selector } : {}),
206
+ };
207
+ }
@@ -30,10 +30,10 @@ export function makeClaimFilesTool(host, lang) {
30
30
  return defineTool({
31
31
  name: CLAIM_FILES_TOOL_NAME,
32
32
  label: "Claim files to avoid parallel conflicts",
33
- description: "Declare files you are about to edit so parallel runs in the same project steer clear (advisory only — never blocks edits). " +
34
- "claim reserves paths for THIS conversation (first wins; conflicts reported, not overridden); release frees yours (no paths = all yours); list shows the project's claim table. " +
35
- "Claims expire after ~30 min idle (your prompts refresh them) and release when the conversation closes. Paths must stay inside the project.",
36
- promptSnippet: "claim files you are about to edit (advisory, first-wins) so parallel runs steer clear",
33
+ description: "Declare files you are about to edit so parallel runs in the same project steer clear (advisory — never blocks edits). " +
34
+ "Claims expire after ~30 min idle (your prompts refresh them) and release when the conversation closes. " +
35
+ "Paths must stay inside the project.",
36
+ promptSnippet: "reserve files you are about to edit (parallel-run guard)",
37
37
  parameters: Type.Object({
38
38
  action: Type.Optional(Type.String({ description: 'claim = reserve paths; release = free yours; list = show table. Default "list".' })),
39
39
  paths: Type.Optional(Type.Array(Type.String(), { description: "claim/release only: file paths (inside the project)." })),
@@ -0,0 +1,51 @@
1
+ /**
2
+ * client-id-utils — 伪客户端 ID 判断与插件调用工作区校验。
3
+ *
4
+ * 负责:
5
+ * - isPseudoClientId: 判断是否为插件或定时任务的无头伪客户端(sink 常驻)
6
+ * - checkPluginCwd: 校验插件指定的工作目录合法性(防止 Windows SystemRoot 误操作)
7
+ *
8
+ * 从 agent-service.ts 抽出为独立模块。
9
+ */
10
+ import { statSync } from "node:fs";
11
+ import { resolve, sep } from "node:path";
12
+ /** issue #226:插件无头调用的工作目录校验(纯函数,可单测)。
13
+ * 存在性语义与定时任务一致(须存在且为目录,不默默跑错目录);另在
14
+ * Windows 下拒绝 SystemRoot 及其子树(如 C:\Windows\System32)——后台服务/
15
+ * 快捷方式启动时宿主 cwd 常飘到 system32,直接跑就是高危误操作。 */
16
+ export function checkPluginCwd(cwd) {
17
+ const trimmed = String(cwd ?? "").trim();
18
+ if (!trimmed)
19
+ return { ok: false, error: "工作目录为空" };
20
+ let abs;
21
+ try {
22
+ abs =
23
+ process.platform === "win32" && /^[A-Za-z]:$/.test(trimmed) ? `${trimmed.toUpperCase()}${sep}` : resolve(trimmed);
24
+ }
25
+ catch {
26
+ return { ok: false, error: `工作目录非法:${trimmed}` };
27
+ }
28
+ try {
29
+ if (!statSync(abs).isDirectory())
30
+ throw new Error("not-a-dir");
31
+ }
32
+ catch {
33
+ return { ok: false, error: `目标项目不存在或不是目录:${trimmed}` };
34
+ }
35
+ if (process.platform === "win32") {
36
+ const sysRoot = (process.env.SystemRoot || process.env.windir || "C:\\Windows")
37
+ .replace(/\//g, "\\")
38
+ .replace(/\\+$/, "");
39
+ const norm = abs.replace(/\//g, "\\").replace(/\\+$/, "");
40
+ const low = norm.toLowerCase();
41
+ const rootLow = sysRoot.toLowerCase();
42
+ if (low === rootLow || low.startsWith(`${rootLow}\\`)) {
43
+ return { ok: false, error: `拒绝在系统目录执行:${abs}(请在插件设置里指定项目工作目录)` };
44
+ }
45
+ }
46
+ return { ok: true, abs };
47
+ }
48
+ /** 插件/调度伪客户端:sink 常驻(fire-and-forget 的空函数),不能按浏览器存活判断。 */
49
+ export function isPseudoClientId(id) {
50
+ return id.startsWith("plugin:") || id.startsWith("scheduler:");
51
+ }
@@ -12,7 +12,8 @@ import { dirname, isAbsolute, resolve } from "node:path";
12
12
  import { writeJsonAtomicSync } from "./atomic-file.js";
13
13
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { deriveLegacy, legacyToDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
15
- import { UI_SLOTS } from "./plugins.js";
15
+ import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
16
+ import { UI_SLOTS } from "./plugin-ui-slots.js";
16
17
  /** 大模型 API 出错自动重试次数的默认值(SDK 默认 3)。 */
17
18
  export const DEFAULT_RETRY_MAX_ATTEMPTS = 6;
18
19
  /** 工具执行看门狗超时的默认值(默认 20 分钟;环境变量 PI_WEB_TOOL_TIMEOUT_MS 覆盖)。 */
@@ -20,6 +21,25 @@ export const DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS = (() => {
20
21
  const v = Number(process.env.PI_WEB_TOOL_TIMEOUT_MS);
21
22
  return Number.isFinite(v) && v >= 0 ? v : 20 * 60_000;
22
23
  })();
24
+ /** 消息列表尾部「常驻渲染」消息条数的默认值:更早的消息折叠为摘要行
25
+ * (见 web/src/components/MessageList.tsx 的 recentStart)。默认与原硬编码
26
+ * KEEP_RECENT 一致(15),想要更大窗口在设置面板「常驻渲染消息数」里开。纯 UI 偏好。 */
27
+ export const DEFAULT_KEEP_RECENT_MESSAGES = 15;
28
+ export const KEEP_RECENT_MESSAGES_MIN = 5;
29
+ export const KEEP_RECENT_MESSAGES_MAX = 100;
30
+ /** 归一化常驻渲染消息数:缺省/非数值回落默认值;有效整数钳到 [5, 100]。 */
31
+ export function normalizeKeepRecentMessages(v) {
32
+ if (v === null || v === undefined || v === "")
33
+ return DEFAULT_KEEP_RECENT_MESSAGES;
34
+ const n = Math.floor(Number(v));
35
+ if (!Number.isFinite(n))
36
+ return DEFAULT_KEEP_RECENT_MESSAGES;
37
+ if (n < KEEP_RECENT_MESSAGES_MIN)
38
+ return KEEP_RECENT_MESSAGES_MIN;
39
+ if (n > KEEP_RECENT_MESSAGES_MAX)
40
+ return KEEP_RECENT_MESSAGES_MAX;
41
+ return n;
42
+ }
23
43
  /** 归一化工具看门狗超时(毫秒):0 = 禁用;非数值、负数或空值回落默认值,非负整数保留。 */
24
44
  export function normalizeToolWatchdogTimeoutMs(v) {
25
45
  if (v === null || v === undefined || v === "")
@@ -29,6 +49,20 @@ export function normalizeToolWatchdogTimeoutMs(v) {
29
49
  return DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS;
30
50
  return n;
31
51
  }
52
+ /** 「后台任务」自动清理阈值的合法档位(分钟)。0 = 关。 */
53
+ export const BG_CLEANUP_MINUTES = [0, 15, 30, 60, 120];
54
+ /** 归一化自动清理阈值(分钟):只认档位表里的值(脏值按最近档位下取,负数/非数回落 0 = 关)。
55
+ * 默认关 —— 杀进程是破坏性动作,不替用户做主。 */
56
+ export function normalizeBgCleanupMinutes(v) {
57
+ const n = Math.floor(Number(v));
58
+ if (!Number.isFinite(n) || n <= 0)
59
+ return 0;
60
+ let best = 0;
61
+ for (const step of BG_CLEANUP_MINUTES)
62
+ if (step <= n && step > best)
63
+ best = step;
64
+ return best;
65
+ }
32
66
  /** 工具自己声明超时时留给它的余量(毫秒):让工具先自己超时并返回错误,
33
67
  * 而不是看门狗先下手把整轮对话 abort 掉。 */
34
68
  export const TOOL_WATCHDOG_EXPLICIT_GRACE_MS = 5_000;
@@ -216,6 +250,26 @@ export function normalizeUiLayout(v) {
216
250
  export function normalizeSkillList(v) {
217
251
  return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
218
252
  }
253
+ /** 工具延迟加载的**出厂默认**(默认开;`PI_WEB_TOOL_LAZY_LOADING=0/false/off` 部署级关掉,
254
+ * 给「不想让模型多一步 load_tools」的实例一个开关;用户在设置面板的选择优先于此)。 */
255
+ export const DEFAULT_TOOL_LAZY_LOADING = (() => {
256
+ const v = (process.env.PI_WEB_TOOL_LAZY_LOADING ?? "").trim().toLowerCase();
257
+ return !(v === "0" || v === "false" || v === "off" || v === "no");
258
+ })();
259
+ /** 预设 → 设置面板列表用的 UI 形状(协议要求字段完整:旧/部分预设用默认值补齐)。 */
260
+ export function settingsPresetToUi(p) {
261
+ return {
262
+ name: p.name,
263
+ promptMode: p.promptMode === "replace" ? "replace" : "append",
264
+ customSystemPrompt: p.customSystemPrompt ?? "",
265
+ promptTemplate: p.promptTemplate ?? "",
266
+ promptOverrides: { ...p.promptOverrides },
267
+ disabledSkills: [...(p.disabledSkills ?? [])],
268
+ disabledExtensions: [...(p.disabledExtensions ?? [])],
269
+ reviewPrompt: p.reviewPrompt ?? "",
270
+ reviewDisabledSkills: [...(p.reviewDisabledSkills ?? [])],
271
+ };
272
+ }
219
273
  /** Stable identity of an extension for the enable/disable toggle: the npm
220
274
  * spec for packages (survives version bumps), the resolved entry path
221
275
  * otherwise. */
@@ -721,6 +775,7 @@ export class ClientStateStore {
721
775
  customSystemPrompt: stored?.customSystemPrompt ?? "",
722
776
  promptTemplate,
723
777
  promptOverrides,
778
+ toolPromptOverrides: normalizeToolPromptOverrides(stored?.toolPromptOverrides),
724
779
  disabledSkills: stored?.disabledSkills ?? [],
725
780
  disabledExtensions: stored?.disabledExtensions ?? [],
726
781
  disabledAgentTools: legacyToDisabled(stored ?? {}),
@@ -734,6 +789,8 @@ export class ClientStateStore {
734
789
  terminalBashMaxForegroundMs: stored?.terminalBashMaxForegroundMs ?? 60_000,
735
790
  toolWatchdogTimeoutMs: normalizeToolWatchdogTimeoutMs(stored?.toolWatchdogTimeoutMs),
736
791
  readDirEnabled: stored?.readDirEnabled ?? true,
792
+ bgAutoCleanupMin: normalizeBgCleanupMinutes(stored?.bgAutoCleanupMin),
793
+ toolLazyLoading: stored?.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
737
794
  toolApprovalEnabled: stored?.toolApprovalEnabled ?? true,
738
795
  editSoftEnabled: stored?.disabledAgentTools !== undefined
739
796
  ? deriveLegacy(legacyToDisabled(stored)).editSoftEnabled
@@ -748,6 +805,7 @@ export class ClientStateStore {
748
805
  autoReload: stored?.autoReload,
749
806
  toolsWrap: stored?.toolsWrap ?? true,
750
807
  toolImagesEnabled: stored?.toolImagesEnabled ?? true,
808
+ keepRecentMessages: normalizeKeepRecentMessages(stored?.keepRecentMessages),
751
809
  skillsFullText: normalizeSkillList(stored?.skillsFullText),
752
810
  visionBridgeEnabled: stored?.visionBridgeEnabled ?? true,
753
811
  visionBridgeModel: stored?.visionBridgeModel ?? null,
@@ -785,6 +843,7 @@ export class ClientStateStore {
785
843
  customSystemPrompt: settings.customSystemPrompt ?? cur.customSystemPrompt ?? "",
786
844
  promptTemplate: settings.promptTemplate ?? cur.promptTemplate ?? "",
787
845
  promptOverrides: { ...(settings.promptOverrides ?? cur.promptOverrides) },
846
+ toolPromptOverrides: normalizeToolPromptOverrides(settings.toolPromptOverrides ?? cur.toolPromptOverrides),
788
847
  disabledSkills: settings.disabledSkills ?? cur.disabledSkills ?? [],
789
848
  disabledExtensions: settings.disabledExtensions ?? cur.disabledExtensions ?? [],
790
849
  disabledAgentTools: normalizeDisabledAgentTools(settings.disabledAgentTools ?? cur.disabledAgentTools),
@@ -795,6 +854,8 @@ export class ClientStateStore {
795
854
  terminalBashMaxForegroundMs: settings.terminalBashMaxForegroundMs ?? cur.terminalBashMaxForegroundMs ?? 60_000,
796
855
  toolWatchdogTimeoutMs: normalizeToolWatchdogTimeoutMs(settings.toolWatchdogTimeoutMs ?? cur.toolWatchdogTimeoutMs ?? DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS),
797
856
  readDirEnabled: settings.readDirEnabled ?? cur.readDirEnabled ?? true,
857
+ bgAutoCleanupMin: normalizeBgCleanupMinutes(settings.bgAutoCleanupMin ?? cur.bgAutoCleanupMin),
858
+ toolLazyLoading: settings.toolLazyLoading ?? cur.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
798
859
  toolApprovalEnabled: settings.toolApprovalEnabled ?? cur.toolApprovalEnabled ?? true,
799
860
  editSoftEnabled: settings.editSoftEnabled ?? cur.editSoftEnabled ?? false,
800
861
  questionnaireEnabled: settings.questionnaireEnabled ?? cur.questionnaireEnabled ?? true,
@@ -805,6 +866,7 @@ export class ClientStateStore {
805
866
  autoReload: settings.autoReload ?? cur.autoReload,
806
867
  toolsWrap: settings.toolsWrap ?? cur.toolsWrap ?? true,
807
868
  toolImagesEnabled: settings.toolImagesEnabled ?? cur.toolImagesEnabled ?? true,
869
+ keepRecentMessages: normalizeKeepRecentMessages(settings.keepRecentMessages ?? cur.keepRecentMessages ?? DEFAULT_KEEP_RECENT_MESSAGES),
808
870
  skillsFullText: normalizeSkillList(settings.skillsFullText ?? cur.skillsFullText),
809
871
  visionBridgeEnabled: settings.visionBridgeEnabled ?? cur.visionBridgeEnabled ?? true,
810
872
  // 按键存在性合并:null 是合法值(清除语义),`null ?? cur` 会把旧值