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,158 @@
1
+ /**
2
+ * 内置默认审批规则(与 server/tool-approval.ts 既有内置检测表保持 100% 同口径与同一 id)。
3
+ */
4
+ export const DEFAULT_APPROVAL_RULES = [
5
+ {
6
+ id: "builtin.bash.rm-rf",
7
+ enabled: true,
8
+ tools: ["bash"],
9
+ field: "command",
10
+ match: "regex",
11
+ value: "\\brm\\s+((-[a-zA-Z0-9]*[rf][a-zA-Z0-9]*|--recursive|--force)\\s+)+(((\\/)|(~)|(\\.\\.)|(\\*)|(\\.\\/))|[a-zA-Z]:[\\\\/])",
12
+ action: "ask",
13
+ label: "递归/强制删除 (rm -rf)",
14
+ labelEn: "Recursive/force delete (rm -rf)",
15
+ reason: "检测到高风险的递归/强制删除大范围路径命令 (rm -rf)",
16
+ reasonEn: "Detected high-risk recursive/force deletion of wide paths (rm -rf)",
17
+ categoryId: "bash.rm-rf",
18
+ builtin: true,
19
+ },
20
+ {
21
+ id: "builtin.bash.win-del",
22
+ enabled: true,
23
+ tools: ["bash"],
24
+ field: "command",
25
+ match: "regex",
26
+ value: "\\b(del|rmdir|rd)\\s+[/\\-][fsq]",
27
+ action: "ask",
28
+ label: "Windows 强制删除 (del/rmdir/rd)",
29
+ labelEn: "Windows force delete (del/rmdir/rd)",
30
+ reason: "检测到高风险的 Windows 强制/递归删除目录命令 (del/rmdir/rd /s /q)",
31
+ reasonEn: "Detected high-risk Windows force/recursive deletion command (del/rmdir/rd /s /q)",
32
+ categoryId: "bash.win-del",
33
+ builtin: true,
34
+ },
35
+ {
36
+ id: "builtin.bash.disk",
37
+ enabled: true,
38
+ tools: ["bash"],
39
+ field: "command",
40
+ match: "regex",
41
+ value: "\\b(mkfs|format\\s+[a-zA-Z]:|dd\\s+if=)",
42
+ action: "ask",
43
+ label: "磁盘格式化/底层写入",
44
+ labelEn: "Disk format / raw block write",
45
+ reason: "检测到磁盘格式化或底层块写入危险命令 (format/mkfs/dd)",
46
+ reasonEn: "Detected dangerous disk formatting or raw block write command (format/mkfs/dd)",
47
+ categoryId: "bash.disk",
48
+ builtin: true,
49
+ },
50
+ {
51
+ id: "builtin.bash.git-destructive",
52
+ enabled: true,
53
+ tools: ["bash"],
54
+ field: "command",
55
+ match: "regex",
56
+ // git 全局选项前缀(-C <path> / -c k=v / --git-dir=…)、git.exe;push 强推 / +refspec / :branch 删远端;
57
+ // checkout . / restore . / stash drop|clear 丢弃未提交修改(restore --staged 只取消暂存,排除)。
58
+ // push 的参数区不跨 ; & | 换行,避免把后续命令里的 -f(如 `rm -f`)算进来(#578)。
59
+ value: "\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+(?:push\\s+(?:[^;&|\\n]*?\\s)?(?:--force|-[a-zA-Z0-9]*f)\\b|push\\s+(?:[^;&|\\n]*?\\s)?(?:\\+\\S+|:[^\\s/]\\S*)|reset\\s+--hard|clean\\s+(?:-[a-zA-Z]+\\s+)*-[a-zA-Z0-9]*f[a-zA-Z0-9]*|branch\\s+-[dD]\\b|checkout\\s+(?:--\\s+)?\\.(?=\\s|$|[;&|])|restore\\s+(?:--(?!staged\\b)\\S+\\s+)*\\.(?=\\s|$|[;&|])|stash\\s+(?:drop|clear)\\b)",
60
+ action: "ask",
61
+ label: "破坏性 Git 操作",
62
+ labelEn: "Destructive git operation",
63
+ reason: "检测到不可逆的破坏性 Git 操作 (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)",
64
+ reasonEn: "Detected irreversible destructive Git operation (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)",
65
+ categoryId: "bash.git-destructive",
66
+ builtin: true,
67
+ },
68
+ {
69
+ id: "builtin.bash.chmod",
70
+ enabled: true,
71
+ tools: ["bash"],
72
+ field: "command",
73
+ match: "regex",
74
+ value: "\\bchmod\\s+(-R\\s+)?(777|000)\\b",
75
+ action: "ask",
76
+ label: "危险权限修改 (chmod)",
77
+ labelEn: "Dangerous permission change (chmod)",
78
+ reason: "检测到过度开放或全局破坏性的文件权限修改 (chmod 777/000)",
79
+ reasonEn: "Detected overly permissive or globally destructive file permission change (chmod 777/000)",
80
+ categoryId: "bash.chmod",
81
+ builtin: true,
82
+ },
83
+ {
84
+ id: "builtin.bash.system-redirect",
85
+ enabled: true,
86
+ tools: ["bash"],
87
+ field: "command",
88
+ match: "regex",
89
+ value: ">\\s*(\\/etc\\/|\\/boot\\/|C:\\\\Windows)",
90
+ action: "ask",
91
+ label: "写入系统关键目录",
92
+ labelEn: "Write into system directories",
93
+ reason: "检测到重定向写入系统关键目录的危险操作",
94
+ reasonEn: "Detected dangerous redirection writing into critical system directories",
95
+ categoryId: "bash.system-redirect",
96
+ builtin: true,
97
+ },
98
+ {
99
+ id: "builtin.file.sensitive.env",
100
+ enabled: true,
101
+ tools: ["write", "edit", "edit_soft"],
102
+ field: "path",
103
+ match: "regex",
104
+ value: "(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$",
105
+ action: "ask",
106
+ label: "敏感配置 (.env)",
107
+ labelEn: "Sensitive config (.env)",
108
+ reason: "尝试修改敏感环境变量/密钥配置文件 (.env)",
109
+ reasonEn: "Attempting to modify sensitive environment/secret configuration (.env)",
110
+ categoryId: "file.sensitive.env",
111
+ builtin: true,
112
+ },
113
+ {
114
+ id: "builtin.file.sensitive.ssh",
115
+ enabled: true,
116
+ tools: ["write", "edit", "edit_soft"],
117
+ field: "path",
118
+ match: "regex",
119
+ value: "(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$",
120
+ action: "ask",
121
+ label: "SSH 密钥/凭据",
122
+ labelEn: "SSH keys / credentials",
123
+ reason: "尝试修改 SSH 密钥或认证凭据文件",
124
+ reasonEn: "Attempting to modify SSH keys or authentication credentials",
125
+ categoryId: "file.sensitive.ssh",
126
+ builtin: true,
127
+ },
128
+ {
129
+ id: "builtin.file.sensitive.shell",
130
+ enabled: true,
131
+ tools: ["write", "edit", "edit_soft"],
132
+ field: "path",
133
+ match: "regex",
134
+ value: "(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$",
135
+ action: "ask",
136
+ label: "Shell 启动配置",
137
+ labelEn: "Shell profile",
138
+ reason: "尝试修改用户全局 Shell 启动配置文件",
139
+ reasonEn: "Attempting to modify user global Shell profile configuration",
140
+ categoryId: "file.sensitive.shell",
141
+ builtin: true,
142
+ },
143
+ {
144
+ id: "builtin.file.outside-workspace",
145
+ enabled: true,
146
+ tools: ["write", "edit", "edit_soft"],
147
+ field: "path",
148
+ match: "outside_workspace",
149
+ value: "",
150
+ action: "ask",
151
+ label: "工作区外写入",
152
+ labelEn: "Write outside workspace",
153
+ reason: "尝试在工作区外部写入/修改文件",
154
+ reasonEn: "Attempting to write/modify file outside the workspace",
155
+ categoryId: "file.outside-workspace",
156
+ builtin: true,
157
+ },
158
+ ];
@@ -32,6 +32,8 @@
32
32
  import { existsSync, readFileSync, statSync } from "node:fs";
