pi-web-ui 0.98.0 → 0.100.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 (69) hide show
  1. package/CHANGELOG.md +85 -5
  2. package/README.md +2 -1
  3. package/README.zh-CN.md +2 -1
  4. package/bin/pi-web-ui.mjs +174 -36
  5. package/dist/server/agent-service.js +1169 -152
  6. package/dist/server/approval-rules.js +95 -23
  7. package/dist/server/attachments.js +55 -0
  8. package/dist/server/bg-servers.js +82 -2
  9. package/dist/server/claim-files-tool.js +4 -4
  10. package/dist/server/client-state.js +41 -0
  11. package/dist/server/compact-context-tool.js +10 -9
  12. package/dist/server/conversation-read-tool.js +7 -8
  13. package/dist/server/conversation-touches.js +19 -0
  14. package/dist/server/delegate-task.js +10 -14
  15. package/dist/server/dsh/dsh-agent-service.js +116 -12
  16. package/dist/server/edit-soft-tool.js +10 -12
  17. package/dist/server/eval-tool.js +26 -6
  18. package/dist/server/goal-evidence.js +173 -0
  19. package/dist/server/goal-service.js +78 -15
  20. package/dist/server/hashline-engine.js +198 -31
  21. package/dist/server/index.js +55 -9
  22. package/dist/server/load-tools-tool.js +100 -0
  23. package/dist/server/lsp-tool.js +10 -16
  24. package/dist/server/marker-service.js +53 -12
  25. package/dist/server/markers/builtins/action.js +108 -0
  26. package/dist/server/markers/index.js +4 -1
  27. package/dist/server/model-enrich.js +2 -0
  28. package/dist/server/patch-remote-catalog.js +28 -10
  29. package/dist/server/patch-tool.js +74 -38
  30. package/dist/server/plan-manager.js +71 -30
  31. package/dist/server/plan-mode.js +7 -6
  32. package/dist/server/plugin-api-catalog.js +10 -3
  33. package/dist/server/plugin-conversation-view.js +47 -0
  34. package/dist/server/plugins.js +113 -26
  35. package/dist/server/present-files-tool.js +10 -11
  36. package/dist/server/preset-fields.js +693 -0
  37. package/dist/server/preset-share.js +1178 -0
  38. package/dist/server/prompt-composer.js +23 -9
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/read-tool.js +8 -10
  41. package/dist/server/resolve-global-sdk.js +80 -18
  42. package/dist/server/schedule-agent-tool.js +147 -146
  43. package/dist/server/sdk-origin.js +125 -37
  44. package/dist/server/settings-service.js +103 -84
  45. package/dist/server/skill-tool.js +3 -4
  46. package/dist/server/subagents.js +15 -22
  47. package/dist/server/terminals.js +29 -39
  48. package/dist/server/tool-approval.js +3 -1
  49. package/dist/server/tool-manager.js +63 -27
  50. package/dist/server/tool-prompt-overrides.js +158 -0
  51. package/dist/server/tool-prompts.js +42 -0
  52. package/dist/server/tool-signature.js +104 -0
  53. package/dist/server/update-check.js +0 -15
  54. package/dist/server/workspace-snapshot.js +42 -11
  55. package/package.json +5 -3
  56. package/plugin-sdk/README.md +8 -4
  57. package/plugin-sdk/import-check.mjs +210 -0
  58. package/plugin-sdk/index.d.ts +4 -1
  59. package/plugin-sdk/index.mjs +1 -0
  60. package/plugins/catalog.json +33 -2
  61. package/themes/zhupi-dark.css +1 -1
  62. package/themes/zhupi.css +1 -1
  63. package/web/dist/assets/{TerminalPanel-C88r3r3Q.js → TerminalPanel-C3I1Mc-C.js} +2 -2
  64. package/web/dist/assets/index-B-E2EM_0.css +1 -0
  65. package/web/dist/assets/index-BYumAaGi.js +379 -0
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/sw.js +1 -1
  68. package/web/dist/assets/index-2jDtjHvW.css +0 -1
  69. package/web/dist/assets/index-BjdK7s1M.js +0 -368
@@ -24,6 +24,7 @@ import "./patch-node-pty.js";
24
24
  import { spawn } from "node-pty";
25
25
  import { defineTool } from "@earendil-works/pi-coding-agent";
26
26
  import { Type } from "typebox";
27
+ import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
27
28
  import { pick } from "./i18n.js";
28
29
  /** Location of the command list for a project: <workspaceRoot>/.pi/commands.json */
