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
@@ -122,82 +122,154 @@ export function extractRuleFieldValue(field, toolName, params) {
122
122
  return "";
123
123
  }
124
124
  /**
125
- * 单条规则针对具体工具调用的匹配判定(纯函数)。
125
+ * 单条规则针对具体工具调用的匹配详情判定(纯函数,issue #566)。
126
+ * 匹配成功时返回匹配区间信息 { index, length, text },否则返回 null。
126
127
  */
127
- export function matchApprovalRule(rule, toolName, params, cwd, workspaceRoots = []) {
128
+ export function matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots = []) {
128
129
  if (!rule.enabled)
129
- return false;
130
+ return null;
130
131
  // 1. 工具名匹配
131
132
  const targetTools = rule.tools.map((t) => t.trim().toLowerCase());
132
133
  const toolMatches = targetTools.includes("*") || targetTools.includes(toolName.trim().toLowerCase());
133
134
  if (!toolMatches)
134
- return false;
135
+ return null;
135
136
  // 2. 特殊匹配方式:outside_workspace(工作区外路径)
136
137
  if (rule.match === "outside_workspace") {
137
138
  const targetPath = extractRuleFieldValue("path", toolName, params);
138
139
  if (!targetPath)
139
- return false;
140
+ return null;
140
141
  // 无论相对或绝对路径,统一经 resolve(cwd, targetPath) 规范化并消除 ".."
141
142
  const abs = resolve(cwd, targetPath);
142
143
  const allRoots = [resolve(cwd), ...workspaceRoots.map((r) => resolve(r))];
143
144
  const inside = allRoots.some((r) => isPathInsideRoot(abs, r));
144
- return !inside;
145
+ if (!inside) {
146
+ return { index: 0, length: targetPath.length, text: targetPath };
147
+ }
148
+ return null;
145
149
  }
146
150
  // 3. 提取字段文本
147
151
  const fieldValue = extractRuleFieldValue(rule.field, toolName, params);
148
- // 4. 按 match kind 进行文本判定
152
+ if (!fieldValue)
153
+ return null;
154
+ // 4. 按 match kind 进行文本判定并提取命中区间
149
155
  switch (rule.match) {
150
156
  case "regex": {
151
157
  try {
152
158
  const re = new RegExp(rule.value, "i");
153
- return re.test(fieldValue);
159
+ const m = re.exec(fieldValue);
160
+ if (m) {
161
+ return {
162
+ index: m.index,
163
+ length: m[0].length,
164
+ text: m[0],
165
+ };
166
+ }
167
+ return null;
154
168
  }
155
169
  catch {
156
- return false;
170
+ return null;
157
171
  }
158
172
  }
159
173
  case "glob": {
160
174
  try {
161
175
  const re = globToRegex(rule.value);
162
- return re.test(fieldValue.replace(/\\/g, "/"));
176
+ const normalized = fieldValue.replace(/\\/g, "/");
177
+ if (re.test(normalized)) {
178
+ return { index: 0, length: fieldValue.length, text: fieldValue };
179
+ }
180
+ return null;
163
181
  }
164
182
  catch {
165
- return false;
183
+ return null;
166
184
  }
167
185
  }
168
186
  case "contains": {
169
- return fieldValue.toLowerCase().includes(rule.value.toLowerCase());
187
+ const idx = fieldValue.toLowerCase().indexOf(rule.value.toLowerCase());
188
+ if (idx >= 0) {
189
+ return {
190
+ index: idx,
191
+ length: rule.value.length,
192
+ text: fieldValue.slice(idx, idx + rule.value.length),
193
+ };
194
+ }
195
+ return null;
170
196
  }
171
197
  case "prefix": {
172
- return fieldValue.toLowerCase().startsWith(rule.value.toLowerCase());
198
+ if (fieldValue.toLowerCase().startsWith(rule.value.toLowerCase())) {
199
+ return {
200
+ index: 0,
201
+ length: rule.value.length,
202
+ text: fieldValue.slice(0, rule.value.length),
203
+ };
204
+ }
205
+ return null;
173
206
  }
174
207
  default:
175
- return false;
208
+ return null;
176
209
  }
177
210
  }
178
211
  /**
179
- * 完整评估规则列表对工具调用的决策(纯函数,按列表顺序首个匹配胜出)。
212
+ * 单条规则针对具体工具调用的匹配判定(纯函数)。
213
+ */
214
+ export function matchApprovalRule(rule, toolName, params, cwd, workspaceRoots = []) {
215
+ return matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots) !== null;
216
+ }
217
+ /**
218
+ * 完整评估规则列表对工具调用的决策(纯函数,按列表顺序首个匹配胜出,收集全部命中清单,issue #566)。
180
219
  */
