pi-web-ui 0.99.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 (66) hide show
  1. package/CHANGELOG.md +53 -2
  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 +1160 -149
  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 +4 -5
  18. package/dist/server/goal-evidence.js +173 -0
  19. package/dist/server/goal-service.js +48 -8
  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/patch-remote-catalog.js +28 -10
  28. package/dist/server/patch-tool.js +9 -8
  29. package/dist/server/plan-mode.js +7 -6
  30. package/dist/server/plugin-api-catalog.js +10 -3
  31. package/dist/server/plugin-conversation-view.js +47 -0
  32. package/dist/server/plugins.js +113 -26
  33. package/dist/server/present-files-tool.js +10 -11
  34. package/dist/server/preset-fields.js +693 -0
  35. package/dist/server/preset-share.js +1178 -0
  36. package/dist/server/prompt-composer.js +23 -9
  37. package/dist/server/protocol-version.js +1 -1
  38. package/dist/server/read-tool.js +8 -10
  39. package/dist/server/resolve-global-sdk.js +80 -18
  40. package/dist/server/schedule-agent-tool.js +147 -146
  41. package/dist/server/sdk-origin.js +125 -37
  42. package/dist/server/settings-service.js +103 -84
  43. package/dist/server/skill-tool.js +3 -4
  44. package/dist/server/subagents.js +15 -22
  45. package/dist/server/terminals.js +16 -33
  46. package/dist/server/tool-approval.js +3 -1
  47. package/dist/server/tool-manager.js +63 -27
  48. package/dist/server/tool-prompt-overrides.js +158 -0
  49. package/dist/server/tool-prompts.js +42 -0
  50. package/dist/server/tool-signature.js +104 -0
  51. package/dist/server/workspace-snapshot.js +42 -11
  52. package/package.json +5 -3
  53. package/plugin-sdk/README.md +8 -4
  54. package/plugin-sdk/import-check.mjs +210 -0
  55. package/plugin-sdk/index.d.ts +4 -1
  56. package/plugin-sdk/index.mjs +1 -0
  57. package/plugins/catalog.json +33 -2
  58. package/themes/zhupi-dark.css +1 -1
  59. package/themes/zhupi.css +1 -1
  60. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-C3I1Mc-C.js} +2 -2
  61. package/web/dist/assets/index-B-E2EM_0.css +1 -0
  62. package/web/dist/assets/index-BYumAaGi.js +379 -0
  63. package/web/dist/index.html +2 -2
  64. package/web/dist/sw.js +1 -1
  65. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  66. package/web/dist/assets/index-ByCBN4Kt.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) {
@@ -1623,31 +1624,12 @@ export function makeTerminalBashTool(terminals, opts) {
1623
1624
  return defineTool({
1624
1625
  name: "bash",
1625
1626
  label: "Run bash command",
1626
- description: "Run a shell command in a visible terminal; returns full output and exit code. " +
1627
- "persist=false (default): a fresh one-shot terminal per call; the shell exits after the command but its output stays viewable. " +
1628
- "persist=true: runs in the persistent 'ai-bash' terminal — shell state (cd/venv/ssh) is retained across calls; " +
1629
- "terminal_read/terminal_input/terminal_key observe or interact; terminal_wait blocks on backgrounded commands. " +
1630
- "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. " +
1631
- "For interactive commands (REPLs, y/n prompts) set persist=true and drive them with terminal_input / terminal_key.",
1632
- promptSnippet: "run shell commands (persist=true keeps the terminal alive across calls)",
1633
- parameters: Type.Object({
1634
- command: Type.String({ description: "The shell command to run" }),
1635
- timeout: Type.Optional(Type.Number({ description: "Optional timeout in seconds" })),
1636
- persist: Type.Optional(Type.Boolean({
1637
- description: "true → run in the persistent 'ai-bash' terminal: shell state (cd/venv/ssh) is retained across calls. " +
1638
- "false (default) → one-shot terminal that exits when the command finishes; output stays viewable.",
1639
- })),
1640
- head: Type.Optional(Type.Integer({
1641
- minimum: 1,
1642
- maximum: 5000,
1643
- description: "Only return the FIRST N lines of output (like `| head -N`); prefer this over piping through head.",
1644
- })),
1645
- tail: Type.Optional(Type.Integer({
1646
- minimum: 1,
1647
- maximum: 5000,
1648
- description: "Only return the LAST N lines of output (like `| tail -N`); prefer this over piping through tail.",
1649
- })),
1650
- }),
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,
1651
1633
  execute: async (_id, p, signal) => {
1652
1634
  const lang = opts.lang?.() ?? "en";
1653
1635
  const persist = p.persist ?? opts.defaultPersist();
@@ -1884,10 +1866,11 @@ lang, options) {
1884
1866
  defineTool({
1885
1867
  name: "terminal_create",
1886
1868
  label: "Create terminal",
1887
- description: "Create a named persistent interactive PTY. Interact via terminal_input / terminal_key, inspect output via terminal_read. " +
1888
- "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.",
1889
- promptSnippet: "run interactive programs or long-running servers in a persistent visible PTY (multi-step: " +
1890
- "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
+ ],
1891
1874
  parameters: Type.Object({
1892
1875
  terminalId: Type.String({ description: "Stable terminal name" }),
1893
1876
  cwd: Type.Optional(Type.String({ description: "Workspace-relative directory" })),
@@ -2000,10 +1983,10 @@ lang, options) {
2000
1983
  defineTool({
2001
1984
  name: "terminal_wait",
2002
1985
  label: "Wait for terminal command",
2003
- description: "Block until a command started through the BASH TOOL finishes (exit marker appears) or timeout — no polling. " +
2004
- "Only applies to bash-tool commands; commands sent via terminal_input have no completion marker — use terminal_read(waitMs=…) for those. " +
2005
- "Returns {finished, exitCode} plus output produced while waiting; finished=false means still running (call again).",
2006
- 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",
2007
1990
  parameters: Type.Object({
2008
1991
  terminalId: Type.String(),
2009
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
+ }
@@ -5,9 +5,11 @@
5
5
  *
6
6
  * 每次用户发起新任务或运行关键操作前,为当前工作区记录轻量快照引用(Git commit SHA)。
7
7
  * 机制:
8
- * - 利用独立的临时 GIT_INDEX_FILE,通过 `git add -A` + `git write-tree` + `git commit-tree` 生成独立 commit;
8
+ * - 利用独立的临时 GIT_INDEX_FILE,通过 `git add -A -- .` + `git write-tree` + `git commit-tree` 生成独立 commit;
9
+ * - 快照只覆盖对话 cwd 的**子树**(而非整个工作区),commit-tree 的顶层因此只有该子目录一个条目;
9
10
  * - 绝不改变用户现有的 HEAD、branch 指针、工作区文件或 .git/index;
10
- * - 回滚时若启用 restoreWorkspace,通过 `git checkout <snapshotRef> -- .` 与 `git clean -fd` 还原物理文件。
11
+ * - 回滚时若启用 restoreWorkspace,通过 `git checkout <snapshotRef> -- <prefix>` 与 `git clean -fd -- <prefix>`
12
+ * 只还原/清理 cwd 子树,绝不触碰同仓库的兄弟目录。
11
13
  */
12
14
  import { execFile } from "node:child_process";
13
15
  import { randomUUID } from "node:crypto";
@@ -46,8 +48,9 @@ export async function createWorkspaceSnapshot(cwd) {
46
48
  const tempIndex = join(gitDir, `temp-index-snapshot-${randomUUID()}`);
47
49
  const env = { GIT_INDEX_FILE: tempIndex };
48
50
  try {
49
- // 1. 将当前工作区所有改动(含未跟踪与新增)记录到临时 index
50
- await runGit(cwd, ["add", "-A"], env);
51
+ // 1. 将 cwd 子树(而非整个工作区)的当前改动(含未跟踪与新增)记录到临时 index;
52
+ // 暂存路径相对仓库根,write-tree 顶层因此只有该子目录一个条目
53
+ await runGit(cwd, ["add", "-A", "--", "."], env);
51
54
  // 2. 写入 tree 对象
52
55
  const tree = await runGit(cwd, ["write-tree"], env);
53
56
  if (!tree)
@@ -85,11 +88,16 @@ export async function createWorkspaceSnapshot(cwd) {
85
88
  }
86
89
  }
87
90
  /**
88
- * 将工作区物理文件还原到指定的快照状态。
91
+ * 将工作区物理文件还原到指定的快照状态,作用范围严格限定在 cwd 子树内。
89
92
  *
90
93
  * 执行步骤:
91
- * 1. `git read-tree -u --reset <snapshotRef>` 将 index 与工作区重置为快照树,并删除快照之后新增的文件;
92
- * 2. `git clean -fd` 清理快照之后新增的未跟踪文件与空目录。
94
+ * - 仓库根 cwd:使用原子 `git read-tree -u --reset` + `git clean -fd` 整仓还原(天然支持空仓库快照);
95
+ * - 子目录 cwd(pathspec 以 `:(top)` 锚定到仓库根的 cwd 前缀):
96
+ * 1. `git rm -r --cached -- <pathspec>` 把 cwd 子树移出 index(工作区文件不动),使快照中
97
+ * 不存在的文件退回未跟踪状态——这一步让 checkout 之外的「快照后新增且已 add」的文件也能被回滚;
98
+ * 2. `git checkout <snapshotRef> -- <pathspec>` 把快照内容写回 index 与工作区(恢复被修改/删除的跟踪文件,快照无该子树文件时容错跳过);
99
+ * 3. `git clean -fd -- <pathspec>` 清理快照之后新增的未跟踪文件与空目录。
100
+ * 同仓库的兄弟目录在以上任何一步都不受影响。
93
101
  */
94
102
  export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
95
103
  const gitDir = await gitDirOf(cwd);
@@ -99,10 +107,33 @@ export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
99
107
  try {
100
108
  // 验证 snapshotRef 合法性
101
109
  await runGit(cwd, ["rev-parse", "--verify", snapshotRef]);
102
- // 1. 将 index 和工作区彻底重置到快照树状态(自动清除快照中不存在的文件)
103
- await runGit(cwd, ["read-tree", "-u", "--reset", snapshotRef]);
104
- // 2. 清理新产生的未跟踪文件与目录
105
- await runGit(cwd, ["clean", "-fd"]);
110
+ // cwd 相对仓库根的前缀(子目录形如 `proj/`,仓库根为空串)。
111
+ const prefix = await runGit(cwd, ["rev-parse", "--show-prefix"]);
112
+ if (!prefix) {
113
+ // 仓库根 cwd:整仓还原,使用原子 read-tree --reset,旧实现经过长期验证且天然支持空仓库快照
114
+ await runGit(cwd, ["read-tree", "-u", "--reset", snapshotRef]);
115
+ await runGit(cwd, ["clean", "-fd"]);
116
+ return { success: true };
117
+ }
118
+ // 子目录 cwd:作用域收敛到该子树,不误伤同仓兄弟目录与仓库根
119
+ const pathspec = `:(top)${prefix}`;
120
+ // 1. 把 cwd 子树移出 index(不删除工作区文件),快照里不存在的文件由此退回未跟踪状态
121
+ await runGit(cwd, ["rm", "-r", "--cached", "--quiet", "--ignore-unmatch", "--", pathspec]);
122
+ // 2. 从快照树把 cwd 子树写回 index 与工作区(恢复被修改与被删除的跟踪文件)
123
+ // 注:若快照时刻该子树为空(快照树内无匹配文件),checkout 会报
124
+ // "did not match any file(s) known to git";此时快照树内本无文件,捕获忽略即可,
125
+ // 第 3 步 clean 会清理掉新增文件完成空状态还原。
126
+ try {
127
+ await runGit(cwd, ["checkout", snapshotRef, "--", pathspec]);
128
+ }
129
+ catch (checkoutErr) {
130
+ const errMsg = String(checkoutErr);
131
+ if (!errMsg.includes("did not match any file(s) known to git")) {
132
+ throw checkoutErr;
133
+ }
134
+ }
135
+ // 3. 清理快照之后新增的未跟踪文件与空目录(含第 1 步退回未跟踪的那些)
136
+ await runGit(cwd, ["clean", "-fd", "--", pathspec]);
106
137
  return { success: true };
107
138
  }
108
139
  catch (err) {