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
@@ -0,0 +1,115 @@
1
+ /** 单个插件同时可见的条目上限(超出的丢弃并给诊断)。 */
2
+ export const PANEL_ITEM_CAP = 50;
3
+ /** 心跳 TTL:缺省 60 秒(插件若不传 ttlMs)。 */
4
+ export const PANEL_TTL_DEFAULT_MS = 60_000;
5
+ /** TTL 夹取区间:过短会抖动,过长等于没有超时。 */
6
+ export const PANEL_TTL_MIN_MS = 5_000;
7
+ export const PANEL_TTL_MAX_MS = 3_600_000;
8
+ const ID_MAX = 96;
9
+ const TITLE_MAX = 200;
10
+ const HINT_MAX = 200;
11
+ const ICON_MAX = 8;
12
+ const ACTION_MAX = 96;
13
+ const STATUSES = new Set(["running", "done", "error"]);
14
+ /** 把插件传来的 `items` 清洗成可信的条目列表(纯函数)。不合法的条目丢弃,不抛错。 */
15
+ export function sanitizePanelItems(raw) {
16
+ const diags = [];
17
+ const items = [];
18
+ if (!Array.isArray(raw)) {
19
+ diags.push("setRunning: items must be an array — ignored");
20
+ return { items, diags };
21
+ }
22
+ const seen = new Set();
23
+ raw.forEach((rawItem, idx) => {
24
+ if (!rawItem || typeof rawItem !== "object") {
25
+ diags.push(`setRunning[#${idx}]: not an object — dropped`);
26
+ return;
27
+ }
28
+ const o = rawItem;
29
+ const id = typeof o.id === "string" ? o.id.trim().slice(0, ID_MAX) : "";
30
+ if (!id) {
31
+ diags.push(`setRunning[#${idx}]: missing id — dropped`);
32
+ return;
33
+ }
34
+ if (seen.has(id)) {
35
+ diags.push(`setRunning: duplicate id "${id}" — later one dropped`);
36
+ return;
37
+ }
38
+ if (items.length >= PANEL_ITEM_CAP) {
39
+ diags.push(`setRunning: capped at ${PANEL_ITEM_CAP} items — "${id}" and later dropped`);
40
+ return;
41
+ }
42
+ seen.add(id);
43
+ const title = typeof o.title === "string" && o.title.trim() ? o.title.trim().slice(0, TITLE_MAX) : id;
44
+ let status = "running";
45
+ if (o.status !== undefined) {
46
+ if (typeof o.status === "string" && STATUSES.has(o.status))
47
+ status = o.status;
48
+ else
49
+ diags.push(`setRunning["${id}"]: unknown status — treated as "running"`);
50
+ }
51
+ const item = { id, title, status };
52
+ if (typeof o.hint === "string" && o.hint.trim())
53
+ item.hint = o.hint.trim().slice(0, HINT_MAX);
54
+ if (typeof o.icon === "string" && o.icon.trim())
55
+ item.icon = o.icon.trim().slice(0, ICON_MAX);
56
+ if (typeof o.action === "string" && o.action.trim())
57
+ item.action = o.action.trim().slice(0, ACTION_MAX);
58
+ items.push(item);
59
+ });
60
+ return { items, diags };
61
+ }
62
+ /** TTL 夹取:非数字 / 缺省 → 默认值;其余夹进 [MIN, MAX]。 */
63
+ export function clampPanelTtl(raw) {
64
+ const n = typeof raw === "number" && Number.isFinite(raw) ? raw : PANEL_TTL_DEFAULT_MS;
65
+ return Math.min(PANEL_TTL_MAX_MS, Math.max(PANEL_TTL_MIN_MS, Math.round(n)));
66
+ }
67
+ export class LeftPanelRunningStore {
68
+ now;
69
+ slots = new Map();
70
+ constructor(now = Date.now) {
71
+ this.now = now;
72
+ }
73
+ /** 整体替换某插件的运行条目(同时是心跳)。 */
74
+ set(pluginId, pluginName, raw, opts) {
75
+ const { items, diags } = sanitizePanelItems(raw);
76
+ if (items.length === 0) {
77
+ const had = this.slots.delete(pluginId);
78
+ return { count: 0, changed: had, diags };
79
+ }
80
+ const ttlMs = clampPanelTtl(opts?.ttlMs);
81
+ const prev = this.slots.get(pluginId);
82
+ const changed = !prev || prev.pluginName !== pluginName || JSON.stringify(prev.items) !== JSON.stringify(items);
83
+ this.slots.set(pluginId, { pluginName, items, ttlMs, touchedAt: this.now() });
84
+ return { count: items.length, changed, diags };
85
+ }
86
+ /** 清空某插件的条目。返回是否真的删了东西(没有则不需要广播)。 */
87
+ clear(pluginId) {
88
+ return this.slots.delete(pluginId);
89
+ }
90
+ /** 清掉心跳过期的插件,返回被清掉的插件 id 列表(调用方据此广播)。 */
91
+ sweep() {
92
+ const t = this.now();
93
+ const expired = [];
94
+ for (const [pluginId, slot] of this.slots) {
95
+ if (t - slot.touchedAt > slot.ttlMs) {
96
+ this.slots.delete(pluginId);
97
+ expired.push(pluginId);
98
+ }
99
+ }
100
+ return expired;
101
+ }
102
+ /** 当前全部分组(按插件 id 排序,空组不出现)。返回副本,调用方随便改。 */
103
+ groups() {
104
+ return [...this.slots.entries()]
105
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
106
+ .map(([pluginId, slot]) => ({
107
+ pluginId,
108
+ pluginName: slot.pluginName,
109
+ items: slot.items.map((it) => ({ ...it })),
110
+ }));
111
+ }
112
+ get size() {
113
+ return this.slots.size;
114
+ }
115
+ }
@@ -0,0 +1,100 @@
1
+ // ---------------------------------------------------------------------------
2
+ // load-tools-tool.ts — 延迟加载模式下模型拉取工具 schema 的唯一入口。
3
+ // ---------------------------------------------------------------------------
4
+ // 背景:模型每轮都会拿到**全部活跃工具**的名字 + 完整参数 schema,几十个工具加起来
5
+ // 是几万字符的常驻开销(设置页「查看工具 schema」能看到了多少)。延迟加载把工具分成
6
+ // 两层:
7
+ // - 常驻:核心工具(bash/read/edit/write)+ 本工具;
8
+ // - 目录:其余工具只在系统提示词里以「名字 + 一行摘要」出现(见 prompt-composer 的
9
+ // tool catalog 段)。
10
+ // 模型要用某个目录里的工具时先调本工具,那批工具才会被激活 —— SDK 的中途工具变更会
11
+ // 把新增工具以 defer_loading / tool_search 的形式注入(见 agent-session 的
12
+ // `_preparePromptAndToolLoadout`),不占首轮上下文。
13
+ //
14
+ // 与 skills 的 `skill` 工具同构:名录常驻、正文按需。区别只在「正文」是工具 schema。
15
+ //
16
+ // 文案约定:工具 definition(description/promptSnippet/promptGuidelines)纯英文;
17
+ // per-call 返回文本按 lang 走 pick(lang, zh, en, key)。
18
+ // ---------------------------------------------------------------------------
19
+ import { defineTool } from "@earendil-works/pi-coding-agent";
20
+ import { Type } from "typebox";
21
+ import { pick } from "./i18n.js";
22
+ import { LOAD_TOOLS_TOOL_NAME } from "./tool-manager.js";
23
+ /** 单次最多加载多少(防模型一口气把整个目录塞回来)。 */
24
+ export const LOAD_TOOLS_MAX = 20;
25
+ function describe(t) {
26
+ const text = (t.description ?? t.summary ?? "").trim().split("\n")[0] ?? "";
27
+ return text.length > 240 ? `${text.slice(0, 240)}…` : text;
28
+ }
29
+ export function makeLoadToolsTool(host, lang) {
30
+ const getLang = lang ?? (() => "en");
31
+ const text = (t, details = {}) => ({
32
+ content: [{ type: "text", text: t }],
33
+ details,
34
+ });
35
+ return defineTool({
36
+ name: LOAD_TOOLS_TOOL_NAME,
37
+ label: "Load tools",
38
+ description: "Attach the full parameter schema of tools listed in the system prompt's tool catalog. " +
39
+ "Tools whose schema is not loaded are shown there by name + one-line summary; load the ones you need " +
40
+ "BEFORE calling them. Loaded tools stay available for the rest of the conversation.",
41
+ promptSnippet: "load catalog tools you are about to use",
42
+ promptGuidelines: [
43
+ "When a task needs a tool that is only listed in the catalog (name + one-line summary, no schema yet), " +
44
+ "call load_tools with its name first instead of guessing arguments",
45
+ "Load every tool you expect to need in ONE call — each load re-declares the tool set",
46
+ ],
47
+ parameters: Type.Object({
48
+ tools: Type.Array(Type.String(), {
49
+ description: `Tool names to load (1-${LOAD_TOOLS_MAX} per call), exactly as listed in the catalog.`,
50
+ minItems: 1,
51
+ maxItems: LOAD_TOOLS_MAX,
52
+ }),
53
+ }),
54
+ execute: async (_id, params) => {
55
+ const l = getLang();
56
+ const asked = params.tools;
57
+ const names = Array.isArray(asked)
58
+ ? [
59
+ ...new Set(asked
60
+ .filter((n) => typeof n === "string")
61
+ .map((n) => n.trim())
62
+ .filter(Boolean)),
63
+ ]
64
+ : [];
65
+ if (names.length === 0) {
66
+ return text(pick(l, "没有给出要加载的工具名。", "No tool names given.", "loadtools.names.empty"), {
67
+ loaded: [],
68
+ rejected: [],
69
+ });
70
+ }
71
+ const { loaded, rejected } = host.load(names.slice(0, LOAD_TOOLS_MAX));
72
+ const lines = [];
73
+ if (loaded.length > 0) {
74
+ lines.push(pick(l, `已加载 ${loaded.length} 个工具(完整参数 schema 已附上,本对话后续轮次都可用):`, `Loaded ${loaded.length} tool(s) — their full parameter schema is now attached for the rest of this conversation:`, "loadtools.loaded", { count: loaded.length }));
75
+ for (const t of loaded) {
76
+ const d = describe(t);
77
+ lines.push(`- ${t.name}${d ? `: ${d}` : ""}`);
78
+ // guidelines 不进系统提示词(会随加载变化、打坏前缀缓存),在此随回执交付。
79
+ for (const g of t.guidelines ?? []) {
80
+ const rule = g.trim();
81
+ if (rule)
82
+ lines.push(` - ${rule}`);
83
+ }
84
+ }
85
+ }
86
+ for (const r of rejected) {
87
+ lines.push(pick(l, `- ${r.name}: ${r.reason}`, `- ${r.name}: ${r.reason}`, "loadtools.rejected", {
88
+ name: r.name,
89
+ reason: r.reason,
90
+ }));
91
+ }
92
+ if (loaded.length === 0 && rejected.length === 0) {
93
+ const catalog = host.listLoadable();
94
+ lines.push(pick(l, "没有可加载的工具了。当前可加载:", "No tools left to load. Available:", "loadtools.none"));
95
+ lines.push(...catalog.map((t) => `- ${t.name}`));
96
+ }
97
+ return text(lines.join("\n"), { loaded: loaded.map((t) => t.name), rejected });
98
+ },
99
+ });
100
+ }
@@ -226,17 +226,23 @@ export async function autoInstallLanguageServer(pkg) {
226
226
  const npmCmd = isWin ? "npm.cmd" : "npm";
227
227
  let stderr = "";
228
228
  await new Promise((resolve, reject) => {
229
- const proc = spawn(npmCmd, ["install", "--no-audit", "--no-fund", "--save-dev", ...pkgs], {
229
+ const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : npmCmd;
230
+ const spawnArgs = isWin
231
+ ? ["/d", "/s", "/c", npmCmd, "install", "--no-audit", "--no-fund", "--save-dev", ...pkgs]
232
+ : ["install", "--no-audit", "--no-fund", "--save-dev", ...pkgs];
233
+ const proc = spawn(spawnCmd, spawnArgs, {
230
234
  cwd: userLspDir,
231
235
  stdio: ["ignore", "ignore", "pipe"],
232
- shell: isWin,
236
+ windowsHide: true,
233
237
  });
234
238
  const timer = setTimeout(() => {
235
239
  if (isWin) {
236
- // shell:true 时 proc.pid 只是 cmd.exe 的 PID——proc.kill() 只杀得到
237
- // cmd.exe,npm/node 整棵子进程树会残留。taskkill /T 连树强杀。
240
+ // win32 下 taskkill /T 连整棵子进程树强杀,避免 npm/node 残留。
238
241
  if (typeof proc.pid === "number") {
239
- const killer = spawn("taskkill", ["/PID", String(proc.pid), "/T", "/F"], { stdio: "ignore" });
242
+ const killer = spawn("taskkill", ["/PID", String(proc.pid), "/T", "/F"], {
243
+ stdio: "ignore",
244
+ windowsHide: true,
245
+ });
240
246
  killer.on("error", () => { });
241
247
  }
242
248
  }
@@ -316,13 +322,17 @@ export class LspClient {
316
322
  }
317
323
  async start() {
318
324
  this.touch();
319
- this.proc = spawn(this.binPath, this.binArgs, {
325
+ const isWin = process.platform === "win32";
326
+ const isBatch = isWin && /\.(cmd|bat)$/i.test(this.binPath);
327
+ const spawnCmd = isBatch ? process.env.ComSpec || "cmd.exe" : this.binPath;
328
+ const spawnArgs = isBatch ? ["/d", "/s", "/c", this.binPath, ...this.binArgs] : this.binArgs;
329
+ this.proc = spawn(spawnCmd, spawnArgs, {
320
330
  cwd: this.projectCwd,
321
331
  stdio: ["pipe", "pipe", "pipe"],
322
- shell: process.platform === "win32" && /\.(cmd|bat)$/i.test(this.binPath),
332
+ windowsHide: true,
323
333
  });
324
334
  this.proc.stdout?.on("data", (chunk) => this.handleData(chunk));
325
- this.proc.stderr?.on("data", (d) => {
335
+ this.proc.stderr?.on("data", (_d) => {
326
336
  // 可选记录 debug 日志,不干扰输出
327
337
  });
328
338
  // spawn 失败(ENOENT/EACCES 等)只触发 'error',进程从未启动时不会触发
@@ -347,7 +357,7 @@ export class LspClient {
347
357
  });
348
358
  try {
349
359
  // 发送 initialize 握手
350
- const initRes = await this.request("initialize", {
360
+ await this.request("initialize", {
351
361
  processId: process.pid,
352
362
  rootUri: pathToFileURL(this.projectCwd).toString(),
353
363
  workspaceFolders: [
@@ -372,7 +382,16 @@ export class LspClient {
372
382
  catch (err) {
373
383
  if (this.proc) {
374
384
  try {
375
- this.proc.kill();
385
+ if (process.platform === "win32" && typeof this.proc.pid === "number") {
386
+ const killer = spawn("taskkill", ["/PID", String(this.proc.pid), "/T", "/F"], {
387
+ stdio: "ignore",
388
+ windowsHide: true,
389
+ });
390
+ killer.on("error", () => { });
391
+ }
392
+ else {
393
+ this.proc.kill();
394
+ }
376
395
  }
377
396
  catch { }
378
397
  this.proc = null;
@@ -546,7 +565,16 @@ export class LspClient {
546
565
  catch { }
547
566
  if (this.proc) {
548
567
  try {
549
- this.proc.kill();
568
+ if (process.platform === "win32" && typeof this.proc.pid === "number") {
569
+ const killer = spawn("taskkill", ["/PID", String(this.proc.pid), "/T", "/F"], {
570
+ stdio: "ignore",
571
+ windowsHide: true,
572
+ });
573
+ killer.on("error", () => { });
574
+ }
575
+ else {
576
+ this.proc.kill();
577
+ }
550
578
  }
551
579
  catch { }
552
580
  this.proc = null;
@@ -856,18 +884,12 @@ export function makeLspTool(options) {
856
884
  const getLang = options.lang ?? (() => "en");
857
885
  return defineTool({
858
886
  name: LSP_TOOL_NAME,
859
- promptSnippet: "IDE-grade semantic analysis (LSP) across the workspace: definition, references, hover, diagnostics, symbols, impact check",
887
+ promptSnippet: "semantic code intelligence (definitions, references, diagnostics, impact)",
860
888
  label: "LSP code intelligence",
861
- description: `IDE-grade semantic analysis (LSP) across the workspace. Actions:
862
- - \`definition\`: definition of the symbol at \`line\`/\`character\` in \`path\` (file, line, snippet).
863
- - \`references\`: all workspace usages of that symbol.
864
- - \`hover\`: type signature and docs for that symbol.
865
- - \`diagnostics\`: compiler/type errors and warnings for \`path\` (whole file).
866
- - \`documentSymbol\`: hierarchical symbol outline with line spans for \`path\`.
867
- - \`read_symbol\`: read the body of \`symbol\` in \`path\` (e.g. "parseConfig").
868
- - \`workspaceSymbol\`: search symbols across the workspace by \`query\`.
869
- - \`cascade\`: impact check for \`path\` — report diagnostics of files referencing it.
870
- Lines are 1-indexed.`,
889
+ description: "IDE-grade semantic analysis (LSP) across the workspace (lines are 1-indexed). `definition` / `references` / `hover`: " +
890
+ "resolve the symbol at `line`/`character` in `path` to its definition, workspace usages, or type and docs. `diagnostics`: " +
891
+ "file errors/warnings. `documentSymbol`: symbol outline. `read_symbol`: body of `symbol` in `path`. `workspaceSymbol`: " +
892
+ "symbols matching `query`. `cascade`: diagnostics of files referencing `path`.",
871
893
  parameters: Type.Object({
872
894
  action: Type.Unsafe({
873
895
  type: "string",
@@ -884,16 +906,16 @@ Lines are 1-indexed.`,
884
906
  description: "The LSP operation to perform.",
885
907
  }),
886
908
  path: Type.Optional(Type.String({
887
- description: "Workspace-relative or absolute path to the target source file (required for all actions except workspaceSymbol).",
909
+ description: "Workspace-relative or absolute file path (required for every action except workspaceSymbol).",
888
910
  })),
889
911
  symbol: Type.Optional(Type.String({
890
- description: "Symbol name to read for 'read_symbol' action (e.g. 'functionName' or 'ClassName.methodName').",
912
+ description: "Symbol for 'read_symbol' (e.g. 'fn' or 'Class.method').",
891
913
  })),
892
914
  query: Type.Optional(Type.String({
893
- description: "Search query for 'workspaceSymbol' action.",
915
+ description: "Search query for 'workspaceSymbol'.",
894
916
  })),
895
917
  line: Type.Optional(Type.Number({
896
- description: "1-indexed line number in the source file.",
918
+ description: "1-indexed line in the file.",
897
919
  })),
898
920
  character: Type.Optional(Type.Number({
899
921
  description: "1-indexed column/character position (defaults to 1).",
@@ -901,7 +923,7 @@ Lines are 1-indexed.`,
901
923
  timeout: Type.Optional(Type.Number({
902
924
  minimum: 1,
903
925
  maximum: 120,
904
- description: "Timeout in seconds (1-120, defaults to 15).",
926
+ description: "Timeout in seconds (default 15).",
905
927
  })),
906
928
  allowInstall: Type.Optional(Type.Boolean({
907
929
  description: "Install the missing language server into ~/.pi-web/lsp-servers (user-space, no sudo). Default false: the tool returns an installHint instead.",
@@ -1381,7 +1403,7 @@ Lines are 1-indexed.`,
1381
1403
  while (pending.size > 0 && Date.now() < deadline) {
1382
1404
  await new Promise((r) => setTimeout(r, 120));
1383
1405
  const known = client.getAllDiagnostics();
1384
- for (const u of [...pending]) {
1406
+ for (const u of Array.from(pending)) {
1385
1407
  if (known.has(u))
1386
1408
  pending.delete(u);
1387
1409
  }
@@ -5,8 +5,9 @@ import { pick } from "./i18n.js";
5
5
  import { ensureMarkersRegistered, parseMarkers, getMarker, allMarkers, collectGuidance, listMarkerNames, } from "./markers/index.js";
6
6
  import { loadStateFromBranch, appendSnapshot } from "./markers/store.js";
7
7
  import { TODO_NAMESPACE, initTodoState } from "./markers/builtins/todo.js";
8
+ import { ACTION_NAMESPACE, initActionState } from "./markers/builtins/action.js";
8
9
  ensureMarkersRegistered();
9
- const DEFAULT_MARKERS = {
10
+ const _DEFAULT_MARKERS = {
10
11
  markersEnabled: true,
11
12
  disabledMarkers: [],
12
13
  };
@@ -31,6 +32,8 @@ export class MarkerService {
31
32
  isMarkerEnabled(name) {
32
33
  if (!this.settings.markersEnabled)
33
34
  return false;
35
+ if (name === "suggest" && this.settings.disabledMarkers.includes("action"))
36
+ return false;
34
37
  return !this.settings.disabledMarkers.includes(name);
35
38
  }
36
39
  /** 当前服务端语言(英文默认,未接线前保持原有英文行为)。 */
@@ -63,10 +66,16 @@ export class MarkerService {
63
66
  }
64
67
  toggleMarker(name, enabled) {
65
68
  const set = new Set(this.settings.disabledMarkers);
66
- if (enabled)
69
+ if (enabled) {
67
70
  set.delete(name);
68
- else
71
+ if (name === "action")
72
+ set.delete("suggest");
73
+ }
74
+ else {
69
75
  set.add(name);
76
+ if (name === "action")
77
+ set.add("suggest");
78
+ }
70
79
  this.settings.disabledMarkers = [...set];
71
80
  this.host.stateStore.saveMarkerSettings(this.host.clientId, this.settings);
72
81
  }
@@ -147,16 +156,19 @@ export class MarkerService {
147
156
  const disabled = new Set(this.settings.disabledMarkers);
148
157
  const states = new Map();
149
158
  const getOrInit = (ns) => {
150
- let st = states.get(ns);
159
+ const canonicalNs = ns === "suggest" ? ACTION_NAMESPACE : ns;
160
+ let st = states.get(canonicalNs);
151
161
  if (st !== undefined)
152
162
  return st;
153
- if (ns === TODO_NAMESPACE)
154
- st = this.getState(conversationId, ns, initTodoState);
163
+ if (canonicalNs === TODO_NAMESPACE)
164
+ st = this.getState(conversationId, canonicalNs, initTodoState);
165
+ else if (canonicalNs === ACTION_NAMESPACE)
166
+ st = this.getState(conversationId, canonicalNs, initActionState);
155
167
  else {
156
- const marker = getMarker(ns);
168
+ const marker = getMarker(canonicalNs);
157
169
  st = marker?.init ? marker.init() : {};
158
170
  }
159
- states.set(ns, st);
171
+ states.set(canonicalNs, st);
160
172
  return st;
161
173
  };
162
174
  const dirty = new Set();
@@ -188,9 +200,10 @@ export class MarkerService {
188
200
  };
189
201
  }
190
202
  if (result.applied) {
191
- // todo 落库;notify/conv 即时生效(通知已发 / 对话已重命名),无需快照。
192
- if (token.tool !== "notify" && token.tool !== "conv") {
193
- dirty.add(token.tool);
203
+ // todo 与 action 落库;notify/conv 即时生效(通知已发 / 对话已重命名),无需快照。
204
+ const canonicalTool = token.tool === "suggest" ? ACTION_NAMESPACE : token.tool;
205
+ if (canonicalTool !== "notify" && canonicalTool !== "conv") {
206
+ dirty.add(canonicalTool);
194
207
  }
195
208
  }
196
209
  else if (result.error) {
@@ -208,6 +221,9 @@ export class MarkerService {
208
221
  this.saveState(conversationId, ns, mutated);
209
222
  }
210
223
  this.pushOverlay(conversationId);
224
+ if (dirty.has(ACTION_NAMESPACE)) {
225
+ this.host.onActionsChange?.(conversationId);
226
+ }
211
227
  }
212
228
  pushOverlay(conversationId) {
213
229
  const lines = this.overlayLines(conversationId);
@@ -224,6 +240,8 @@ export class MarkerService {
224
240
  overlayLines(conversationId) {
225
241
  const lines = [];
226
242
  for (const m of allMarkers()) {
243
+ if (m.name === "suggest")
244
+ continue;
227
245
  if (this.settings.disabledMarkers.includes(m.name))
228
246
  continue;
229
247
  if (!m.overlay)
@@ -231,6 +249,8 @@ export class MarkerService {
231
249
  let state;
232
250
  if (m.name === TODO_NAMESPACE)
233
251
  state = this.getState(conversationId, m.name, initTodoState);
252
+ else if (m.name === ACTION_NAMESPACE)
253
+ state = this.getState(conversationId, m.name, initActionState);
234
254
  else {
235
255
  state = this.getState(conversationId, m.name, () => m.init?.() ?? {});
236
256
  if (state === undefined)
@@ -259,15 +279,36 @@ export class MarkerService {
259
279
  getRawState(conversationId, namespace) {
260
280
  if (namespace === TODO_NAMESPACE)
261
281
  return this.getState(conversationId, namespace, initTodoState);
282
+ if (namespace === ACTION_NAMESPACE || namespace === "suggest")
283
+ return this.getState(conversationId, ACTION_NAMESPACE, initActionState);
262
284
  const m = getMarker(namespace);
263
285
  return this.getState(conversationId, namespace, () => m?.init?.() ?? {});
264
286
  }
287
+ getActionSuggestions(conversationId) {
288
+ if (!this.isMarkerEnabled("action"))
289
+ return null;
290
+ const st = this.getState(conversationId, ACTION_NAMESPACE, initActionState);
291
+ if (!st || !st.actions || st.actions.length === 0)
292
+ return null;
293
+ return st.actions.map((a) => ({ id: a.id, label: a.label, prompt: a.prompt }));
294
+ }
295
+ clearActions(conversationId) {
296
+ const st = this.getState(conversationId, ACTION_NAMESPACE, initActionState);
297
+ if (st && st.actions && st.actions.length > 0) {
298
+ st.actions = [];
299
+ this.saveState(conversationId, ACTION_NAMESPACE, st);
300
+ this.pushOverlay(conversationId);
301
+ this.host.onActionsChange?.(conversationId);
302
+ }
303
+ }
265
304
  /** 供设置面板展示的 marker 目录(含启用状态)。 */
266
- /** UI 过滤:rename/title 是 conv 的别名,不单独展示。 */
305
+ /** UI 过滤:rename/title 是 conv 的别名,suggest 是 action 的别名,不单独展示。 */
267
306
  listForUi() {
268
307
  const seen = new Set();
269
308
  const out = [];
270
309
  for (const m of allMarkers()) {
310
+ if (m.name === "suggest")
311
+ continue;
271
312
  if (seen.has(m.name))
272
313
  continue;
273
314
  seen.add(m.name);
@@ -0,0 +1,108 @@
1
+ /**
2
+ * builtins/action.ts — 建议操作标记(期待用户操作)。
3
+ *
4
+ * 语法:
5
+ * [[action:suggest:<按钮文字>]] 添加快捷操作建议(点击发送该文字)
6
+ * [[action:suggest:<按钮显示>,prompt=<实际发送文本>]] 区分展示标签与实际发送内容
7
+ * [[action:suggest:label=<按钮显示>,prompt=<发送文本>]] kwargs 风格
8
+ * [[action:clear:all]] 清空当前建议操作
9
+ *
10
+ * 兼容操作别名:
11
+ * tool 兼容 action 与 suggest
12
+ * op 兼容 suggest / add / next / reply / choice / option / clear
13
+ */
14
+ import { getServerBlock, pick } from "../../i18n.js";
15
+ export const ACTION_NAMESPACE = "action";
16
+ export function initActionState() {
17
+ return { actions: [], nextId: 1 };
18
+ }
19
+ const ACTION_GUIDANCE_ZH = [
20
+ "- 建议后续操作:[[action:suggest:<文字>]](当期待用户操作时,如是否继续、后续步骤选择;在对话最底部生成按钮,用户点击即发送该文字)",
21
+ "- 可指定不同按钮显示与发送内容:[[action:suggest:<按钮显示>,prompt=<实际发送文本>]]",
22
+ "- 清空候选操作:[[action:clear:all]]",
23
+ ];
24
+ const ACTION_GUIDANCE_EN = [
25
+ "- Suggest next actions: [[action:suggest:<text>]] (when expecting user input, e.g. whether to continue, what to do next; creates buttons at the bottom of the conversation, clicked to send text immediately)",
26
+ "- Optional separate prompt: [[action:suggest:<label>,prompt=<text to send>]]",
27
+ "- Clear suggestions: [[action:clear:all]]",
28
+ ];
29
+ /** 语言感知的 action guidance:en 用英译、zh 用中文,默认英文。 */
30
+ export function getActionGuidance(lang = "en") {
31
+ return getServerBlock(lang, "markers.action.guidance", ACTION_GUIDANCE_ZH, ACTION_GUIDANCE_EN);
32
+ }
33
+ const VALID_ACTION_OPS = new Set(["suggest", "add", "next", "reply", "choice", "option", "action"]);
34
+ export const actionMarker = {
35
+ name: "action",
36
+ guidance: ACTION_GUIDANCE_ZH,
37
+ getGuidance: getActionGuidance,
38
+ async apply(token, _ctx, state, lang = "en") {
39
+ const op = token.op.toLowerCase();
40
+ if (op === "clear") {
41
+ state.actions = [];
42
+ return {
43
+ applied: true,
44
+ feedback: pick(lang, "已清空建议操作", "Cleared suggested actions", "markers.action.cleared"),
45
+ };
46
+ }
47
+ if (!VALID_ACTION_OPS.has(op)) {
48
+ return {
49
+ applied: false,
50
+ error: pick(lang, `action 未知操作: ${token.op}(支持 suggest/next/add/clear)`, `action unknown operation: ${token.op} (supports suggest/next/add/clear)`, "markers.action.unknown.operation", { "token.op": token.op }),
51
+ };
52
+ }
53
+ // 提取 label 与 prompt:
54
+ // args: token.args.join(",").trim() (兼容含逗号的正文,如 "是,继续执行")
55
+ const argsText = token.args.join(",").trim();
56
+ const kwLabel = token.kwargs["label"]?.trim() || "";
57
+ const kwPrompt = token.kwargs["prompt"]?.trim() || "";
58
+ const kwText = token.kwargs["text"]?.trim() || "";
59
+ let prompt = kwPrompt || argsText || kwText || kwLabel;
60
+ let label = kwLabel || argsText || kwText || prompt;
61
+ if (!label && !prompt) {
62
+ return {
63
+ applied: false,
64
+ error: pick(lang, "action:suggest 需要操作描述 [[action:suggest:<文字>]]", "action:suggest requires an action description [[action:suggest:<text>]]", "markers.action.requires.text"),
65
+ };
66
+ }
67
+ if (!prompt)
68
+ prompt = label;
69
+ if (!label)
70
+ label = prompt;
71
+ // 字符长度封顶保护
72
+ if (label.length > 80)
73
+ label = label.slice(0, 80);
74
+ if (prompt.length > 2000)
75
+ prompt = prompt.slice(0, 2000);
76
+ // 去重
77
+ const existing = state.actions.find((a) => a.label === label && a.prompt === prompt);
78
+ if (existing) {
79
+ return {
80
+ applied: true,
81
+ feedback: pick(lang, `建议操作已存在: ${label}`, `Suggested action already exists: ${label}`, "markers.action.already.exists", { label }),
82
+ };
83
+ }
84
+ // 数量上限 8 个,超限剔除最早的一项
85
+ if (state.actions.length >= 8) {
86
+ state.actions.shift();
87
+ }
88
+ const id = `act-${state.nextId++}`;
89
+ state.actions.push({ id, label, prompt });
90
+ return {
91
+ applied: true,
92
+ feedback: pick(lang, `已添加建议操作: ${label}`, `Added suggested action: ${label}`, "markers.action.added", {
93
+ label,
94
+ }),
95
+ };
96
+ },
97
+ overlay(state) {
98
+ if (!state || state.actions.length === 0)
99
+ return undefined;
100
+ const lines = state.actions.map((a) => (a.label === a.prompt ? ` [${a.label}]` : ` [${a.label}] -> ${a.prompt}`));
101
+ return { tool: "action", lines: [`${state.actions.length} action(s)`, ...lines] };
102
+ },
103
+ init: initActionState,
104
+ };
105
+ export const suggestMarker = {
106
+ ...actionMarker,
107
+ name: "suggest",
108
+ };
@@ -5,6 +5,7 @@ import { registerMarker } from "./registry.js";
5
5
  import { todoMarker } from "./builtins/todo.js";
6
6
  import { notifyMarker } from "./builtins/notify.js";
7
7
  import { renameMarker } from "./builtins/rename.js";
8
+ import { actionMarker, suggestMarker } from "./builtins/action.js";
8
9
  let initialized = false;
9
10
  export function ensureMarkersRegistered() {
10
11
  if (initialized)
@@ -12,9 +13,11 @@ export function ensureMarkersRegistered() {
12
13
  registerMarker(todoMarker);
13
14
  registerMarker(notifyMarker);
14
15
  registerMarker(renameMarker);
16
+ registerMarker(actionMarker);
17
+ registerMarker(suggestMarker);
15
18
  initialized = true;
16
19
  }
17
- export { todoMarker, notifyMarker, renameMarker };
20
+ export { todoMarker, notifyMarker, renameMarker, actionMarker, suggestMarker };
18
21
  export * from "./marker.js";
19
22
  export * from "./registry.js";
20
23
  export * from "./store.js";