33
33
  import { resolve, sep } from "node:path";
34
34
  import { writeJsonAtomicSync } from "./atomic-file.js";
35
+ import { DEFAULT_APPROVAL_RULES } from "./approval-default-rules.js";
36
+ export { DEFAULT_APPROVAL_RULES };
35
37
  /**
36
38
  * 跨平台判定 target 路径是否严格位于 root 目录内部或就是 root 本身。
37
39
  * 针对 Windows 盘符大小写不敏感及正反斜杠统一进行规范化,防止 .. 路径穿越逃逸。
@@ -122,237 +124,181 @@ export function extractRuleFieldValue(field, toolName, params) {
122
124
  return "";
123
125
  }
124
126
  /**
125
- * 单条规则针对具体工具调用的匹配判定(纯函数)。
127
+ * 单条规则针对具体工具调用的匹配详情判定(纯函数,issue #566)。
128
+ * 匹配成功时返回匹配区间信息 { index, length, text },否则返回 null。
126
129
  */
127
- export function matchApprovalRule(rule, toolName, params, cwd, workspaceRoots = []) {
130
+ /** 单条规则在一段字段文本里的全部命中区间(issue #578)。regex 规则逐次扫描、不只取首个。 */
131
+ export function matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceRoots = []) {
128
132
  if (!rule.enabled)
129
- return false;
133
+ return [];
134
+ const targetTools = rule.tools.map((t) => t.trim().toLowerCase());
135
+ const toolMatches = targetTools.includes("*") || targetTools.includes(toolName.trim().toLowerCase());
136
+ if (!toolMatches)
137
+ return [];
138
+ if (rule.match === "regex") {
139
+ const fieldValue = extractRuleFieldValue(rule.field, toolName, params);
140
+ if (!fieldValue)
141
+ return [];
142
+ let re;
143
+ try {
144
+ re = new RegExp(rule.value, "gi");
145
+ }
146
+ catch {
147
+ return [];
148
+ }
149
+ const out = [];
150
+ for (let m = re.exec(fieldValue); m; m = re.exec(fieldValue)) {
151
+ if (m[0].length === 0) {
152
+ re.lastIndex++; // 空匹配推进一位,防死循环
153
+ continue;
154
+ }
155
+ out.push({ index: m.index, length: m[0].length, text: m[0] });
156
+ }
157
+ return out;
158
+ }
159
+ const single = matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots);
160
+ return single ? [single] : [];
161
+ }
162
+ export function matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots = []) {
163
+ if (!rule.enabled)
164
+ return null;
130
165
  // 1. 工具名匹配
131
166
  const targetTools = rule.tools.map((t) => t.trim().toLowerCase());
132
167
  const toolMatches = targetTools.includes("*") || targetTools.includes(toolName.trim().toLowerCase());
133
168
  if (!toolMatches)
134
- return false;
169
+ return null;
135
170
  // 2. 特殊匹配方式:outside_workspace(工作区外路径)
136
171
  if (rule.match === "outside_workspace") {
137
172
  const targetPath = extractRuleFieldValue("path", toolName, params);
138
173
  if (!targetPath)
139
- return false;
174
+ return null;
140
175
  // 无论相对或绝对路径,统一经 resolve(cwd, targetPath) 规范化并消除 ".."
141
176
  const abs = resolve(cwd, targetPath);
142
177
  const allRoots = [resolve(cwd), ...workspaceRoots.map((r) => resolve(r))];
143
178
  const inside = allRoots.some((r) => isPathInsideRoot(abs, r));
144
- return !inside;
179
+ if (!inside) {
180
+ return { index: 0, length: targetPath.length, text: targetPath };
181
+ }
182
+ return null;
145
183
  }
146
184
  // 3. 提取字段文本
147
185
  const fieldValue = extractRuleFieldValue(rule.field, toolName, params);
148
- // 4. 按 match kind 进行文本判定
186
+ if (!fieldValue)
187
+ return null;
188
+ // 4. 按 match kind 进行文本判定并提取命中区间
149
189
  switch (rule.match) {
150
190
  case "regex": {
151
191
  try {
152
192
  const re = new RegExp(rule.value, "i");
153
- return re.test(fieldValue);
193
+ const m = re.exec(fieldValue);
194
+ if (m) {
195
+ return {
196
+ index: m.index,
197
+ length: m[0].length,
198
+ text: m[0],
199
+ };
200
+ }
201
+ return null;
154
202
  }
155
203
  catch {
156
- return false;
204
+ return null;
157
205
  }
158
206
  }
159
207
  case "glob": {
160
208
  try {
161
209
  const re = globToRegex(rule.value);
162
- return re.test(fieldValue.replace(/\\/g, "/"));
210
+ const normalized = fieldValue.replace(/\\/g, "/");
211
+ if (re.test(normalized)) {
212
+ return { index: 0, length: fieldValue.length, text: fieldValue };
213
+ }
214
+ return null;
163
215
  }
164
216
  catch {
165
- return false;
217
+ return null;
166
218
  }
167
219
  }
168
220
  case "contains": {
169
- return fieldValue.toLowerCase().includes(rule.value.toLowerCase());
221
+ const idx = fieldValue.toLowerCase().indexOf(rule.value.toLowerCase());
222
+ if (idx >= 0) {
223
+ return {
224
+ index: idx,
225
+ length: rule.value.length,
226
+ text: fieldValue.slice(idx, idx + rule.value.length),
227
+ };
228
+ }
229
+ return null;
170
230
  }
171
231
  case "prefix": {
172
- return fieldValue.toLowerCase().startsWith(rule.value.toLowerCase());
232
+ if (fieldValue.toLowerCase().startsWith(rule.value.toLowerCase())) {
233
+ return {
234
+ index: 0,
235
+ length: rule.value.length,
236
+ text: fieldValue.slice(0, rule.value.length),
237
+ };
238
+ }
239
+ return null;
173
240
  }
174
241
  default:
175
- return false;
242
+ return null;
176
243
  }
177
244
  }