29
30
  export function commandsFilePath(workspaceRoot) {
@@ -1580,28 +1581,35 @@ function cleanBashOutput(raw) {
1580
1581
  /** 一次性 bash 终端序号:非持久调用每次新建一个终端,进程结束后退出、输出
1581
1582
  * 保留在 history 供查阅——故每调用独立 id,避免复用覆盖旧输出。 */
1582
1583
  let oneShotBashSeq = 0;
1584
+ /** head / tail 的运行时上限,与 bash 工具参数 schema 的 maximum 5000 一致
1585
+ * (agent-service.ts)——schema 只影响提示不拦运行时(issue #462)。 */
1586
+ const MAX_HEAD_TAIL_LINES = 5000;
1583
1587
  /** 应用 head / tail 参数到输出顶层行(替代 `| head` / `| tail` 管道——管道会
1584
1588
  * 缓冲输出、让可见终端全程哑火,还容易白白触发静默解阻)。两者同时给时先
1585
1589
  * 截头再截尾。 */
1586
1590
  export function applyHeadTail(text, head, tail, lang = "en") {
1591
+ // 入口钳到 schema 上限:此前只判 >0,传 1e9 会把整段缓冲灌进单条工具结果
1592
+ // 并持久化进转录。
1593
+ const headN = head && head > 0 ? Math.min(Math.floor(head), MAX_HEAD_TAIL_LINES) : 0;
1594
+ const tailN = tail && tail > 0 ? Math.min(Math.floor(tail), MAX_HEAD_TAIL_LINES) : 0;
1587
1595
  // 只对真实数据行切片;省略提示行单独存,最后再包回输出,避免提示行在
1588
1596
  // head+tail 组合时被当成数据行参与第二次截取(导致尾部少截一行)。
1589
1597
  let data = text.split("\n");
1590
1598
  let headNote = null;
1591
1599
  let tailNote = null;
1592
- if (head && head > 0 && data.length > head) {
1593
- const n = data.length - head;
1600
+ if (headN && data.length > headN) {
1601
+ const n = data.length - headN;
1594
1602
  headNote = pick(lang, `…(后 ${n} 行已省略)`, `…[${n} lines omitted below]…`, "terminals.headtail.omitted.below", {
1595
1603
  n,
1596
1604
  });
1597
- data = data.slice(0, head);
1605
+ data = data.slice(0, headN);
1598
1606
  }
1599
- if (tail && tail > 0 && data.length > tail) {
1600
- const n = data.length - tail;
1607
+ if (tailN && data.length > tailN) {
1608
+ const n = data.length - tailN;
1601
1609
  tailNote = pick(lang, `…(前 ${n} 行已省略)`, `…[${n} lines omitted above]…`, "terminals.headtail.omitted.above", {
1602
1610
  n,
1603
1611
  });
1604
- data = data.slice(-tail);
1612
+ data = data.slice(-tailN);
1605
1613
  }
1606
1614
  const parts = [];
1607
1615
  if (tailNote)
@@ -1616,31 +1624,12 @@ export function makeTerminalBashTool(terminals, opts) {
1616
1624
  return defineTool({
1617
1625
  name: "bash",
1618
1626
  label: "Run bash command",
1619
- description: "Run a shell command in a visible terminal; returns full output and exit code. " +
1620
- "persist=false (default): a fresh one-shot terminal per call; the shell exits after the command but its output stays viewable. " +
1621
- "persist=true: runs in the persistent 'ai-bash' terminal — shell state (cd/venv/ssh) is retained across calls; " +
1622
- "terminal_read/terminal_input/terminal_key observe or interact; terminal_wait blocks on backgrounded commands. " +
1623
- "Run the bare command — never pipe through head/tail/more/less (output is returned complete; pipes hide live progress); use the head/tail params instead. " +
1624
- "For interactive commands (REPLs, y/n prompts) set persist=true and drive them with terminal_input / terminal_key.",
1625
- promptSnippet: "run shell commands (persist=true keeps the terminal alive across calls)",
1626
- parameters: Type.Object({
1627
- command: Type.String({ description: "The shell command to run" }),
1628
- timeout: Type.Optional(Type.Number({ description: "Optional timeout in seconds" })),
1629
- persist: Type.Optional(Type.Boolean({
1630
- description: "true → run in the persistent 'ai-bash' terminal: shell state (cd/venv/ssh) is retained across calls. " +
1631
- "false (default) → one-shot terminal that exits when the command finishes; output stays viewable.",
1632
- })),
1633
- head: Type.Optional(Type.Integer({
1634
- minimum: 1,
1635
- maximum: 5000,
1636
- description: "Only return the FIRST N lines of output (like `| head -N`); prefer this over piping through head.",
1637
- })),
1638
- tail: Type.Optional(Type.Integer({
1639
- minimum: 1,
1640
- maximum: 5000,
1641
- description: "Only return the LAST N lines of output (like `| tail -N`); prefer this over piping through tail.",
1642
- })),
1643
- }),
1627
+ // 提示词单源:模型看到的 bash 定义由 makeAdaptiveBashTool 从 tool-prompts.ts 取,
1628
+ // 本定义只提供终端这条执行路径(description/schema 必须与另两条一致,不另写一套)。
1629
+ description: BASH_DESCRIPTION,
1630
+ promptSnippet: BASH_PROMPT_SNIPPET,
1631
+ promptGuidelines: BASH_PROMPT_GUIDELINES,
1632
+ parameters: BASH_PARAMETERS,
1644
1633
  execute: async (_id, p, signal) => {
1645
1634
  const lang = opts.lang?.() ?? "en";
1646
1635
  const persist = p.persist ?? opts.defaultPersist();
@@ -1877,10 +1866,11 @@ lang, options) {
1877
1866
  defineTool({
1878
1867
  name: "terminal_create",
1879
1868
  label: "Create terminal",
1880
- description: "Create a named persistent interactive PTY. Interact via terminal_input / terminal_key, inspect output via terminal_read. " +
1881
- "Prefer bash for one-shot commands; use this (or bash persist=true) for interactive/TUI programs (REPLs, vim/htop, y/n prompts) or long-running servers to observe or interrupt.",
1882
- promptSnippet: "run interactive programs or long-running servers in a persistent visible PTY (multi-step: " +
1883
- "create → input/key → read)",
1869
+ description: "Create a named persistent interactive PTY. Interact via terminal_input / terminal_key; inspect output via terminal_read.",
1870
+ promptSnippet: "drive interactive programs or long-running servers in a PTY",
1871
+ promptGuidelines: [
1872
+ "Use this for full-screen TUIs (vim/htop) and servers you need to observe or interrupt; prefer bash for one-shot commands",
1873
+ ],
1884
1874
  parameters: Type.Object({
1885
1875
  terminalId: Type.String({ description: "Stable terminal name" }),
1886
1876
  cwd: Type.Optional(Type.String({ description: "Workspace-relative directory" })),
@@ -1993,10 +1983,10 @@ lang, options) {
1993
1983
  defineTool({
1994
1984
  name: "terminal_wait",
1995
1985
  label: "Wait for terminal command",
1996
- description: "Block until a command started through the BASH TOOL finishes (exit marker appears) or timeout — no polling. " +
1997
- "Only applies to bash-tool commands; commands sent via terminal_input have no completion marker — use terminal_read(waitMs=…) for those. " +
1998
- "Returns {finished, exitCode} plus output produced while waiting; finished=false means still running (call again).",
1999
- promptSnippet: "block until a terminal's current command finishes (no polling)",
1986
+ description: "Block until a bash-tool command finishes (exit marker) or timeout — no polling. " +
1987
+ "Returns {finished, exitCode} plus output produced meanwhile; finished=false = still running (call again). " +
1988
+ "terminal_input commands have no completion marker — use terminal_read(waitMs=…) for those.",
1989
+ promptSnippet: "avoid polling: wait for a long bash command to finish",
2000
1990
  parameters: Type.Object({
2001
1991
  terminalId: Type.String(),
2002
1992
  cursor: Type.Optional(Type.Integer({
@@ -17,7 +17,7 @@
17
17
  * - 本对话「允许同类」→ 该对话内同一规则档位(category)不再弹。
18
18
  * 策略只活在内存里(挂在 Conversation 上,过户随对话搬走),重启/新对话即恢复询问。
19
19
  */
20
- import { DEFAULT_APPROVAL_RULES, evaluateApprovalRules } from "./approval-rules.js";
20
+ import { DEFAULT_APPROVAL_RULES, evaluateApprovalRules, } from "./approval-rules.js";
21
21
  /** 策略为空(既没全部允许也没记同类):调用方据此不挂空策略、面板据此不显示撤销区。 */
22
22
  export function isApprovalPolicyEmpty(policy) {
23
23
  return !policy || (!policy.allowAll && policy.categories.size === 0);
@@ -63,6 +63,7 @@ export function checkDangerousToolCall(toolName, params, cwd, workspaceRoots = [
63
63
  reason: res.reason,
64
64
  reasonEn: res.reasonEn,
65
65
  category: res.category,
66
+ hits: res.hits,
66
67
  };
67
68
  }
68
69
  if (res.action === "allow") {
@@ -78,6 +79,7 @@ export function checkDangerousToolCall(toolName, params, cwd, workspaceRoots = [
78
79
  reason: res.reason,
79
80
  reasonEn: res.reasonEn,
80
81
  category: res.category,
82
+ hits: res.hits,
81
83
  };
82
84
  }
83
85
  return { dangerous: false };
@@ -57,11 +57,12 @@ export const CONVERSATION_READ_TOOL_NAME = "conversation_read";
57
57
  /** 技能全文按名加载工具(定义见 skill-tool.ts):名录见 {{skills}} 段,
58
58
  * 全文走本工具按需取,不再让模型拼路径调 read。 */
59
59
  export const SKILL_TOOL_NAME = "skill";
60
- /** 定时任务工具(定义见 schedule-agent-tool.ts):创建/查看/取消内置调度任务,
61
- * 到期自动唤醒发起对话执行 prompt 并汇报。 */
62
- export const SCHEDULE_TASK_TOOL_NAME = "schedule_task";
63
- export const SCHEDULE_LIST_TOOL_NAME = "schedule_list";
64
- export const SCHEDULE_CANCEL_TOOL_NAME = "schedule_cancel";
60
+ /** 定时任务工具(定义见 schedule-agent-tool.ts):单 action 工具,create 建任务 /
61
+ * list 查看 / cancel 取消;到期自动唤醒发起对话执行 prompt 并汇报。 */
62
+ export const SCHEDULE_TOOL_NAME = "schedule";
63
+ /** 旧版 3 个独立定时任务工具名(持久化配置迁移用:用户在旧版本关掉的任一个
64
+ * 都迁移为关闭合并后的 schedule 工具)。 */
65
+ export const LEGACY_SCHEDULE_TOOL_NAMES = ["schedule_task", "schedule_list", "schedule_cancel"];
65
66
  /** 持久代码求值沙箱工具(定义见 eval-tool.ts):在受控持久内核中执行 Python 或 JS/TS 代码。 */
66
67
  export const EVAL_TOOL_NAME = "eval";
67
68
  /** 展示文件工具(定义见 present-files-tool.ts):把图片/视频/文本作为预览卡片
@@ -78,9 +79,16 @@ export const COMPACT_CONTEXT_TOOL_NAME = "compact_context";
78
79
  export const PATCH_TOOL_NAME = "patch";
79
80
  /** 原生语言服务器工具(定义见 lsp-tool.ts):代码定义跳转、引用查询、类型悬停与诊断。 */
80
81
  export const LSP_TOOL_NAME = "lsp";
82
+ /** 按需加载工具(定义见 load-tools-tool.ts):延迟加载模式下模型的唯一入口 ——
83
+ * 系统提示词只给全部工具的**名字 + 一行摘要**,模型先把要用的名字交给它,那些
84
+ * 工具的完整参数 schema 才会进入会话(SDK 中途新增工具,支持 defer_loading /
85
+ * tool_search 的供应商不会把它们堆在首轮)。 */
86
+ export const LOAD_TOOLS_TOOL_NAME = "load_tools";
87
+ /** 延迟加载模式下**永远活跃**的核心工具(其余全部先当未加载)。 */
88
+ export const LAZY_CORE_TOOL_NAMES = ["bash", "read", "edit", "write"];
81
89
  /** 旧工具名(持久化迁移用;新代码一律用 MARKERS_LIST_TOOL_NAME)。 */
82
90
  export const LEGACY_MARKERS_LIST_TOOL_NAME = "markers_list";
83
- /** 可开关的 Agent 工具总目录(共 27 个)。核心内置工具 bash/read/edit/write 不进
91
+ /** 可开关的 Agent 工具总目录(共 23 个)。核心内置工具 bash/read/edit/write 不进
84
92
  * 目录——目录条目 = OTHER_AGENT_TOOLS 自动渲染的设置行,而这四个在设置页
85
93
  * 「核心工具」区单独开关(见 SettingsModal 的 CORE_BUILTIN_TOOL_NAMES 区块),
86
94
  * 禁用名单同样接受它们(normalizeDisabledAgentTools)。 */
@@ -206,26 +214,10 @@ export const AGENT_TOOL_CATALOG = [
206
214
  descKey: "evalEnabledDesc",
207
215
  offHintKey: "evalOffHint",
208
216
  },
209
- // 定时/延时唤醒:默认开(不打开 AI 根本不知道能定时;60s 间隔底线+面板可随时取消),
210
- // DSH 引擎没有该 customTool(走 goal-rpc,无 customTool 注册面)。
217
+ // 定时/延时唤醒(单 action:create/list/cancel):默认开(不打开 AI 根本不知道能定时;
218
+ // 60s 间隔底线+面板可随时取消),DSH 引擎没有该 customTool(走 goal-rpc,无 customTool 注册面)。
211
219
  {
212
- name: SCHEDULE_TASK_TOOL_NAME,
213
- group: "other",
214
- defaultOn: true,
215
- dshVisible: false,
216
- descKey: "scheduleTaskEnabledDesc",
217
- offHintKey: "scheduleTaskOffHint",
218
- },
219
- {
220
- name: SCHEDULE_LIST_TOOL_NAME,
221
- group: "other",
222
- defaultOn: true,
223
- dshVisible: false,
224
- descKey: "scheduleTaskEnabledDesc",
225
- offHintKey: "scheduleTaskOffHint",
226
- },
227
- {
228
- name: SCHEDULE_CANCEL_TOOL_NAME,
220
+ name: SCHEDULE_TOOL_NAME,
229
221
  group: "other",
230
222
  defaultOn: true,
231
223
  dshVisible: false,
@@ -259,10 +251,32 @@ export function isCoreBuiltinTool(name) {
259
251
  return CORE_BUILTIN_TOOL_NAMES.includes(name);
260
252
  }
261
253
  const KNOWN_NAMES = new Set(AGENT_TOOL_CATALOG.map((t) => t.name));
254
+ /** 全部已知可开关工具与核心内置工具全集(共 31 个)。用于白名单收敛与默认关闭推导。 */
255
+ export const ALL_KNOWN_AGENT_TOOL_NAMES = [
256
+ ...AGENT_TOOL_CATALOG.map((t) => t.name),
257
+ ...CORE_BUILTIN_TOOL_NAMES,
258
+ ];
262
259
  /** 是否为本表登记的可开关工具(未知名一律 false,不抛错)。 */
263
260
  export function isKnownAgentTool(name) {
264
261
  return KNOWN_NAMES.has(name);
265
262
  }
263
+ /** 是否为预设可配置的有效工具(目录登记工具 ∪ 核心内置工具)。 */
264
+ export function isConfigurableAgentTool(name) {
265
+ return KNOWN_NAMES.has(name) || isCoreBuiltinTool(name);
266
+ }
267
+ /** 根据禁用名单计算出当前系统中真正启用的可用工具列表(只取当前系统可用的配置)。 */
268
+ export function resolveEnabledAgentTools(disabled) {
269
+ const disabledSet = new Set(disabled);
270
+ return ALL_KNOWN_AGENT_TOOL_NAMES.filter((name) => !disabledSet.has(name));
271
+ }
272
+ /**
273
+ * 依据显式启用的工具白名单推导禁用列表:**默认没有开的工具就是关**。
274
+ * 凡是不在 enabled 列表里的当前系统已知工具,一律归入禁用名单,防止系统升级增加新工具时意外隐式开启。
275
+ */
276
+ export function resolveDisabledAgentToolsFromEnabled(enabled) {
277
+ const enabledSet = new Set(enabled);
278
+ return ALL_KNOWN_AGENT_TOOL_NAMES.filter((name) => !enabledSet.has(name));
279
+ }
266
280
  /** 归一化禁用名单:非数组回落默认(= 默认关的那些);数组则只保留已知工具名
267
281
  * (去重;未知名丢弃,防旧文件/手写脏数据污染)。支持登记核心内置工具。 */
268
282
  export function normalizeDisabledAgentTools(v) {
@@ -276,6 +290,10 @@ export function normalizeDisabledAgentTools(v) {
276
290
  if (typeof name === "string" && LEGACY_SUBAGENT_TOOL_NAMES.includes(name)) {
277
291
  name = SUBAGENT_TOOL_NAME;
278
292
  }
293
+ // 旧版定时任务三件套迁移:任意旧 schedule_* 关闭均迁移为关闭 schedule 工具(#193)。
294
+ if (typeof name === "string" && LEGACY_SCHEDULE_TOOL_NAMES.includes(name)) {
295
+ name = SCHEDULE_TOOL_NAME;
296
+ }
279
297
  if (typeof name === "string" && (KNOWN_NAMES.has(name) || isCoreBuiltinTool(name)) && !out.includes(name)) {
280
298
  out.push(name);
281
299
  }
@@ -339,7 +357,7 @@ export function setAgentToolsEnabled(session, names, on) {
339
357
  * 复原基线取 session.getAllTools()(全集,含被禁用的)——基线里没有的工具不会凭空发明。
340
358
  * Session 未就绪时静默跳过(下次创建/reload 会再应用)。
341
359
  */
342
- export function applyAgentToolsGating(session, disabled, preset) {
360
+ export function applyAgentToolsGating(session, disabled, preset, options) {
343
361
  try {
344
362
  const off = new Set(disabled);
345
363
  const allNames = session.getAllTools().map((t) => t.name);
@@ -366,12 +384,30 @@ export function applyAgentToolsGating(session, disabled, preset) {
366
384
  names.add(core);
367
385
  }
368
386
  const filtered = filterToolsByPreset(names, preset);
369
- session.setActiveToolsByName(filtered);
387
+ const active = new Set(filtered);
388
+ const baseline = new Set(allNames);
389
+ for (const name of options?.forceActive ?? []) {
390
+ if (baseline.has(name) && !off.has(name))
391
+ active.add(name);
392
+ }
393
+ session.setActiveToolsByName([...active]);
370
394
  }
371
395
  catch {
372
396
  // Session 未就绪——下次创建/reload 会再应用。
373
397
  }
374
398
  }
399
+ /**
400
+ * 延迟加载:把「除核心工具 / 已加载 / load_tools 之外的已登记工具」算成临时禁用名单,
401
+ * 直接交给 applyAgentToolsGating。
402
+ *
403
+ * 用禁用名单而不是另加一套机制:`applyAgentToolsGating` 本来就是「按名字加减活跃集」,
404
+ * 于是延迟加载不引入第二条门控路径,与用户禁用名单 / 计划·审查闸门同一条链——
405
+ * 加载只是把名字从这份名单里拿出来。
406
+ */
407
+ export function lazyLoadingDisabledTools(allNames, loaded, core = LAZY_CORE_TOOL_NAMES) {
408
+ const keep = new Set([...core, LOAD_TOOLS_TOOL_NAME, ...loaded]);
409
+ return allNames.filter((n) => !keep.has(n));
410
+ }
375
411
  /** pi 引擎内置 Agent 预设名录(对齐 DSH 预设体系,会话级工具白名单)。 */
376
412
  export const PI_AGENT_PRESETS = [
377
413
  {
@@ -0,0 +1,158 @@
1
+ /** 各字段上限:与 `tool-info.ts` 的下发上限同口径,防扩展/手抖写疯。 */
2
+ export const TOOL_PROMPT_DESCRIPTION_CAP = 8_000;
3
+ export const TOOL_PROMPT_SNIPPET_CAP = 8_000;
4
+ /** promptGuidelines 合计字数上限(多条要点共享)。 */
5
+ export const TOOL_PROMPT_GUIDELINE_CAP = 8_000;
6
+ /** promptGuidelines 条数上限。 */
7
+ export const TOOL_PROMPT_GUIDELINE_MAX = 50;
8
+ /** 覆盖项数上限(一个工作区正常几十个工具;防脏存档无限膨胀)。 */
9
+ export const TOOL_PROMPT_OVERRIDE_MAX = 500;
10
+ function trimmedString(v, cap) {
11
+ if (typeof v !== "string")
12
+ return undefined;
13
+ const s = v.trim();
14
+ if (!s)
15
+ return undefined;
16
+ return s.length > cap ? s.slice(0, cap) : s;
17
+ }
18
+ /**
19
+ * 归一化单条覆盖:只保留非空字段;全空 → null(= 没有覆盖)。
20
+ * 空串/空白/非字符串一律当「没设置」,与 `promptOverrides` 的口径一致。
21
+ */
22
+ export function normalizeToolPromptOverride(v) {
23
+ if (!v || typeof v !== "object")
24
+ return null;
25
+ const src = v;
26
+ const out = {};
27
+ const description = trimmedString(src.description, TOOL_PROMPT_DESCRIPTION_CAP);
28
+ if (description)
29
+ out.description = description;
30
+ const promptSnippet = trimmedString(src.promptSnippet, TOOL_PROMPT_SNIPPET_CAP);
31
+ if (promptSnippet)
32
+ out.promptSnippet = promptSnippet;
33
+ if (Array.isArray(src.promptGuidelines)) {
34
+ const guidelines = [];
35
+ let total = 0;
36
+ for (const g of src.promptGuidelines) {
37
+ const text = trimmedString(g, TOOL_PROMPT_GUIDELINE_CAP);
38
+ if (!text)
39
+ continue;
40
+ if (guidelines.length >= TOOL_PROMPT_GUIDELINE_MAX)
41
+ break;
42
+ if (total + text.length > TOOL_PROMPT_GUIDELINE_CAP)
43
+ break;
44
+ guidelines.push(text);
45
+ total += text.length;
46
+ }
47
+ if (guidelines.length > 0)
48
+ out.promptGuidelines = guidelines;
49
+ }
50
+ return Object.keys(out).length > 0 ? out : null;
51
+ }
52
+ /** 归一化整张覆盖表:丢掉空项/空对象/非字符串键;超出上限的条目截断。
53
+ * 当传入 knownTools 时,只取当前系统已知可用的工具配置,丢弃未知或不可用工具,防后期漂移或脏数据。 */
54
+ export function normalizeToolPromptOverrides(v, knownTools) {
55
+ if (!v || typeof v !== "object" || Array.isArray(v))
56
+ return {};
57
+ const out = {};
58
+ let count = 0;
59
+ const isKnown = (key) => {
60
+ if (!knownTools)
61
+ return true;
62
+ if (knownTools instanceof Set)
63
+ return knownTools.has(key);
64
+ return knownTools.includes(key);
65
+ };
66
+ for (const [name, raw] of Object.entries(v)) {
67
+ const key = name.trim();
68
+ if (!key || !isKnown(key))
69
+ continue;
70
+ const ov = normalizeToolPromptOverride(raw);
71
+ if (!ov)
72
+ continue;
73
+ if (count >= TOOL_PROMPT_OVERRIDE_MAX)
74
+ break;
75
+ out[key] = ov;
76
+ count++;
77
+ }
78
+ return out;
79
+ }
80
+ /** 取某工具的有效覆盖(没有 → null)。 */
81
+ export function toolPromptOverrideOf(map, name) {
82
+ const ov = map?.[name];
83
+ return ov && Object.keys(ov).length > 0 ? ov : null;
84
+ }
85
+ /** 叠加覆盖后的有效文案(覆盖字段优先,缺省回落默认)。 */
86
+ export function effectiveToolPrompt(base, override) {
87
+ if (!override)
88
+ return { ...base };
89
+ const out = { ...base };
90
+ if (override.description)
91
+ out.description = override.description;
92
+ if (override.promptSnippet)
93
+ out.promptSnippet = override.promptSnippet;
94
+ if (override.promptGuidelines)
95
+ out.promptGuidelines = [...override.promptGuidelines];
96
+ return out;
97
+ }
98
+ /**
99
+ * 把覆盖表打进会话:返回被覆盖的工具名;会话结构不符(SDK 改私有字段名)返回 null。
100
+ *
101
+ * 幂等:每次都用 `_toolDefinitions` 的默认值重算,清空覆盖后再次 apply 会准确复原。
102
+ * 调用点见 `agent-service.ts` 的 `applyToolGating()`(会话创建/设置变更/插件 sync 后统一重放)。
103
+ */
104
+ export function applyToolPromptOverrides(session, overrides) {
105
+ const s = session;
106
+ const registry = s?._toolRegistry;
107
+ const definitions = s?._toolDefinitions;
108
+ if (!s || !(registry instanceof Map) || !(definitions instanceof Map))
109
+ return null;
110
+ const snippets = s._toolPromptSnippets;
111
+ const guidelines = s._toolPromptGuidelines;
112
+ const applied = [];
113
+ for (const [name, tool] of registry) {
114
+ if (!tool || typeof tool !== "object")
115
+ continue;
116
+ const base = definitions.get(name)?.definition;
117
+ if (!base)
118
+ continue;
119
+ const override = toolPromptOverrideOf(overrides, name);
120
+ // description:模型可见的 tool schema 主描述。
121
+ if (typeof base.description === "string") {
122
+ const next = override?.description ?? base.description;
123
+ if (tool.description !== next)
124
+ tool.description = next;
125
+ }
126
+ // promptSnippet:系统提示词 Available tools 列表。
127
+ if (snippets instanceof Map) {
128
+ const next = override?.promptSnippet ?? base.promptSnippet;
129
+ if (typeof next === "string" && next.trim())
130
+ snippets.set(name, next);
131
+ else
132
+ snippets.delete(name);
133
+ }
134
+ // promptGuidelines:系统提示词 Guidelines 段。
135
+ if (guidelines instanceof Map) {
136
+ const next = override?.promptGuidelines ?? base.promptGuidelines;
137
+ if (Array.isArray(next) && next.length > 0)
138
+ guidelines.set(name, [...next]);
139
+ else
140
+ guidelines.delete(name);
141
+ }
142
+ if (override)
143
+ applied.push(name);
144
+ }
145
+ // 上面的 snippet/guidelines 补丁改的是 SDK 内部表,而 `_baseSystemPromptOptions`
146
+ // 是在 `setActiveToolsByName()` 里**快照**这两个表的 —— 不重建的话,当 web-ui 自己
147
+ // 不重渲染提示词(完全默认态)时模型会拿到旧 snippet。用当前活跃集重放一次即可
148
+ // (同时把带新 description 的包装工具重新装进 `agent.state.tools`)。
149
+ if (typeof s.getActiveToolNames === "function" && typeof s.setActiveToolsByName === "function") {
150
+ try {
151
+ s.setActiveToolsByName(s.getActiveToolNames());
152
+ }
153
+ catch {
154
+ // 活跃集校验失败不该让覆盖整体失效:跳过重建,只当提示词快照未刷新。
155
+ }
156
+ }
157
+ return applied;
158
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * bash 工具「模型可见」部分的唯一事实源。
3
+ *
4
+ * 同一个 bash 工具存在三条执行路径(原生 SDK bash / 终端接管 bash / 由
5
+ * `makeAdaptiveBashTool` 在两者间动态分流),但模型只看到**一份**工具定义:
6
+ * 分流器用 `{...killable}` 覆盖 name/label/parameters/execute,提示词从本模块取。
7
+ * 历史上三条路径各写一份 description/snippet(且终端那份经分流器覆盖后**永不发送**),
8
+ * 结果是文案漂移——"prefer head/tail over piping" 只写在死的那份里。集中到此处后
9
+ * 新增分支只需复用,不再各自维护。
10
+ */
11
+ import { Type } from "typebox";
12
+ /** 主描述:做什么 + 副作用/边界(不写「什么时候用」,那是 guidelines 的活)。 */
13
+ export const BASH_DESCRIPTION = "Run a shell command and return its full output plus exit code. " +
14
+ "When the terminal-backed bash is active (setting: default bash override) it runs in a visible terminal: " +
15
+ "persist=true keeps the 'ai-bash' terminal alive (cd/venv/ssh retained across calls), persist=false is one-shot; " +
16
+ "otherwise it runs natively (process spawn, no terminal) and persist has no effect. " +
17
+ "Never pipe through head/tail/more/less — use the head/tail params (pipes hide live progress).";
18
+ /** 触发条件(进系统提示词 Available tools 列表,渲染为 `- bash: <snippet>`)。 */
19
+ export const BASH_PROMPT_SNIPPET = "run shell commands";
20
+ /** 行为要点:只在「何时用/顺序/禁止」上说 description 没说的事。 */
21
+ export const BASH_PROMPT_GUIDELINES = [
22
+ "For interactive commands (REPLs, y/n prompts) set persist=true and drive them with terminal_input / terminal_key",
23
+ ];
24
+ /** 参数 schema(含参数说明):三条执行路径共用,避免「分流后 schema 变陌生」。 */
25
+ export const BASH_PARAMETERS = Type.Object({
26
+ command: Type.String({ description: "The shell command to run" }),
27
+ timeout: Type.Optional(Type.Number({ description: "Optional timeout in seconds" })),
28
+ persist: Type.Optional(Type.Boolean({
29
+ description: "Ignored in native mode. With the terminal-backed bash: true = persistent 'ai-bash' terminal " +
30
+ "(shell state retained across calls), false = one-shot terminal.",
31
+ })),
32
+ head: Type.Optional(Type.Integer({
33
+ minimum: 1,
34
+ maximum: 5000,
35
+ description: "Only return the FIRST N lines of output (like `| head -N`).",
36
+ })),
37
+ tail: Type.Optional(Type.Integer({
38
+ minimum: 1,
39
+ maximum: 5000,
40
+ description: "Only return the LAST N lines of output (like `| tail -N`).",
41
+ })),
42
+ });
@@ -0,0 +1,104 @@
1
+ /**
2
+ * server/tool-signature.ts
3
+ *
4
+ * Generates compact parameter signatures with concise English hints (1-2 words / <= 20 chars)
5
+ * and produces lightweight shallow schemas (skeleton schemas) from tool JSON Schema / TypeBox definitions.
6
+ *
7
+ * Strictly pure English to keep model prompts concise and conform to hygiene guards.
8
+ */
9
+ /** Clean and extract a concise English hint from a parameter's schema. */
10
+ export function extractConciseParamHint(prop) {
11
+ if (!prop || typeof prop !== "object")
12
+ return "";
13
+ const p = prop;
14
+ const desc = (p.description || "").trim();
15
+ if (desc) {
16
+ // Strip parenthetical notes like "(default 30)", "(1-indexed)"
17
+ const cleaned = desc.replace(/\([^)]*\)/g, "").trim();
18
+ // Take first clause before punctuation or newline
19
+ const clause = cleaned.split(/[,.;:—\n]/)[0]?.trim() || "";
20
+ // Strip leading articles/adjectives: "the", "optional", "a", "an"
21
+ const stripped = clause.replace(/^(the|optional|a|an)\s+/i, "").trim();
22
+ // Extract up to 2 words, max 20 chars, without truncating words
23
+ const words = stripped.split(/\s+/).filter(Boolean);
24
+ const picked = [];
25
+ let len = 0;
26
+ for (const w of words) {
27
+ if (picked.length >= 2)
28
+ break;
29
+ const nextLen = len === 0 ? w.length : len + 1 + w.length;
30
+ if (nextLen > 20) {
31
+ if (picked.length === 0)
32
+ picked.push(w.slice(0, 20));
33
+ break;
34
+ }
35
+ picked.push(w);
36
+ len = nextLen;
37
+ }
38
+ if (picked.length > 0)
39
+ return picked.join(" ");
40
+ }
41
+ if (p.type && typeof p.type === "string") {
42
+ return p.type;
43
+ }
44
+ return "";
45
+ }
46
+ /**
47
+ * Format a compact parameter signature for a tool definition's parameters:
48
+ * e.g. `(steps: step list, activeStepId?: step ID)`
49
+ */
50
+ export function formatCompactSignature(parameters) {
51
+ if (!parameters || typeof parameters !== "object")
52
+ return "";
53
+ const schema = parameters;
54
+ const props = schema.properties;
55
+ if (!props || typeof props !== "object" || Object.keys(props).length === 0) {
56
+ return "";
57
+ }
58
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
59
+ const entries = Object.entries(props);
60
+ // Limit to first 6 properties to keep lines compact
61
+ const visibleEntries = entries.slice(0, 6);
62
+ const formatted = visibleEntries.map(([key, val]) => {
63
+ const isReq = required.has(key);
64
+ const hint = extractConciseParamHint(val);
65
+ return `${key}${isReq ? "" : "?"}${hint ? `: ${hint}` : ""}`;
66
+ });
67
+ if (entries.length > visibleEntries.length) {
68
+ formatted.push("...");
69
+ }
70
+ return `(${formatted.join(", ")})`;
71
+ }
72
+ /**
73
+ * Creates a lightweight "shallow schema" (skeleton schema) from a full TypeBox / JSON Schema.
74
+ * Retains only top-level property types and concise hints while stripping heavy nested
75
+ * enum descriptions, complex sub-schemas, and markdown examples.
76
+ *
77
+ * Reduces token footprint by ~80-90% while keeping native function calling fully compatible.
78
+ */
79
+ export function createShallowSchema(parameters) {
80
+ if (!parameters || typeof parameters !== "object")
81
+ return undefined;
82
+ const schema = parameters;
83
+ const props = schema.properties;
84
+ if (!props || typeof props !== "object") {
85
+ return { type: schema.type || "object" };
86
+ }
87
+ const shallowProps = {};
88
+ for (const [key, val] of Object.entries(props)) {
89
+ if (!val || typeof val !== "object")
90
+ continue;
91
+ const p = val;
92
+ const hint = extractConciseParamHint(val);
93
+ shallowProps[key] = {
94
+ type: p.type || "string",
95
+ ...(hint ? { description: hint } : {}),
96
+ };
97
+ }
98
+ const req = Array.isArray(schema.required) ? schema.required : undefined;
99
+ return {
100
+ type: "object",
101
+ properties: shallowProps,
102
+ ...(req && req.length > 0 ? { required: req } : {}),
103
+ };
104
+ }
@@ -32,21 +32,6 @@ export function compareVersions(a, b) {
32
32
  }
33
33
  return 0;
34
34
  }
35
- /**
36
- * Cache a zero-arg function's value for ttlMs. Plain value memoization: the
37
- * pi probe returns null on failure instead of throwing, so errors thread
38
- * through as ordinary values and there is nothing to rethrow.
39
- */
40
- export function memoizeWithTtl(fn, ttlMs) {
41
- let entry = null;
42
- return () => {
43
- const now = Date.now();
44
- if (!entry || now - entry.at >= ttlMs) {
45
- entry = { at: now, value: fn() };
46
- }
47
- return entry.value;
48
- };
49
- }
50
35
  /**
51
36
  * Parse `pi --version` stdout into a version string, or null. Two-stage:
52
37
  * prefer a line that is exactly the version (optional leading "v", optional