181
220
  export function evaluateApprovalRules(rules, toolName, params, cwd, workspaceRoots = []) {
221
+ let primary = null;
222
+ const hits = [];
182
223
  for (const rule of rules) {
183
- if (matchApprovalRule(rule, toolName, params, cwd, workspaceRoots)) {
224
+ const detail = matchApprovalRuleDetail(rule, toolName, params, cwd, workspaceRoots);
225
+ if (detail) {
184
226
  const catId = rule.categoryId || rule.id;
185
227
  const category = {
186
228
  id: catId,
187
229
  label: rule.label,
188
230
  labelEn: rule.labelEn || rule.label,
189
231
  };
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
- };
232
+ if (!primary) {
233
+ primary = {
234
+ action: rule.action,
235
+ matchedRule: rule,
236
+ reason: rule.reason || rule.label,
237
+ reasonEn: rule.reasonEn || rule.labelEn || rule.label,
238
+ category,
239
+ };
240
+ }
241
+ if (hits.length < 10) {
242
+ // 单条 text 超长时做截断,防止塞满 details 预算(硬限制 ≤64KB)
243
+ const safeText = detail.text.length > 200 ? `${detail.text.slice(0, 200)}…` : detail.text;
244
+ hits.push({
245
+ ruleId: rule.id,
246
+ label: rule.label,
247
+ labelEn: rule.labelEn || rule.label,
248
+ field: rule.field,
249
+ index: detail.index,
250
+ length: detail.length,
251
+ text: safeText,
252
+ });
253
+ }
197
254
  }
198
255
  }
256
+ if (primary) {
257
+ return {
258
+ ...primary,
259
+ hits: hits.length > 0 ? hits : undefined,
260
+ };
261
+ }
199
262
  return { action: "none" };
200
263
  }
264
+ /**
265
+ * 纯命令文本的高危规则快速检测(用于对话卡片终端行即时高亮与审查证据打标,issue #566)。
266
+ */
267
+ export function checkBashCommandDanger(command, rules = DEFAULT_APPROVAL_RULES) {
268
+ if (!command || typeof command !== "string")
269
+ return [];
270
+ const res = evaluateApprovalRules(rules, "bash", { command }, "");
271
+ return res.hits ?? [];
272
+ }
201
273
  /**
202
274
  * 内置默认审批规则(与 server/tool-approval.ts 既有内置检测表保持 100% 同口径与同一 id)。
203
275
  */
@@ -704,3 +704,58 @@ ${transcript}
704
704
  }
705
705
  return out;
706
706
  }