178
245
  /**
179
- * 完整评估规则列表对工具调用的决策(纯函数,按列表顺序首个匹配胜出)。
246
+ * 单条规则针对具体工具调用的匹配判定(纯函数)。
247
+ */
248
+ export function matchApprovalRule(rule, toolName, params, cwd, workspaceRoots = []) {
249
+ return matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots) !== null;
250
+ }
251
+ /**
252
+ * 完整评估规则列表对工具调用的决策(纯函数,按列表顺序首个匹配胜出,收集全部命中清单,issue #566)。
180
253
  */
181
254
  export function evaluateApprovalRules(rules, toolName, params, cwd, workspaceRoots = []) {
255
+ let primary = null;
256
+ const hits = [];
182
257
  for (const rule of rules) {
183
- if (matchApprovalRule(rule, toolName, params, cwd, workspaceRoots)) {
184
- const catId = rule.categoryId || rule.id;
185
- const category = {
186
- id: catId,
187
- label: rule.label,
188
- labelEn: rule.labelEn || rule.label,
189
- };
190
- return {
191
- action: rule.action,
192
- matchedRule: rule,
193
- reason: rule.reason || rule.label,
194
- reasonEn: rule.reasonEn || rule.labelEn || rule.label,
195
- category,
196
- };
258
+ // 同一规则可在一段命令里出现多次(如 `git reset --hard && git clean -fd`),全部列出(#578)。
259
+ for (const detail of matchApprovalRuleDetails(rule, toolName, params, cwd, workspaceRoots)) {
260
+ if (!primary) {
261
+ primary = {
262
+ action: rule.action,
263
+ matchedRule: rule,
264
+ reason: rule.reason || rule.label,
265
+ reasonEn: rule.reasonEn || rule.labelEn || rule.label,
266
+ category: {
267
+ id: rule.categoryId || rule.id,
268
+ label: rule.label,
269
+ labelEn: rule.labelEn || rule.label,
270
+ },
271
+ };
272
+ }
273
+ if (hits.length < 10) {
274
+ // 单条 text 超长时做截断,防止塞满 details 预算(硬限制 ≤64KB)
275
+ const safeText = detail.text.length > 200 ? `${detail.text.slice(0, 200)}…` : detail.text;
276
+ hits.push({
277
+ ruleId: rule.id,
278
+ label: rule.label,
279
+ labelEn: rule.labelEn || rule.label,
280
+ field: rule.field,
281
+ index: detail.index,
282
+ length: detail.length,
283
+ text: safeText,
284
+ });
285
+ }
197
286
  }
198
287
  }
288
+ if (primary) {
289
+ return {
290
+ ...primary,
291
+ hits: hits.length > 0 ? hits : undefined,
292
+ };
293
+ }
199
294
  return { action: "none" };
200
295
  }
201
- /**
202
- * 内置默认审批规则(与 server/tool-approval.ts 既有内置检测表保持 100% 同口径与同一 id)。
203
- */
204
- export const DEFAULT_APPROVAL_RULES = [
205
- {
206
- id: "builtin.bash.rm-rf",
207
- enabled: true,
208
- tools: ["bash"],
209
- field: "command",
210
- match: "regex",
211
- value: "\\brm\\s+((-[a-zA-Z0-9]*[rf][a-zA-Z0-9]*|--recursive|--force)\\s+)+(((\\/)|(~)|(\\.\\.)|(\\*)|(\\.\\/))|[a-zA-Z]:[\\\\/])",
212
- action: "ask",
213
- label: "递归/强制删除 (rm -rf)",
214
- labelEn: "Recursive/force delete (rm -rf)",
215
- reason: "检测到高风险的递归/强制删除大范围路径命令 (rm -rf)",
216
- reasonEn: "Detected high-risk recursive/force deletion of wide paths (rm -rf)",
217
- categoryId: "bash.rm-rf",
218
- builtin: true,
219
- },
220
- {
221
- id: "builtin.bash.win-del",
222
- enabled: true,
223
- tools: ["bash"],
224
- field: "command",
225
- match: "regex",
226
- value: "\\b(del|rmdir|rd)\\s+[/\\-][fsq]",
227
- action: "ask",
228
- label: "Windows 强制删除 (del/rmdir/rd)",
229
- labelEn: "Windows force delete (del/rmdir/rd)",
230
- reason: "检测到高风险的 Windows 强制/递归删除目录命令 (del/rmdir/rd /s /q)",
231
- reasonEn: "Detected high-risk Windows force/recursive deletion command (del/rmdir/rd /s /q)",
232
- categoryId: "bash.win-del",
233
- builtin: true,
234
- },
235
- {
236
- id: "builtin.bash.disk",
237
- enabled: true,
238
- tools: ["bash"],
239
- field: "command",
240
- match: "regex",
241
- value: "\\b(mkfs|format\\s+[a-zA-Z]:|dd\\s+if=)",
242
- action: "ask",
243
- label: "磁盘格式化/底层写入",
244
- labelEn: "Disk format / raw block write",
245
- reason: "检测到磁盘格式化或底层块写入危险命令 (format/mkfs/dd)",
246
- reasonEn: "Detected dangerous disk formatting or raw block write command (format/mkfs/dd)",
247
- categoryId: "bash.disk",
248
- builtin: true,
249
- },
250
- {
251
- id: "builtin.bash.git-destructive",
252
- enabled: true,
253
- tools: ["bash"],
254
- field: "command",
255
- match: "regex",
256
- value: "\\bgit\\s+(push\\s+.*?(--force|-[a-zA-Z0-9]*f)\\b|reset\\s+--hard|clean\\s+-[a-zA-Z0-9]*f|branch\\s+-[dD]\\b)",
257
- action: "ask",
258
- label: "破坏性 Git 操作",
259
- labelEn: "Destructive git operation",
260
- reason: "检测到不可逆的破坏性 Git 操作 (force push / reset --hard / clean -f)",
261
- reasonEn: "Detected irreversible destructive Git operation (force push / reset --hard / clean -f)",
262
- categoryId: "bash.git-destructive",
263
- builtin: true,
264
- },
265
- {
266
- id: "builtin.bash.chmod",
267
- enabled: true,
268
- tools: ["bash"],
269
- field: "command",
270
- match: "regex",
271
- value: "\\bchmod\\s+(-R\\s+)?(777|000)\\b",
272
- action: "ask",
273
- label: "危险权限修改 (chmod)",
274
- labelEn: "Dangerous permission change (chmod)",
275
- reason: "检测到过度开放或全局破坏性的文件权限修改 (chmod 777/000)",
276
- reasonEn: "Detected overly permissive or globally destructive file permission change (chmod 777/000)",
277
- categoryId: "bash.chmod",
278
- builtin: true,
279
- },
280
- {
281
- id: "builtin.bash.system-redirect",
282
- enabled: true,
283
- tools: ["bash"],
284
- field: "command",
285
- match: "regex",
286
- value: ">\\s*(\\/etc\\/|\\/boot\\/|C:\\\\Windows)",
287
- action: "ask",
288
- label: "写入系统关键目录",
289
- labelEn: "Write into system directories",
290
- reason: "检测到重定向写入系统关键目录的危险操作",
291
- reasonEn: "Detected dangerous redirection writing into critical system directories",
292
- categoryId: "bash.system-redirect",
293
- builtin: true,
294
- },
295
- {
296
- id: "builtin.file.sensitive.env",
297
- enabled: true,
298
- tools: ["write", "edit", "edit_soft"],
299
- field: "path",
300
- match: "regex",
301
- value: "(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$",
302
- action: "ask",
303
- label: "敏感配置 (.env)",
304
- labelEn: "Sensitive config (.env)",
305
- reason: "尝试修改敏感环境变量/密钥配置文件 (.env)",
306
- reasonEn: "Attempting to modify sensitive environment/secret configuration (.env)",
307
- categoryId: "file.sensitive.env",
308
- builtin: true,
309
- },
310
- {
311
- id: "builtin.file.sensitive.ssh",
312
- enabled: true,
313
- tools: ["write", "edit", "edit_soft"],
314
- field: "path",
315
- match: "regex",
316
- value: "(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$",
317
- action: "ask",
318
- label: "SSH 密钥/凭据",
319
- labelEn: "SSH keys / credentials",
320
- reason: "尝试修改 SSH 密钥或认证凭据文件",
321
- reasonEn: "Attempting to modify SSH keys or authentication credentials",
322
- categoryId: "file.sensitive.ssh",
323
- builtin: true,
324
- },
325
- {
326
- id: "builtin.file.sensitive.shell",
327
- enabled: true,
328
- tools: ["write", "edit", "edit_soft"],
329
- field: "path",
330
- match: "regex",
331
- value: "(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$",
332
- action: "ask",
333
- label: "Shell 启动配置",
334
- labelEn: "Shell profile",
335
- reason: "尝试修改用户全局 Shell 启动配置文件",
336
- reasonEn: "Attempting to modify user global Shell profile configuration",
337
- categoryId: "file.sensitive.shell",
338
- builtin: true,
339
- },
340
- {
341
- id: "builtin.file.outside-workspace",
342
- enabled: true,
343
- tools: ["write", "edit", "edit_soft"],
344
- field: "path",
345
- match: "outside_workspace",
346
- value: "",
347
- action: "ask",
348
- label: "工作区外写入",
349
- labelEn: "Write outside workspace",
350
- reason: "尝试在工作区外部写入/修改文件",
351
- reasonEn: "Attempting to write/modify file outside the workspace",
352
- categoryId: "file.outside-workspace",
353
- builtin: true,
354
- },
355
- ];
296
+ export function checkBashCommandDanger(command, rules = DEFAULT_APPROVAL_RULES) {
297
+ if (!command || typeof command !== "string")
298
+ return [];
299
+ const res = evaluateApprovalRules(rules, "bash", { command }, "");
300
+ return res.hits ?? [];
301
+ }
356
302
  /** 归一化输入规则。脏数据或非法规则返回 null。 */
357
303
  export function normalizeApprovalRule(raw) {
358
304
  if (!raw || typeof raw !== "object")
@@ -0,0 +1,94 @@
1
+ /**
2
+ * ask_user_question customTool:人机协作提问问卷工具。
3
+ *
4
+ * 模型需要澄清歧义需求、做重大技术路线决策时调用,向客户端弹出结构化问卷卡片。
5
+ * 从 agent-service.ts 抽出为独立模块。
6
+ */
7
+ import { Type } from "typebox";
8
+ /**
9
+ * askUser 签名带 {aborted} 快照而非完整 AbortSignal:customTool 的 execute 信号
10
+ * 服务于整个 agent 生命周期,这里按「已中止即拒绝」的最小语义处理,避免与其它
11
+ * 工具的取消逻辑纠缠。
12
+ */
13
+ export function makeAskUserQuestionTool(clientSession,
14
+ /** 本 runtime 所属会话:提问跟着对话走,快照只把当前对话的问卷推给客户端。 */
15
+ ownerId) {
16
+ const QuestionOptionSchema = Type.Object({
17
+ label: Type.String({ description: "Display label (1-5 words)" }),
18
+ description: Type.Optional(Type.String({
19
+ description: "Short explanation of impact/tradeoff",
20
+ })),
21
+ preview: Type.Optional(Type.String({
22
+ description: "Optional preview (markdown/HTML/code)",
23
+ })),
24
+ });
25
+ const QuestionSchema = Type.Object({
26
+ id: Type.String({ description: "Unique identifier (snake_case)" }),
27
+ question: Type.String({ description: "Question text (markdown/HTML ok)" }),
28
+ detail: Type.Optional(Type.String({ description: "Optional context under question" })),
29
+ header: Type.Optional(Type.String({ description: "Optional short header" })),
30
+ options: Type.Optional(Type.Array(QuestionOptionSchema, {
31
+ description: "2-4 choices (recommended option first)",
32
+ minItems: 2,
33
+ maxItems: 4,
34
+ })),
35
+ multiSelect: Type.Optional(Type.Boolean({ description: "Allow multiple choices (default: false)" })),
36
+ dependsOn: Type.Optional(Type.Object({
37
+ questionId: Type.String({ description: "Prior question ID" }),
38
+ value: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], {
39
+ description: "Show when prior answer matches",
40
+ })),
41
+ })),
42
+ optionsMap: Type.Optional(Type.Record(Type.String(), Type.Array(QuestionOptionSchema), {
43
+ description: "Dynamic options keyed by prior answer",
44
+ })),
45
+ });
46
+ return {
47
+ name: "ask_user_question",
48
+ label: "Ask the user",
49
+ description: "Ask the user 1-3 focused questions to clarify requirements, confirm decisions, or choose options. " +
50
+ "Renders a rich browser dialog; resumes on submit or cancel.",
51
+ promptSnippet: "clarify ambiguous requirements or confirm a decision with the user",
52
+ promptGuidelines: [
53
+ "When requirements are ambiguous, clarify with ask_user_question: 1 to 3 focused questions (prefer 1), 2-4 choices with the recommended option first, each with a concise impact/tradeoff",
54
+ "A cancelled question comes back as a tool error — respect it without immediately re-asking",
55
+ ],
56
+ parameters: Type.Object({
57
+ questions: Type.Array(QuestionSchema, {
58
+ description: "Questions to ask (prefer 1).",
59
+ minItems: 1,
60
+ maxItems: 3,
61
+ }),
62
+ }),
63
+ execute: async (_id, params, signal) => {
64
+ const qs = params.questions;
65
+ if (!Array.isArray(qs) || qs.length === 0) {
66
+ throw new Error("ask_user_question requires at least one question");
67
+ }
68
+ if (qs.length > 3) {
69
+ throw new Error("ask_user_question allows at most 3 questions per call to prevent question fatigue (单次提问最多不得超过 3 个问题)");
70
+ }
71
+ const answers = await clientSession.askUser(qs, {
72
+ aborted: signal?.aborted,
73
+ }, ownerId);
74
+ if (answers === null) {
75
+ throw new Error("User cancelled the question.\n用户取消了提问。");
76
+ }
77
+ // 工具结果:把每道题的回答拼成简洁文本给模型,同时留 details 供 UI 展示。
78
+ const lines = answers.map((a) => {
79
+ const q = qs.find((q) => q.id === a.id);
80
+ const label = a.selected.join(", ");
81
+ const custom = a.custom?.trim() ? ` (wrote: ${a.custom.trim()})` : "";
82
+ return `${q?.header ?? q?.id ?? a.id}: ${label || "(no selection)"}${custom}`;
83
+ });
84
+ return {
85
+ content: [{ type: "text", text: lines.join("\n") }],
86
+ details: { answers },
87
+ };
88
+ },
89
+ };
90
+ }
91
+ /** 判定是否应当即时向前端推送问卷弹窗(只推给当前前台会话,未指定会话按全局放行)。 */
92
+ export function shouldPopQuestion(conversationId, activeId) {
93
+ return conversationId === undefined || conversationId === activeId;
94
+ }
@@ -8,7 +8,7 @@
8
8
  * - 避免快照和消息列表随会话进行出现数兆字节 base64 的膨胀。
9
9
  */
10
10
  import { createHash, randomUUID } from "node:crypto";
11
- import { mkdirSync, existsSync, readdirSync } from "node:fs";
11
+ import { mkdirSync, existsSync, readdirSync, writeFileSync, renameSync, rmSync } from "node:fs";
12
12
  import { readFile, rename, rm, writeFile, stat } from "node:fs/promises";
13
13
  import { join, extname } from "node:path";
14
14
  let storeDir = "";
@@ -79,6 +79,43 @@ export async function saveAttachment(buffer, mimeType = "application/octet-strea
79
79
  filePath,
80
80
  };
81
81
  }
82
+ /**
83
+ * 将二进制内容写入附件存储(同步版本,供消息序列化等纯同步链路使用):
84
+ * 已存在同哈希文件则直接返回元数据,不重复写盘。
85
+ */
86
+ export function saveAttachmentSync(buffer, mimeType = "application/octet-stream", preferredExt) {
87
+ if (!storeDir) {
88
+ throw new Error("AttachmentStore has not been initialized with initAttachmentStore(dataDir)");
89
+ }
90
+ const hash = createHash("sha256").update(buffer).digest("hex");
91
+ const ext = preferredExt || MIME_EXT_MAP[mimeType] || ".bin";
92
+ const fileName = `${hash}${ext}`;
93
+ const filePath = join(storeDir, fileName);
94
+ if (!existsSync(filePath)) {
95
+ const tmpPath = `${filePath}.${randomUUID()}.tmp`;
96
+ try {
97
+ writeFileSync(tmpPath, buffer);
98
+ renameSync(tmpPath, filePath);
99
+ }
100
+ catch (err) {
101
+ try {
102
+ rmSync(tmpPath, { force: true });
103
+ }
104
+ catch { }
105
+ const code = err.code;
106
+ if (code !== "EEXIST" && code !== "EPERM")
107
+ throw err;
108
+ }
109
+ }
110
+ return {
111
+ hash,
112
+ size: buffer.length,
113
+ mimeType,
114
+ ext,
115
+ url: `/api/attachment/${hash}`,
116
+ filePath,
117
+ };
118
+ }
82
119
  /**
83
120
  * 根据哈希查找已存储的附件文件路径及元数据。
84
121
  */