707
+ /**
708
+ * 判断一个会话 entry 是否是提问前置注入的 aside 卡片(附件/并行提醒等)。
709
+ * 这些消息由服务端的 prompt 前置阶段通过 sendCustomMessage 注入在用户提问消息之前。
710
+ */
711
+ export function isPromptAsideEntry(entry) {
712
+ if (!entry || typeof entry !== "object")
713
+ return false;
714
+ const e = entry;
715
+ const customType = e.customType ?? (e.type === "message" && e.message?.role === "custom" ? e.message.customType : undefined);
716
+ return ((e.type === "custom_message" || (e.type === "message" && e.message?.role === "custom")) &&
717
+ (customType === "file" || customType === "parallel-work-reminder"));
718
+ }
719
+ /**
720
+ * 判断一个 entry 是否为用户提问消息。
721
+ */
722
+ export function isUserMessageEntry(entry) {
723
+ if (!entry || typeof entry !== "object")
724
+ return false;
725
+ const e = entry;
726
+ return (e.type === "message" && e.message?.role === "user") || e.type === "user" || e.role === "user";
727
+ }
728
+ /**
729
+ * 从给定的 entry 节点开始,向上追溯属于该轮提问的前置附件 aside 节点(customType === "file" 等),
730
+ * 返回该轮提问之前的基准 entry id(作为 fork/分支截断点)。
731
+ * 如果追溯到会话根(即该提问是会话第一轮提问),返回 null。
732
+ */
733
+ export function findTurnBaseEntryId(sm, entryId) {
734
+ const target = sm.getEntry(entryId);
735
+ if (!target)
736
+ return null;
737
+ // 只有针对用户消息,才需要向上跳过属于该提问的前置附件 aside 卡片
738
+ if (!isUserMessageEntry(target)) {
739
+ const parentId = target.parentId;
740
+ return parentId ?? null;
741
+ }
742
+ let currentId = entryId;
743
+ while (currentId) {
744
+ const entry = sm.getEntry(currentId);
745
+ if (!entry)
746
+ break;
747
+ const parentId = entry.parentId;
748
+ if (!parentId)
749
+ return null;
750
+ const parentEntry = sm.getEntry(parentId);
751
+ if (!parentEntry)
752
+ return null;
753
+ if (isPromptAsideEntry(parentEntry)) {
754
+ currentId = parentId;
755
+ }
756
+ else {
757
+ return parentId;
758
+ }
759
+ }
760
+ return null;
761
+ }
@@ -2,6 +2,22 @@ import { killPidTree, lookupProcessName, lookupProcessCommandLine, snapshotListe
2
2
  const BG_REFRESH_INTERVAL_MS = 30_000;
3
3
  /** bash 结束后等这么久再拍「后」快照——给后台服务绑定端口的时间。 */
4
4
  const BG_BIND_WAIT_MS = 1500;
5
+ /** 自动清理时「闲置多久算遗留」的兜底阈值(分钟)——手动「立即清理」在策略为关时用它。 */
6
+ export const BG_CLEANUP_FALLBACK_MIN = 30;
7
+ /**
8
+ * 从当前列表里挑出「该被自动清理」的条目(纯函数,好测):
9
+ * - **钉住的(keep)不碰** —— 用户明确说要留的,永远不动;
10
+ * - 插件注册的任务不参与(它们不在这个列表里,由插件的 stop 回调负责);
11
+ * - 只看 `since`(宿主首次发现它的时间)与阈值,与是否还在跑无关(还在跑才会在列表里)。
12
+ * @param entries `{port, pid, since, keep?}` 列表
13
+ * @param opts `{ now, thresholdMs }`;thresholdMs ≤ 0 = 不清理
14
+ * @returns 待清理的条目(原样引用)
15
+ */
16
+ export function staleLeftovers(entries, opts) {
17
+ if (!Number.isFinite(opts.thresholdMs) || opts.thresholdMs <= 0)
18
+ return [];
19
+ return entries.filter((e) => !e.keep && Number.isFinite(e.since) && opts.now - e.since >= opts.thresholdMs);
20
+ }
5
21
  /**
6
22
  * 基本不可能由 AI 启动的常驻桌面软件进程名(小写)。命中即跳过,避免面板被
7
23
  * 微信/QQ 等本地软件的动态监听端口污染。注意 Chrome 不进黑名单:AI 会用
@@ -78,11 +94,19 @@ export class BgServerTracker {
78
94
  constructor(opts) {
79
95
  this.opts = opts;
80
96
  }
81
- /** 启动周期性存活检查(死项静默剔除)。 */
97
+ /** 启动周期性存活检查(死项静默剔除)+ 按策略自动清理遗留实例。 */
82
98
  start() {
83
- this.refreshTimer = setInterval(() => void this.refresh(), BG_REFRESH_INTERVAL_MS);
99
+ this.refreshTimer = setInterval(() => void this.tick(), BG_REFRESH_INTERVAL_MS);
84
100
  this.refreshTimer.unref?.();
85
101
  }
102
+ /** 一轮定时任务:先剔死项,再按策略清遗留(策略为 0 = 关,只剔不杀)。 */
103
+ async tick() {
104
+ await this.refresh();
105
+ const minutes = Number(this.opts.cleanupMinutes?.() ?? 0);
106
+ if (!Number.isFinite(minutes) || minutes <= 0)
107
+ return;
108
+ await this.cleanStale(minutes * 60_000, { manual: false });
109
+ }
86
110
  stop() {
87
111
  if (this.refreshTimer) {
88
112
  clearInterval(this.refreshTimer);
@@ -171,6 +195,7 @@ export class BgServerTracker {
171
195
  since: v.since,
172
196
  ...(v.name ? { name: v.name } : {}),
173
197
  ...(v.command ? { command: v.command } : {}),
198
+ ...(v.keep ? { keep: true } : {}),
174
199
  }))
175
200
  .sort((a, b) => a.since - b.since);
176
201
  for (const t of this.opts.pluginTasks?.() ?? [])
@@ -258,6 +283,61 @@ export class BgServerTracker {
258
283
  this.opts.flushSnapshot();
259
284
  return true;
260
285
  }
286
+ /** 钉住 / 取消钉住一个实例(自动清理跳过钉住的)。端口不在列表里 → 回一条 info 通知。 */
287
+ setKeep(port, keep) {
288
+ const entry = this.servers.get(port);
289
+ if (!entry) {
290
+ this.opts.emit({
291
+ type: "notice",
292
+ level: "info",
293
+ text: `端口 ${port} 不在后台任务列表中(可能已自行退出)`,
294
+ textEn: `Port ${port} is not in the background task list (it may have exited)`,
295
+ });
296
+ this.opts.flushSnapshot();
297
+ return false;
298
+ }
299
+ if (keep)
300
+ entry.keep = true;
301
+ else
302
+ delete entry.keep;
303
+ this.push();
304
+ return true;
305
+ }
306
+ /**
307
+ * 按阈值清理遗留实例:先复核端口→pid 归属(同 killOne,不对就剔条目绝不误杀),
308
+ * 再杀**未钉住**且闲置超阈值的那些,最后推一条汇总通知。
309
+ * @param manual 手动点「立即清理」:即使没东西可清也给一句反馈(否则点了像没反应)。
310
+ */
311
+ async cleanStale(thresholdMs, opts) {
312
+ await this.verifyBeforeKill();
313
+ const picked = staleLeftovers([...this.servers.entries()].map(([port, v]) => ({ port, ...v })), { now: Date.now(), thresholdMs });
314
+ if (picked.length === 0) {
315
+ if (opts.manual) {
316
+ this.opts.emit({
317
+ type: "notice",
318
+ level: "info",
319
+ text: `没有需要清理的遗留实例(阈值 ${Math.round(thresholdMs / 60_000)} 分钟,已钉住的不算)`,
320
+ textEn: `No leftover instance to clean (threshold ${Math.round(thresholdMs / 60_000)} min; kept ones excluded)`,
321
+ });
322
+ }
323
+ return [];
324
+ }
325
+ const killed = [];
326
+ for (const item of picked) {
327
+ killPidTree(item.pid);
328
+ this.servers.delete(item.port);
329
+ killed.push(item.port);
330
+ }
331
+ this.push();
332
+ this.opts.emit({
333
+ type: "notice",
334
+ level: "info",
335
+ text: `已清理 ${killed.length} 个遗留后台实例:端口 ${killed.join("、")}(闲置超 ${Math.round(thresholdMs / 60_000)} 分钟;可在面板里钉住想留的)`,
336
+ textEn: `Cleaned ${killed.length} leftover background instance(s): port ${killed.join(", ")} (idle over ${Math.round(thresholdMs / 60_000)} min; pin the ones you want to keep)`,
337
+ });
338
+ this.opts.flushSnapshot();
339
+ return killed;
340
+ }
261
341
  /** Kill every background server the agent started; returns the freed ports. */
262
342
  async killAll() {
263
343
  if (this.servers.size === 0)
@@ -30,10 +30,10 @@ export function makeClaimFilesTool(host, lang) {
30
30
  return defineTool({
31
31
  name: CLAIM_FILES_TOOL_NAME,
32
32
  label: "Claim files to avoid parallel conflicts",
33
- description: "Declare files you are about to edit so parallel runs in the same project steer clear (advisory only — never blocks edits). " +
34
- "claim reserves paths for THIS conversation (first wins; conflicts reported, not overridden); release frees yours (no paths = all yours); list shows the project's claim table. " +
35
- "Claims expire after ~30 min idle (your prompts refresh them) and release when the conversation closes. Paths must stay inside the project.",
36
- promptSnippet: "claim files you are about to edit (advisory, first-wins) so parallel runs steer clear",
33
+ description: "Declare files you are about to edit so parallel runs in the same project steer clear (advisory — never blocks edits). " +
34
+ "Claims expire after ~30 min idle (your prompts refresh them) and release when the conversation closes. " +
35
+ "Paths must stay inside the project.",
36
+ promptSnippet: "reserve files you are about to edit (parallel-run guard)",
37
37
  parameters: Type.Object({
38
38
  action: Type.Optional(Type.String({ description: 'claim = reserve paths; release = free yours; list = show table. Default "list".' })),
39
39
  paths: Type.Optional(Type.Array(Type.String(), { description: "claim/release only: file paths (inside the project)." })),
@@ -13,6 +13,7 @@ import { writeJsonAtomicSync } from "./atomic-file.js";
13
13
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { deriveLegacy, legacyToDisabled, normalizeDisabledAgentTools } from "./tool-manager.js";
15
15
  import { UI_SLOTS } from "./plugins.js";
16
+ import { normalizeToolPromptOverrides } from "./tool-prompt-overrides.js";
16
17
  /** 大模型 API 出错自动重试次数的默认值(SDK 默认 3)。 */
17
18
  export const DEFAULT_RETRY_MAX_ATTEMPTS = 6;
18
19
  /** 工具执行看门狗超时的默认值(默认 20 分钟;环境变量 PI_WEB_TOOL_TIMEOUT_MS 覆盖)。 */
@@ -29,6 +30,20 @@ export function normalizeToolWatchdogTimeoutMs(v) {
29
30
  return DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS;
30
31
  return n;
31
32
  }
33
+ /** 「后台任务」自动清理阈值的合法档位(分钟)。0 = 关。 */
34
+ export const BG_CLEANUP_MINUTES = [0, 15, 30, 60, 120];
35
+ /** 归一化自动清理阈值(分钟):只认档位表里的值(脏值按最近档位下取,负数/非数回落 0 = 关)。
36
+ * 默认关 —— 杀进程是破坏性动作,不替用户做主。 */
37
+ export function normalizeBgCleanupMinutes(v) {
38
+ const n = Math.floor(Number(v));
39
+ if (!Number.isFinite(n) || n <= 0)
40
+ return 0;
41
+ let best = 0;
42
+ for (const step of BG_CLEANUP_MINUTES)
43
+ if (step <= n && step > best)
44
+ best = step;
45
+ return best;
46
+ }
32
47
  /** 工具自己声明超时时留给它的余量(毫秒):让工具先自己超时并返回错误,
33
48
  * 而不是看门狗先下手把整轮对话 abort 掉。 */
34
49
  export const TOOL_WATCHDOG_EXPLICIT_GRACE_MS = 5_000;
@@ -216,6 +231,26 @@ export function normalizeUiLayout(v) {
216
231
  export function normalizeSkillList(v) {
217
232
  return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
218
233
  }
234
+ /** 工具延迟加载的**出厂默认**(默认开;`PI_WEB_TOOL_LAZY_LOADING=0/false/off` 部署级关掉,
235
+ * 给「不想让模型多一步 load_tools」的实例一个开关;用户在设置面板的选择优先于此)。 */
236
+ export const DEFAULT_TOOL_LAZY_LOADING = (() => {
237
+ const v = (process.env.PI_WEB_TOOL_LAZY_LOADING ?? "").trim().toLowerCase();
238
+ return !(v === "0" || v === "false" || v === "off" || v === "no");
239
+ })();
240
+ /** 预设 → 设置面板列表用的 UI 形状(协议要求字段完整:旧/部分预设用默认值补齐)。 */
241
+ export function settingsPresetToUi(p) {
242
+ return {
243
+ name: p.name,
244
+ promptMode: p.promptMode === "replace" ? "replace" : "append",
245
+ customSystemPrompt: p.customSystemPrompt ?? "",
246
+ promptTemplate: p.promptTemplate ?? "",
247
+ promptOverrides: { ...(p.promptOverrides ?? {}) },
248
+ disabledSkills: [...(p.disabledSkills ?? [])],
249
+ disabledExtensions: [...(p.disabledExtensions ?? [])],
250
+ reviewPrompt: p.reviewPrompt ?? "",
251
+ reviewDisabledSkills: [...(p.reviewDisabledSkills ?? [])],
252
+ };
253
+ }
219
254
  /** Stable identity of an extension for the enable/disable toggle: the npm
220
255
  * spec for packages (survives version bumps), the resolved entry path
221
256
  * otherwise. */
@@ -721,6 +756,7 @@ export class ClientStateStore {
721
756
  customSystemPrompt: stored?.customSystemPrompt ?? "",
722
757
  promptTemplate,
723
758
  promptOverrides,
759
+ toolPromptOverrides: normalizeToolPromptOverrides(stored?.toolPromptOverrides),
724
760
  disabledSkills: stored?.disabledSkills ?? [],
725
761
  disabledExtensions: stored?.disabledExtensions ?? [],
726
762
  disabledAgentTools: legacyToDisabled(stored ?? {}),
@@ -734,6 +770,8 @@ export class ClientStateStore {
734
770
  terminalBashMaxForegroundMs: stored?.terminalBashMaxForegroundMs ?? 60_000,
735
771
  toolWatchdogTimeoutMs: normalizeToolWatchdogTimeoutMs(stored?.toolWatchdogTimeoutMs),
736
772
  readDirEnabled: stored?.readDirEnabled ?? true,
773
+ bgAutoCleanupMin: normalizeBgCleanupMinutes(stored?.bgAutoCleanupMin),
774
+ toolLazyLoading: stored?.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
737
775
  toolApprovalEnabled: stored?.toolApprovalEnabled ?? true,
738
776
  editSoftEnabled: stored?.disabledAgentTools !== undefined
739
777
  ? deriveLegacy(legacyToDisabled(stored)).editSoftEnabled
@@ -785,6 +823,7 @@ export class ClientStateStore {
785
823
  customSystemPrompt: settings.customSystemPrompt ?? cur.customSystemPrompt ?? "",
786
824
  promptTemplate: settings.promptTemplate ?? cur.promptTemplate ?? "",
787
825
  promptOverrides: { ...(settings.promptOverrides ?? cur.promptOverrides) },
826
+ toolPromptOverrides: normalizeToolPromptOverrides(settings.toolPromptOverrides ?? cur.toolPromptOverrides),
788
827
  disabledSkills: settings.disabledSkills ?? cur.disabledSkills ?? [],
789
828
  disabledExtensions: settings.disabledExtensions ?? cur.disabledExtensions ?? [],
790
829
  disabledAgentTools: normalizeDisabledAgentTools(settings.disabledAgentTools ?? cur.disabledAgentTools),
@@ -795,6 +834,8 @@ export class ClientStateStore {
795
834
  terminalBashMaxForegroundMs: settings.terminalBashMaxForegroundMs ?? cur.terminalBashMaxForegroundMs ?? 60_000,
796
835
  toolWatchdogTimeoutMs: normalizeToolWatchdogTimeoutMs(settings.toolWatchdogTimeoutMs ?? cur.toolWatchdogTimeoutMs ?? DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS),
797
836
  readDirEnabled: settings.readDirEnabled ?? cur.readDirEnabled ?? true,
837
+ bgAutoCleanupMin: normalizeBgCleanupMinutes(settings.bgAutoCleanupMin ?? cur.bgAutoCleanupMin),
838
+ toolLazyLoading: settings.toolLazyLoading ?? cur.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
798
839
  toolApprovalEnabled: settings.toolApprovalEnabled ?? cur.toolApprovalEnabled ?? true,
799
840
  editSoftEnabled: settings.editSoftEnabled ?? cur.editSoftEnabled ?? false,
800
841
  questionnaireEnabled: settings.questionnaireEnabled ?? cur.questionnaireEnabled ?? true,
@@ -58,15 +58,17 @@ export function buildCompactionInstructions(focus, customSummary) {
58
58
  }
59
59
  export const CompactContextParams = Type.Object({
60
60
  focus: Type.String({
61
- description: "Compression focus and requirements for the current issue/task. State: 1) the active problem/goal; 2) context to PRESERVE (key decisions, code changes, conventions, user constraints); 3) what to REMOVE or condense (failed attempts, resolved debugging, off-topic history).",
61
+ description: "Compression focus for the current issue. State: 1) the active problem/goal; " +
62
+ "2) context to PRESERVE (decisions, code changes, conventions, constraints); " +
63
+ "3) what to REMOVE or condense (failed attempts, resolved debugging, off-topic history).",
62
64
  }),
63
65
  keepRecentTokens: Type.Optional(Type.Number({
64
66
  minimum: MIN_KEEP_RECENT_TOKENS,
65
67
  maximum: MAX_KEEP_RECENT_TOKENS,
66
- description: "Recent tokens to keep uncompacted (1000-100000). Smaller values (e.g. 3000-8000) compact more aggressively. Omit = auto-calculated from session size.",
68
+ description: "Recent tokens to keep uncompacted; smaller compacts more aggressively; omit = auto-calculated from session size.",
67
69
  })),
68
70
  summary: Type.Optional(Type.String({
69
- description: "Custom structured summary written by you; used as the core basis for the compaction entry if provided.",
71
+ description: "Optional structured summary; used as the basis for the compaction entry.",
70
72
  })),
71
73
  });
72
74
  export function makeCompactContextTool(host, lang) {
@@ -74,13 +76,12 @@ export function makeCompactContextTool(host, lang) {
74
76
  return defineTool({
75
77
  name: COMPACT_CONTEXT_TOOL_NAME,
76
78
  label: "Compact conversation context based on current issue",
77
- description: "Compress/compact the conversation context around the current task: specify what to preserve (key decisions, code structure, active requirements) and what to drop or heavily summarize (unrelated exploration, verbose outputs, resolved debugging). " +
78
- "Optionally control how many recent tokens stay untouched. Compaction executes when the current turn settles, refreshing context for subsequent turns.",
79
- promptSnippet: "proactively compact conversation context focusing on the current issue",
79
+ description: "Compress the conversation context around the current task. Compaction executes when the current turn settles, " +
80
+ "so the refreshed context applies from the next turn on.",
81
+ promptSnippet: "compact a long or noisy conversation context",
80
82
  promptGuidelines: [
81
- "Use compact_context when the conversation has grown long, or after extensive debugging/exploration, to focus context strictly on the current problem.",
82
- "Clearly specify in 'focus' what to keep (decisions, specs, active changes) and what to drop (failed attempts, voluminous command outputs).",
83
- "After calling compact_context, conclude your current turn with a brief wrap-up and next steps; the system executes compaction right after this turn finishes.",
83
+ "Use it when the conversation has grown long or after extensive exploration, to refocus context on the current problem.",
84
+ "After calling it, wrap up your turn with a brief summary and next steps.",
84
85
  ],
85
86
  parameters: CompactContextParams,
86
87
  execute: async (_id, p) => {
@@ -369,15 +369,14 @@ export function makeConversationReadTool(host, lang, extras) {
369
369
  return defineTool({
370
370
  name: CONVERSATION_READ_TOOL_NAME,
371
371
  label: "Read another conversation",
372
- description: "Read ANOTHER conversation: a running conversation of this client (incl. subagents — id from action=list) or a persisted history session (file path). " +
373
- "Use when the user references another chat. list: running + history sessions (query filter, limit). " +
374
- "read: one transcript — view=chat (default, user/assistant text) or full (incl. tool calls); last=N latest; query searches within (±1 context); messages capped ~600 chars. " +
375
- "files: files it created/modified. status: last tool call, last assistant text, pending question. " +
372
+ description: "Read ANOTHER conversation: a running conversation of this client (incl. subagents — id from action=list) " +
373
+ "or a persisted history session (file path). Use it whenever the user references another chat. " +
376
374
  "Only listed sessions are readable; other tabs' live runs appear in history once persisted.",
377
- promptSnippet: "read another conversation: list/find chats, read transcript (chat view / tail / search), touched files, status summary",
375
+ promptSnippet: "inspect another conversation the user mentions (list/read/files/status)",
378
376
  parameters: Type.Object({
379
377
  action: Type.Optional(Type.String({
380
- description: 'list = show running conversations + history sessions; read = fetch one transcript. Default "list".',
378
+ description: 'Default "list": running conversations + history sessions; read = one transcript (≤600 chars/msg); ' +
379
+ "files = files it created/modified; status = last tool call, last assistant text, pending question.",
381
380
  })),
382
381
  scope: Type.Optional(Type.String({
383
382
  description: 'list only: "current" = this project, "all" = every project. Default "all".',
@@ -391,14 +390,14 @@ export function makeConversationReadTool(host, lang, extras) {
391
390
  view: Type.Optional(Type.String({
392
391
  description: 'read only: "chat" = only user/assistant text (default, cheap); "full" = incl. tool calls/results.',
393
392
  })),
394
- last: Type.Optional(Type.Number({ description: "read only: take the latest N messages (1-200) instead of guessing offset." })),
393
+ last: Type.Optional(Type.Number({ description: "read only: take the latest N messages instead of guessing offset." })),
395
394
  id: Type.Optional(Type.String({ description: 'read only: running conversation id (e.g. "c3"), from action=list.' })),
396
395
  path: Type.Optional(Type.String({ description: "read only: history session file path, from action=list." })),
397
396
  offset: Type.Optional(Type.Number({ description: "read only: first message index (0-based). Default 0." })),
398
397
  limit: Type.Optional(Type.Number({
399
398
  description: "list: max entries per section (history defaults to 15, running uncapped up to 50). read/files: max messages/entries (1-200, default 50).",
400
399
  })),
401
- maxChars: Type.Optional(Type.Number({ description: "read only: max characters (1000-60000). Default 20000." })),
400
+ maxChars: Type.Optional(Type.Number({ description: "read only: max characters. Default 20000." })),
402
401
  }),
403
402
  execute: async (_id, p, _signal, _onUpdate, ctx) => {
404
403
  const action = (p.action ?? "list").trim().toLowerCase();
@@ -97,6 +97,16 @@ export function normalizeTouchPath(p) {
97
97
  s = s.slice(2);
98
98
  return s;
99
99
  }
100
+ /** patch 补丁文本 → 目标路径集合(段头 [path#TAG]/[path] + MV 目标)。 */
101
+ export function patchWriteTargets(patchText) {
102
+ const out = [];
103
+ for (const m of patchText.matchAll(/^\s*\[([^#\]\r\n]+)(?:#[0-9A-Fa-f]{4})?\]\s*$/gm)) {
104
+ out.push(m[1].trim());
105
+ }
106
+ for (const m of patchText.matchAll(/^\s*MV\s+(\S+)/gim))
107
+ out.push(m[1]);
108
+ return out;
109
+ }
100
110
  // ---------------------------------------------------------------------------
101
111
  // bash 命令解析(高置信度写入迹象,见文件头规则)
102
112
  // ---------------------------------------------------------------------------
@@ -280,6 +290,15 @@ export function extractTouches(messages, opts) {
280
290
  const ts = typeof m.timestamp === "number" && Number.isFinite(m.timestamp) ? m.timestamp : 0;
281
291
  for (const call of toolCallsOf(m)) {
282
292
  const name = call.name;
293
+ if (name === "patch") {
294
+ // patch 的目标路径在补丁文本里(无 args.path),按段头/MV 提取
295
+ const args = call.args;
296
+ if (args && typeof args.patch === "string") {
297
+ for (const p of patchWriteTargets(args.patch))
298
+ bump(p, ts);
299
+ }
300
+ continue;
301
+ }
283
302
  if (WRITE_TOOL_NAMES.has(name)) {
284
303
  const p = pathOfWriteArgs(call.args);
285
304
  if (p)
@@ -101,14 +101,14 @@ export function buildDelegationPrompt(input, lang = "en") {
101
101
  }
102
102
  const delegateSchema = Type.Object({
103
103
  agent: Type.String({
104
- description: "Specialist template to delegate to (e.g. oracle, metis, momus, explore, librarian, sisyphus-junior, multimodal-looker, review). " +
105
- "Must be an enabled template — use subagent (action='templates') to see descriptions and pick the domain match.",
104
+ description: "Specialist template to delegate to (e.g. oracle, explore, review, librarian). " +
105
+ "Must be enabled — use subagent (action='templates') to list them and pick the domain match.",
106
106
  }),
107
107
  task: Type.String({
108
- description: "Atomic, specific goal: ONE action per delegation (minimum 20 chars). Vague tasks are rejected.",
108
+ description: "Atomic, specific goal: ONE action per delegation. Vague tasks are rejected.",
109
109
  }),
110
110
  expected_outcome: Type.String({
111
- description: "Concrete deliverables with done criteria: what does success look like (minimum 10 chars).",
111
+ description: "Concrete deliverables with done criteria.",
112
112
  }),
113
113
  required_tools: Type.String({
114
114
  description: "Explicit tool whitelist for the subagent (prevents tool sprawl).",
@@ -127,9 +127,8 @@ const delegateSchema = Type.Object({
127
127
  "omit = template model → panel default → follow the main conversation model.",
128
128
  })),
129
129
  persist: Type.Optional(Type.Boolean({
130
- description: "Optional: persist this conversation to disk as a regular session (saved in history, resumable). " +
131
- "Default false (lightweight in-memory subagent). " +
132
- "Use true for tasks that need long-term retention.",
130
+ description: "Persist as a regular session saved in history (default false = lightweight in-memory subagent); " +
131
+ "use for tasks needing long-term retention.",
133
132
  })),
134
133
  });
135
134
  /** 结构化派单工具:校验六段 → 拼装标准 prompt → 走 host.spawnSubagent 真子代理。 */
@@ -142,14 +141,11 @@ export function makeDelegateTaskTool(host, lang) {
142
141
  return defineTool({
143
142
  name: DELEGATE_TOOL_NAME,
144
143
  label: "Delegate task",
145
- description: "Delegate ONE well-defined task to a specialist subagent template via a structured six-section brief (TASK / EXPECTED OUTCOME / REQUIRED TOOLS / MUST DO / MUST NOT DO / CONTEXT). " +
146
- "The brief is validated server-side — missing or vague sections are rejected, so fill every section concretely. " +
147
- "Prefer over subagent (action='spawn') when the work fits a specialist template. Spawns a real subagent conversation; " +
148
- "collect with subagent (action='wait_all' / 'get_result'), redirect with subagent (action='steer'), stop with subagent (action='stop'). " +
149
- "For follow-ups continue the SAME subagent session instead of delegating again.",
150
- promptSnippet: "Delegate a well-defined task to a specialist template with a validated six-section brief",
144
+ description: "Delegate ONE well-defined task to a specialist template via a six-section brief (TASK / EXPECTED OUTCOME / REQUIRED TOOLS / MUST DO / MUST NOT DO / CONTEXT). " +
145
+ "Vague sections are rejected server-side — fill every one concretely. Prefer it over subagent (action='spawn'). Spawns a real subagent conversation; " +
146
+ "follow up with subagent (action='wait_all' | 'get_result' | 'steer' | 'stop'), continuing the SAME session rather than delegating again.",
147
+ promptSnippet: "hand a well-scoped task to a specialist template",
151
148
  promptGuidelines: [
152
- "Prefer delegate_task over subagent (action='spawn') when the work matches a specialist template's domain",
153
149
  "Before delegating, declare which template you chose and WHY its description matches the task",
154
150
  "After delegation ALWAYS verify the result: " +
155
151
  "does it work, does it follow codebase patterns, did it respect MUST DO / MUST NOT DO",