pi-web-ui 0.112.0 → 0.113.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 (37) hide show
  1. package/CHANGELOG.md +38 -1
  2. package/bin/pi-web-ui.mjs +325 -45
  3. package/dist/server/agent-service-daemon.js +29 -4
  4. package/dist/server/agent-service.js +215 -35
  5. package/dist/server/canvas/canvas-agent-tool.js +2 -0
  6. package/dist/server/canvas/canvas-orchestrator.js +40 -1
  7. package/dist/server/canvas/pstack-skills-data.js +498 -0
  8. package/dist/server/dispatch-domain-handlers.js +36 -11
  9. package/dist/server/dsh/dsh-agent-service.js +52 -4
  10. package/dist/server/durable/durable-driver.js +37 -98
  11. package/dist/server/durable/durable-event-projector.js +253 -0
  12. package/dist/server/engine-probe.js +35 -11
  13. package/dist/server/index.js +67 -41
  14. package/dist/server/model-admin.js +185 -63
  15. package/dist/server/plugins.js +10 -6
  16. package/dist/server/remote-ssh-service.js +110 -12
  17. package/dist/server/serialize.js +1 -1
  18. package/dist/server/settings-service.js +36 -48
  19. package/dist/server/setup-page.js +632 -0
  20. package/dist/server/skill-discovery.js +361 -59
  21. package/dist/server/skill-maintenance.js +231 -0
  22. package/dist/server/skill-tool.js +32 -3
  23. package/dist/server/soft-cap.js +29 -7
  24. package/dist/server/subagents.js +246 -31
  25. package/dist/server/tool-host-factories.js +2 -0
  26. package/dist/server/tool-manager.js +106 -28
  27. package/dist/server/universal/drivers/claude-code.js +96 -4
  28. package/dist/server/universal/universal-session.js +19 -0
  29. package/package.json +1 -1
  30. package/plugins/catalog.json +10 -0
  31. package/web/dist/assets/{TerminalPanel-Dqr1dK28.js → TerminalPanel-3wojLfLk.js} +2 -2
  32. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  33. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  34. package/web/dist/index.html +2 -2
  35. package/web/dist/sw.js +1 -1
  36. package/web/dist/assets/index-Dh8BX-lP.js +0 -720
  37. package/web/dist/assets/index-DqrC1I_a.css +0 -1
@@ -84,6 +84,8 @@ export function withSubagentOwner(host, ownerId) {
84
84
  handoffSubagent: (fromRunId, toRunId, payload) => host.handoffSubagent(fromRunId || ownerId, toRunId, payload),
85
85
  markSubagentsConsumed: (runIds) => host.markSubagentsConsumed?.(runIds),
86
86
  finalizeSubagentWorktree: (convId) => host.finalizeSubagentWorktree?.(convId) ?? Promise.resolve(),
87
+ getActiveConversationId: () => host.getActiveConversationId?.(),
88
+ dismissSubagent: (convId, opts) => host.dismissSubagent?.(convId, opts) ?? Promise.resolve({ ok: false, reason: "unsupported" }),
87
89
  };
88
90
  }
89
91
  export const SUBAGENT_TOOL_NAME = "subagent";
@@ -96,6 +98,7 @@ export const SUBAGENT_ACTIONS = [
96
98
  "wait_all",
97
99
  "templates",
98
100
  "handoff",
101
+ "dismiss",
99
102
  ];
100
103
  /**
101
104
  * 单 action 子代理总工具(注册进每个会话的 customTools,供主 agent 驱动子代理)。
@@ -117,6 +120,63 @@ export function makeSubagentTool(host, lang, selfConvId) {
117
120
  content: [{ type: "text", text: t }],
118
121
  details,
119
122
  });
123
+ const expandDescendants = (roots) => {
124
+ if (roots instanceof Set ? roots.size === 0 : roots.length === 0)
125
+ return [];
126
+ const rootSet = roots instanceof Set ? roots : new Set(roots);
127
+ // B20:带 forSelfId(本会话的族)展开 —— 过户把整族搬到别的会话后,
128
+ // 只列本会话自己的列表会展不开后代,wait_all 会误报「没有需要等待的子代理」。
129
+ const all = host.listSubagents(undefined, selfIdOf());
130
+ const out = [];
131
+ for (const s of all) {
132
+ if (rootSet.has(s.convId))
133
+ continue;
134
+ let curParent = s.parentId;
135
+ const seen = new Set();
136
+ while (curParent) {
137
+ if (rootSet.has(curParent)) {
138
+ out.push(s.convId);
139
+ break;
140
+ }
141
+ if (seen.has(curParent))
142
+ break;
143
+ seen.add(curParent);
144
+ curParent = host.getSubagent(curParent)?.parentId;
145
+ }
146
+ }
147
+ return out;
148
+ };
149
+ const isDescendantOf = (targetId, rootId) => {
150
+ const target = host.getSubagent(targetId);
151
+ if (!target)
152
+ return false;
153
+ let curParent = target.parentId;
154
+ const seen = new Set([targetId]);
155
+ while (curParent) {
156
+ if (curParent === rootId)
157
+ return true;
158
+ if (seen.has(curParent))
159
+ break;
160
+ seen.add(curParent);
161
+ curParent = host.getSubagent(curParent)?.parentId;
162
+ }
163
+ return false;
164
+ };
165
+ const depthOf = (targetId) => {
166
+ let d = 0;
167
+ let cur = host.getSubagent(targetId);
168
+ const seen = new Set([targetId]);
169
+ while (cur?.parentId) {
170
+ if (seen.has(cur.parentId))
171
+ break;
172
+ seen.add(cur.parentId);
173
+ d++;
174
+ cur = host.getSubagent(cur.parentId);
175
+ if (!cur)
176
+ break;
177
+ }
178
+ return d;
179
+ };
120
180
  const currentWaitCapMs = typeof host.getWatchdogTimeoutMs === "function"
121
181
  ? computeWaitCapMs(host.getWatchdogTimeoutMs())
122
182
  : computeWaitCapMs();
@@ -126,7 +186,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
126
186
  label: "Subagent manager",
127
187
  description: "Manage background subagent conversations for parallel delegation, research, and execution. " +
128
188
  "Each action's arguments are documented on the parameters below.",
129
- promptSnippet: "manage background subagents (spawn/steer/wait/templates)",
189
+ promptSnippet: "manage background subagents (spawn/steer/wait/dismiss)",
130
190
  parameters: Type.Object({
131
191
  action: Type.Unsafe({
132
192
  type: "string",
@@ -137,10 +197,10 @@ export function makeSubagentTool(host, lang, selfConvId) {
137
197
  description: "spawn: instructions (goal, constraints, expected output).",
138
198
  })),
139
199
  runId: Type.Optional(Type.String({
140
- description: "get_result/steer/stop: target conversation ID.",
200
+ description: "get_result/steer/stop/dismiss: target conversation ID.",
141
201
  })),
142
202
  runIds: Type.Optional(Type.Array(Type.String(), {
143
- description: "wait_all: conversation IDs to wait for (omit = all active).",
203
+ description: "wait_all/dismiss: conversation IDs to wait for or dismiss.",
144
204
  })),
145
205
  message: Type.Optional(Type.String({
146
206
  description: "steer: follow-up instruction.",
@@ -189,11 +249,21 @@ export function makeSubagentTool(host, lang, selfConvId) {
189
249
  minimum: 1,
190
250
  maximum: capSeconds,
191
251
  })),
252
+ scope: Type.Optional(Type.String({
253
+ enum: ["finished_all"],
254
+ description: 'dismiss: batch dismissal scope ("finished_all" to dismiss all finished descendant subagents).',
255
+ })),
256
+ force: Type.Optional(Type.Boolean({
257
+ description: "dismiss: force abort running subagents before dismissing (default: false).",
258
+ })),
259
+ includePersisted: Type.Optional(Type.Boolean({
260
+ description: "dismiss: allow dismissing persisted subagents (default: false).",
261
+ })),
192
262
  }),
193
263
  execute: async (_id, p, signal, _onUpdate, ctx) => {
194
264
  const action = (p.action ?? "").trim().toLowerCase();
195
265
  if (!action) {
196
- return text(pick(getLang(), "subagent 工具缺少 action 参数(可选:spawn, get_result, steer, list, stop, wait_all, templates, handoff)。", "subagent tool requires an action parameter (one of: spawn, get_result, steer, list, stop, wait_all, templates, handoff).", "subagents.action.missing"));
266
+ return text(pick(getLang(), "subagent 工具缺少 action 参数(可选:spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss)。", "subagent tool requires an action parameter (one of: spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss).", "subagents.action.missing"));
197
267
  }
198
268
  switch (action) {
199
269
  case "spawn": {
@@ -388,32 +458,6 @@ export function makeSubagentTool(host, lang, selfConvId) {
388
458
  }
389
459
  return out;
390
460
  };
391
- const expandDescendants = (roots) => {
392
- if (roots instanceof Set ? roots.size === 0 : roots.length === 0)
393
- return [];
394
- const rootSet = roots instanceof Set ? roots : new Set(roots);
395
- // B20:带 forSelfId(本会话的族)展开 —— 过户把整族搬到别的会话后,
396
- // 只列本会话自己的列表会展不开后代,wait_all 会误报「没有需要等待的子代理」。
397
- const all = host.listSubagents(undefined, selfId);
398
- const out = [];
399
- for (const s of all) {
400
- if (rootSet.has(s.convId))
401
- continue;
402
- let curParent = s.parentId;
403
- const seen = new Set();
404
- while (curParent) {
405
- if (rootSet.has(curParent)) {
406
- out.push(s.convId);
407
- break;
408
- }
409
- if (seen.has(curParent))
410
- break;
411
- seen.add(curParent);
412
- curParent = host.getSubagent(curParent)?.parentId;
413
- }
414
- }
415
- return out;
416
- };
417
461
  const explicit = p.runIds && p.runIds.length > 0;
418
462
  const wanted = new Set();
419
463
  const selfAncestorIds = selfId ? ancestorIdsOf(selfId) : new Set();
@@ -591,8 +635,179 @@ export function makeSubagentTool(host, lang, selfConvId) {
591
635
  return text(pick(getLang(), `交接失败:${msg}`, `Handoff failed: ${msg}`, "subagents.handoff.failed", { error: msg }));
592
636
  }
593
637
  }
638
+ case "dismiss": {
639
+ if (!host.dismissSubagent) {
640
+ return text(pick(getLang(), "当前引擎不支持子代理移出能力。", "Subagent dismissal is not supported by the current engine.", "subagents.dismiss.unsupported"));
641
+ }
642
+ const explicitIds = [];
643
+ if (Array.isArray(p.runIds) && p.runIds.length > 0) {
644
+ for (const id of p.runIds) {
645
+ if (typeof id === "string" && id.trim()) {
646
+ explicitIds.push(id.trim());
647
+ }
648
+ }
649
+ }
650
+ else if (p.runId && typeof p.runId === "string" && p.runId.trim()) {
651
+ explicitIds.push(p.runId.trim());
652
+ }
653
+ const isFinishedAll = p.scope === "finished_all";
654
+ if (explicitIds.length === 0 && !isFinishedAll) {
655
+ return text(pick(getLang(), 'subagent(action="dismiss") 缺少目标参数:请指定 runId、runIds 或 scope="finished_all"。', 'subagent(action="dismiss") requires target parameter: specify runId, runIds, or scope="finished_all".', "subagents.dismiss.missing.target"));
656
+ }
657
+ const selfId = selfIdOf();
658
+ const activeConvId = host.getActiveConversationId?.();
659
+ let candidateIds = [];
660
+ if (isFinishedAll) {
661
+ const all = host.listSubagents(undefined, selfId);
662
+ let inScopeList = all;
663
+ if (selfId) {
664
+ const descIds = new Set(expandDescendants(new Set([selfId])));
665
+ inScopeList = all.filter((s) => descIds.has(s.convId));
666
+ }
667
+ // 口径与 finishedSubagentCount 一致:isSubagent、非 streaming、非当前 active
668
+ candidateIds = inScopeList
669
+ .filter((s) => {
670
+ if (s.streaming || s.state === "running")
671
+ return false;
672
+ if (s.convId === selfId)
673
+ return false;
674
+ if (activeConvId && s.convId === activeConvId)
675
+ return false;
676
+ if (s.persisted && !p.includePersisted)
677
+ return false;
678
+ return true;
679
+ })
680
+ .map((s) => s.convId);
681
+ if (candidateIds.length === 0) {
682
+ return text(pick(getLang(), "没有可移出的已结束子代理。", "No finished subagents to dismiss.", "subagents.dismiss.finished_all.empty"), { dismissed: [], skipped: [] });
683
+ }
684
+ }
685
+ else {
686
+ candidateIds = [...new Set(explicitIds)];
687
+ }
688
+ const isSingleExplicit = !isFinishedAll && explicitIds.length === 1;
689
+ if (isSingleExplicit) {
690
+ const targetId = candidateIds[0];
691
+ const snapshot = host.getSubagent(targetId);
692
+ if (!snapshot) {
693
+ const missingId = shortId(targetId);
694
+ return text(pick(getLang(), `未找到子代理 ${missingId}(可能已移出或不存在)。`, `Subagent ${missingId} not found (may have been dismissed or non-existent).`, "subagents.dismiss.not_found", { missingId }));
695
+ }
696
+ if (selfId && targetId === selfId) {
697
+ return text(pick(getLang(), "拒绝移出:不能移出当前会话自身。", "Refused: cannot dismiss the current conversation itself.", "subagents.dismiss.self"));
698
+ }
699
+ if (activeConvId && targetId === activeConvId) {
700
+ const activeId = shortId(targetId);
701
+ return text(pick(getLang(), `子代理 ${activeId} 正在前端处于活动打开状态,无法直接移出。`, `Subagent ${activeId} is currently active in the UI and cannot be dismissed.`, "subagents.dismiss.active", { activeId }));
702
+ }
703
+ if (selfId && !isDescendantOf(targetId, selfId)) {
704
+ const notDescId = shortId(targetId);
705
+ return text(pick(getLang(), `拒绝移出:子代理 ${notDescId} 不属于当前会话的派发族谱(仅允许移出由当前会话派发的子代理)。`, `Refused: subagent ${notDescId} does not belong to the descendant hierarchy of this conversation (can only dismiss subagents spawned by this conversation).`, "subagents.dismiss.not_descendant", { notDescId }));
706
+ }
707
+ if (snapshot.persisted && !p.includePersisted) {
708
+ const persistedId = shortId(targetId);
709
+ return text(pick(getLang(), `子代理 ${persistedId} 为持久化会话(已落盘历史)。如确认需要移出,请传入 includePersisted=true。`, `Subagent ${persistedId} is a persistent session. If you are sure you want to dismiss it, pass includePersisted=true.`, "subagents.dismiss.persisted", { persistedId }));
710
+ }
711
+ const isRunning = snapshot.streaming || snapshot.state === "running";
712
+ if (isRunning && !p.force) {
713
+ const runningId = shortId(targetId);
714
+ return text(pick(getLang(), `子代理 ${runningId} 仍在运行中(状态:${snapshot.state})。请等待其完成、调用 subagent(action="stop"),或指定 force=true 强行中止并移出。`, `Subagent ${runningId} is still running (state: ${snapshot.state}). Wait for it to finish, call subagent(action="stop"), or specify force=true to force abort and dismiss.`, "subagents.dismiss.running", { runningId, state: snapshot.state }));
715
+ }
716
+ if (host.finalizeSubagentWorktree) {
717
+ await host.finalizeSubagentWorktree(targetId);
718
+ }
719
+ const updated = host.getSubagent(targetId) ?? snapshot;
720
+ if (updated.worktree && !updated.worktree.cleanedUp) {
721
+ const wt = updated.worktree;
722
+ const isDirty = Boolean(wt.isDirty || (wt.uncommittedCount ?? 0) > 0 || (wt.aheadCount ?? 0) > 0);
723
+ if (isDirty) {
724
+ const dirtyId = shortId(targetId);
725
+ return text(pick(getLang(), `子代理 ${dirtyId} 的工作树存在未合并改动,无法移出(静默移出会丢失代码):\n- 路径:${wt.path}\n- 分支:${wt.branch}\n- 未提交改动:${wt.uncommittedCount ?? 0} 个文件,领先提交:${wt.aheadCount ?? 0} 个\n请先合并分支(git merge ${wt.branch})或确认放弃后通过 worktree(action="remove", path="${wt.path}", force=true) 清理。`, `Subagent ${dirtyId} has unmerged worktree changes and cannot be dismissed (silent dismissal would lose code):\n- Path: ${wt.path}\n- Branch: ${wt.branch}\n- Changes: ${wt.uncommittedCount ?? 0} uncommitted file(s), ${wt.aheadCount ?? 0} commit(s) ahead\nPlease merge the branch (git merge ${wt.branch}) or discard changes via worktree(action="remove", path="${wt.path}", force=true).`, "subagents.dismiss.worktree.dirty", {
726
+ dirtyId,
727
+ path: wt.path,
728
+ branch: wt.branch,
729
+ uncommitted: wt.uncommittedCount ?? 0,
730
+ ahead: wt.aheadCount ?? 0,
731
+ }));
732
+ }
733
+ }
734
+ const res = await host.dismissSubagent(targetId, {
735
+ force: p.force,
736
+ includePersisted: p.includePersisted,
737
+ });
738
+ if (!res.ok) {
739
+ const failedId = shortId(targetId);
740
+ return text(pick(getLang(), `移出子代理 ${failedId} 失败:${res.reason ?? "未知原因"}。`, `Failed to dismiss subagent ${failedId}: ${res.reason ?? "unknown reason"}.`, "subagents.dismiss.failed", { failedId, reason: res.reason ?? "unknown" }));
741
+ }
742
+ const doneId = shortId(targetId);
743
+ return text(pick(getLang(), `已移出子代理 ${doneId}。移出后不可逆(会话已从左栏移除并释放运行时与临时数据)。提示:如需获取产物,请在移出前调用 subagent(action="get_result")。`, `Dismissed subagent ${doneId}. Dismissal is irreversible (session removed from panel, runtime and temporary data released). Note: call subagent(action="get_result") before dismissal if you need its output.`, "subagents.dismiss.success.single", { doneId }), { dismissed: [targetId], skipped: [] });
744
+ }
745
+ candidateIds.sort((a, b) => depthOf(b) - depthOf(a));
746
+ const dismissed = [];
747
+ const skipped = [];
748
+ for (const targetId of candidateIds) {
749
+ const snapshot = host.getSubagent(targetId);
750
+ if (!snapshot) {
751
+ skipped.push({ runId: targetId, reason: "not_found" });
752
+ continue;
753
+ }
754
+ if (selfId && targetId === selfId) {
755
+ skipped.push({ runId: targetId, reason: "self" });
756
+ continue;
757
+ }
758
+ if (activeConvId && targetId === activeConvId) {
759
+ skipped.push({ runId: targetId, reason: "active" });
760
+ continue;
761
+ }
762
+ if (selfId && !isDescendantOf(targetId, selfId)) {
763
+ skipped.push({ runId: targetId, reason: "not_descendant" });
764
+ continue;
765
+ }
766
+ if (snapshot.persisted && !p.includePersisted) {
767
+ skipped.push({ runId: targetId, reason: "persisted" });
768
+ continue;
769
+ }
770
+ const isRunning = snapshot.streaming || snapshot.state === "running";
771
+ if (isRunning && !p.force) {
772
+ skipped.push({ runId: targetId, reason: "running" });
773
+ continue;
774
+ }
775
+ if (host.finalizeSubagentWorktree) {
776
+ await host.finalizeSubagentWorktree(targetId);
777
+ }
778
+ const updated = host.getSubagent(targetId) ?? snapshot;
779
+ if (updated.worktree && !updated.worktree.cleanedUp) {
780
+ const wt = updated.worktree;
781
+ const isDirty = Boolean(wt.isDirty || (wt.uncommittedCount ?? 0) > 0 || (wt.aheadCount ?? 0) > 0);
782
+ if (isDirty) {
783
+ skipped.push({ runId: targetId, reason: "dirty_worktree" });
784
+ continue;
785
+ }
786
+ }
787
+ const res = await host.dismissSubagent(targetId, {
788
+ force: p.force,
789
+ includePersisted: p.includePersisted,
790
+ });
791
+ if (res.ok) {
792
+ dismissed.push(targetId);
793
+ }
794
+ else {
795
+ skipped.push({ runId: targetId, reason: res.reason ?? "failed" });
796
+ }
797
+ }
798
+ if (dismissed.length === 0) {
799
+ if (isFinishedAll) {
800
+ return text(pick(getLang(), "没有可移出的已结束子代理。", "No finished subagents to dismiss.", "subagents.dismiss.finished_all.empty"), { dismissed: [], skipped });
801
+ }
802
+ return text(pick(getLang(), "没有成功移出任何子代理。", "No subagents were dismissed.", "subagents.dismiss.none"), { dismissed: [], skipped });
803
+ }
804
+ const skippedCount = skipped.length;
805
+ const skippedZh = skippedCount > 0 ? `(${skippedCount} 个已跳过)` : "";
806
+ const skippedEn = skippedCount > 0 ? ` (${skippedCount} skipped)` : "";
807
+ return text(pick(getLang(), `已成功移出 ${dismissed.length} 个子代理${skippedZh}。移出后不可逆(会话已从左栏移除并释放运行时与临时数据)。提示:如需获取产物,请在移出前调用 subagent(action="get_result")。`, `Successfully dismissed ${dismissed.length} subagent(s)${skippedEn}. Dismissal is irreversible (sessions removed from panel, runtimes and temporary data released). Note: call subagent(action="get_result") before dismissal if you need their outputs.`, "subagents.dismiss.success.batch", { count: dismissed.length, skippedZh, skippedEn }), { dismissed, skipped });
808
+ }
594
809
  default:
595
- return text(pick(getLang(), `未知 action:${action}。支持的 action:spawn, get_result, steer, list, stop, wait_all, templates, handoff。`, `Unknown action: ${action}. Supported actions: spawn, get_result, steer, list, stop, wait_all, templates, handoff.`, "subagents.action.unknown", { action }));
810
+ return text(pick(getLang(), `未知 action:${action}。支持的 action:spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss。`, `Unknown action: ${action}. Supported actions: spawn, get_result, steer, list, stop, wait_all, templates, handoff, dismiss.`, "subagents.action.unknown", { action }));
596
811
  }
597
812
  },
598
813
  });
@@ -243,6 +243,8 @@ export function createSkillToolHost(ctx) {
243
243
  name: s.name,
244
244
  description: s.description ?? "",
245
245
  filePath: s.filePath ?? "",
246
+ source: s.source,
247
+ scope: s.scope,
246
248
  }));
247
249
  }
248
250
  catch {
@@ -298,22 +298,80 @@ export const AGENT_TOOL_CATALOG = [
298
298
  ];
299
299
  /** SDK 核心内置工具名(可被门控显式禁用或被预设白名单过滤)。 */
300
300
  export const CORE_BUILTIN_TOOL_NAMES = ["bash", "read", "edit", "write", "powershell", "ls", "grep", "find"];
301
+ /**
302
+ * SDK 核心内置工具的声明式元数据目录。
303
+ * 核心工具不进 AGENT_TOOL_CATALOG(避免被 AI 自杀式通过 tool_manage 禁用,且不占设置页「其他」组目录行),
304
+ * 但拥有与目录工具完全对齐的元数据(默认开关、文案 key、分类、平台与安全维度),共同构成全系统统一的工具事实源。
305
+ */
306
+ export const CORE_TOOL_CATALOG = [
307
+ { name: "bash", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreBashDesc" },
308
+ { name: "read", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreReadDesc" },
309
+ { name: "edit", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreEditDesc" },
310
+ { name: "write", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreWriteDesc" },
311
+ {
312
+ name: "powershell",
313
+ group: "core",
314
+ defaultOn: false,
315
+ platform: "win32",
316
+ allowAgentToggle: false,
317
+ descKey: "toolCorePowershellDesc",
318
+ },
319
+ { name: "ls", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreLsDesc" },
320
+ { name: "grep", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreGrepDesc" },
321
+ { name: "find", group: "core", defaultOn: true, allowAgentToggle: false, descKey: "toolCoreFindDesc" },
322
+ ];
323
+ /** 系统全部已知可开关工具的统一声明式条目集合(核心内置 8 个 ∪ 宿主扩展 28 个,共 36 个)。 */
324
+ export const ALL_AGENT_TOOL_ENTRIES = [
325
+ ...CORE_TOOL_CATALOG.map((c) => ({
326
+ name: c.name,
327
+ group: "core",
328
+ defaultOn: c.defaultOn,
329
+ platform: c.platform,
330
+ allowAgentToggle: c.allowAgentToggle,
331
+ dshVisible: false,
332
+ descKey: c.descKey,
333
+ })),
334
+ ...AGENT_TOOL_CATALOG,
335
+ ];
336
+ const ALL_AGENT_TOOL_MAP = new Map(ALL_AGENT_TOOL_ENTRIES.map((t) => [t.name, t]));
337
+ /** 获取任意已知工具的元数据规范条目。未知名返回 undefined。 */
338
+ export function getAgentToolEntry(name) {
339
+ return ALL_AGENT_TOOL_MAP.get(name);
340
+ }
341
+ /** 判断工具是否在指定操作系统平台上受支持(默认检查当前宿主 process.platform)。 */
342
+ export function isToolSupportedOnPlatform(name, platform = process.platform) {
343
+ const entry = ALL_AGENT_TOOL_MAP.get(name);
344
+ if (!entry?.platform)
345
+ return true;
346
+ if (entry.platform === "win32")
347
+ return platform === "win32";
348
+ if (entry.platform === "posix")
349
+ return platform !== "win32";
350
+ return true;
351
+ }
301
352
  export function isCoreBuiltinTool(name) {
302
353
  return CORE_BUILTIN_TOOL_NAMES.includes(name);
303
354
  }
304
- const KNOWN_NAMES = new Set(AGENT_TOOL_CATALOG.map((t) => t.name));
305
- /** 全部已知可开关工具与核心内置工具全集(共 30 个)。用于白名单收敛与默认关闭推导。 */
306
- export const ALL_KNOWN_AGENT_TOOL_NAMES = [
307
- ...AGENT_TOOL_CATALOG.map((t) => t.name),
308
- ...CORE_BUILTIN_TOOL_NAMES,
309
- ];
310
- /** 是否为本表登记的可开关工具(未知名一律 false,不抛错)。 */
355
+ const ALL_KNOWN_SET = new Set(ALL_AGENT_TOOL_ENTRIES.map((t) => t.name));
356
+ /** 全部已知可开关工具与核心内置工具全集(共 36 个)。用于白名单收敛与默认关闭推导。 */
357
+ export const ALL_KNOWN_AGENT_TOOL_NAMES = ALL_AGENT_TOOL_ENTRIES.map((t) => t.name);
358
+ /** 是否为 AI 可通过 tool_manage 自主开关的工具(显式检查 allowAgentToggle !== false,防自杀式关核心工具)。 */
311
359
  export function isKnownAgentTool(name) {
312
- return KNOWN_NAMES.has(name);
360
+ const entry = ALL_AGENT_TOOL_MAP.get(name);
361
+ return Boolean(entry && entry.allowAgentToggle !== false);
362
+ }
363
+ /**
364
+ * 是否为受宿主配置统一管辖的工具(宿主受管工具 Host-Managed Tools):
365
+ * 即核心内置工具(bash/read/edit/write/powershell 等)∪ AGENT_TOOL_CATALOG 目录登记工具。
366
+ * 只有这类工具的开关受 Web UI 的设置面板(disabledAgentTools)与模式闸门管辖。
367
+ * 其余工具(第三方扩展动态注册的工具如 url_context 等)归扩展自主管辖。
368
+ */
369
+ export function isHostManagedTool(name) {
370
+ return ALL_KNOWN_SET.has(name);
313
371
  }
314
- /** 是否为预设可配置的有效工具(目录登记工具 ∪ 核心内置工具)。 */
372
+ /** 是否为预设可配置的有效工具(宿主目录登记工具 ∪ 核心内置工具,对齐 isHostManagedTool)。 */
315
373
  export function isConfigurableAgentTool(name) {
316
- return KNOWN_NAMES.has(name) || isCoreBuiltinTool(name);
374
+ return isHostManagedTool(name);
317
375
  }
318
376
  /** 根据禁用名单计算出当前系统中真正启用的可用工具列表(只取当前系统可用的配置)。 */
319
377
  export function resolveEnabledAgentTools(disabled) {
@@ -344,15 +402,15 @@ export function normalizeDisabledAgentTools(v) {
344
402
  if (typeof name === "string" && LEGACY_SCHEDULE_TOOL_NAMES.includes(name)) {
345
403
  name = SCHEDULE_TOOL_NAME;
346
404
  }
347
- if (typeof name === "string" && (KNOWN_NAMES.has(name) || isCoreBuiltinTool(name)) && !out.includes(name)) {
405
+ if (typeof name === "string" && ALL_KNOWN_SET.has(name) && !out.includes(name)) {
348
406
  out.push(name);
349
407
  }
350
408
  }
351
409
  return out;
352
410
  }
353
- /** 默认禁用名单(= 目录里 defaultOn=false 的那些)。 */
411
+ /** 默认禁用名单:统一由全部工具条目的 !defaultOn 声明式推导,绝无任何手写特例。 */
354
412
  export function defaultDisabledAgentTools() {
355
- return AGENT_TOOL_CATALOG.filter((t) => !t.defaultOn).map((t) => t.name);
413
+ return ALL_AGENT_TOOL_ENTRIES.filter((t) => !t.defaultOn).map((t) => t.name);
356
414
  }
357
415
  /** 单个工具是否启用(禁用名单里没有 = 启用)。 */
358
416
  export function isAgentToolEnabled(name, disabled) {
@@ -400,18 +458,36 @@ export function setAgentToolsEnabled(session, names, on) {
400
458
  }
401
459
  }
402
460
  /**
403
- * 全量重放(创建会话 / reload 后 / 设置变更后调):按禁用名单把目录内工具与
404
- * 核心内置工具(bash/read/edit/write,禁用名单接受它们)逐个加回或剔除;
405
- * 基线之外的工具(插件工具等)原样不动。
406
- * 支持传入 preset(预设 id),按预设白名单做二次过滤。
407
- * 复原基线取 session.getAllTools()(全集,含被禁用的)——基线里没有的工具不会凭空发明。
461
+ * 全量重放(创建会话 / reload 后 / 设置变更后调):
462
+ *
463
+ * 采用管辖权差异化门控模型(Authority Boundary Gating):
464
+ * 1. 宿主受管工具(Host-Managed Tools,即核心内置工具 + AGENT_TOOL_CATALOG 工具):
465
+ * 由 Web UI 的 disabledAgentTools 开关、模式硬闸门与预设白名单完全掌控状态。
466
+ * 2. 扩展自主工具(Extension-Owned Tools,如 pi-web-search 的 url_context 等):
467
+ * Web UI 默认信任其在活跃集中的既有状态(getActiveToolNames),绝不擅自重新启用
468
+ * 已被扩展主动关闭的外部工具,避免破坏模型的 Prompt 缓存前缀。
469
+ * 3. 预设安全过滤:预设(Preset)只对最终候选集做安全收缩(例如 ask 纯对话清空所有工具,
470
+ * minimal 仅保留 bash+read 等)。
471
+ *
408
472
  * Session 未就绪时静默跳过(下次创建/reload 会再应用)。
409
473
  */
410
474
  export function applyAgentToolsGating(session, disabled, preset, options) {
411
475
  try {
412
476
  const off = new Set(disabled);
413
477
  const allNames = session.getAllTools().map((t) => t.name);
414
- const names = new Set(allNames);
478
+ const initialActiveNames = new Set(session.getActiveToolNames());
479
+ // 明确管辖权分界:
480
+ // - 宿主受管工具:以全集为基线,依据 disabled 名单全量重放;
481
+ // - 扩展自主工具:以 session.getActiveToolNames() 为准继承当前活跃态,未激活的绝不自动开启。
482
+ const names = new Set();
483
+ for (const name of allNames) {
484
+ if (isHostManagedTool(name)) {
485
+ names.add(name);
486
+ }
487
+ else if (initialActiveNames.has(name)) {
488
+ names.add(name);
489
+ }
490
+ }
415
491
  for (const t of AGENT_TOOL_CATALOG) {
416
492
  if (off.has(t.name)) {
417
493
  // issue #481: 若第三方扩展注册了同名工具(如 nicobailon/pi-subagents 的 subagent),
@@ -664,20 +740,22 @@ export function presetHasQuestionnaire(preset) {
664
740
  return filterToolsByPreset([ASK_USER_QUESTION_TOOL_NAME], preset).includes(ASK_USER_QUESTION_TOOL_NAME);
665
741
  }
666
742
  /**
667
- * 旧存档迁移:已有新字段直接归一化;否则按遗留三开关折算
668
- * (语义与改动前一致:terminal/edit 未设/关 = 禁用对应组;问卷未设/开 = 启用)。
743
+ * 旧存档迁移:已有新字段直接归一化;否则按遗留三开关折算。
744
+ * 以统一默认禁用名单为基底,遗留三开关仅在显式指定时加减偏好。
669
745
  */
670
746
  export function legacyToDisabled(s) {
671
747
  if (Array.isArray(s.disabledAgentTools))
672
748
  return normalizeDisabledAgentTools(s.disabledAgentTools);
673
- const off = [];
674
- if (s.terminalToolsEnabled !== true)
675
- off.push(...TERMINAL_TOOL_NAMES);
676
- if (s.editSoftEnabled !== true)
677
- off.push(EDIT_SOFT_TOOL_NAME);
749
+ const off = new Set(defaultDisabledAgentTools());
750
+ if (s.terminalToolsEnabled === true) {
751
+ for (const n of TERMINAL_TOOL_NAMES)
752
+ off.delete(n);
753
+ }
754
+ if (s.editSoftEnabled === true)
755
+ off.delete(EDIT_SOFT_TOOL_NAME);
678
756
  if (s.questionnaireEnabled === false)
679
- off.push(ASK_USER_QUESTION_TOOL_NAME);
680
- return normalizeDisabledAgentTools(off);
757
+ off.add(ASK_USER_QUESTION_TOOL_NAME);
758
+ return normalizeDisabledAgentTools([...off]);
681
759
  }
682
760
  /** 由禁用名单推导遗留三开关(协议兼容用;终端组按“全开才算开”的全有/全无视图)。 */
683
761
  export function deriveLegacy(disabled) {
@@ -12,20 +12,112 @@
12
12
  * 5. 环境容错:未安装 claude 时输出清晰友好的中英文引导提示。
13
13
  */
14
14
  import { execFile, spawn } from "node:child_process";
15
- import { existsSync, writeFileSync } from "node:fs";
15
+ import { existsSync, readdirSync, writeFileSync } from "node:fs";
16
16
  import { createInterface } from "node:readline";
17
17
  import { homedir } from "node:os";
18
- import { join } from "node:path";
18
+ import { delimiter, isAbsolute, join } from "node:path";
19
19
  import { BaseAgentDriver } from "../driver-base.js";
20
20
  import { resolveProviderCredential, listCustomModelsFromConfig, isModelProtocolSupportedByEngine, } from "../../model-resolver.js";
21
21
  import { discoverDiskSkills } from "../../skill-discovery.js";
22
+ /**
23
+ * 探测可执行文件路径:若传入了绝对路径或在系统 PATH 中找到则直接使用;
24
+ * 若未找到(尤其在 macOS launchd/GUI 等精简 PATH 环境),则自动扫描系统及版本管理器的常见安装目录。
25
+ */
26
+ export function resolveClaudeExecutable(cmd = "claude") {
27
+ if (isAbsolute(cmd)) {
28
+ if (existsSync(cmd))
29
+ return cmd;
30
+ if (process.platform === "win32") {
31
+ for (const ext of [".cmd", ".exe", ".bat"]) {
32
+ if (existsSync(cmd + ext))
33
+ return cmd + ext;
34
+ }
35
+ }
36
+ return cmd;
37
+ }
38
+ const isWin = process.platform === "win32";
39
+ const exts = isWin ? [".cmd", ".exe", ".bat", ""] : [""];
40
+ // 1. 优先从当前 process.env.PATH 寻找
41
+ const pathDirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
42
+ for (const dir of pathDirs) {
43
+ for (const ext of exts) {
44
+ const target = join(dir, cmd + ext);
45
+ if (existsSync(target))
46
+ return target;
47
+ }
48
+ }
49
+ // 2. 针对 macOS/Linux,自动扫描常见全局包管理器与 Homebrew 路径
50
+ if (!isWin) {
51
+ const home = homedir();
52
+ const candidateDirs = [
53
+ // macOS Homebrew (Apple Silicon & Intel)
54
+ "/opt/homebrew/bin",
55
+ "/usr/local/bin",
56
+ // 用户目录下的标准与包管理器 bin 路径
57
+ join(home, ".local", "bin"),
58
+ join(home, "bin"),
59
+ join(home, ".npm-global", "bin"),
60
+ join(home, ".config", "yarn", "global", "node_modules", ".bin"),
61
+ join(home, ".yarn", "bin"),
62
+ join(home, ".pnpm-global", "bin"),
63
+ join(home, "Library", "pnpm"),
64
+ join(home, ".bun", "bin"),
65
+ join(home, ".local", "share", "fnm", "current", "bin"),
66
+ ];
67
+ // fnm 当前或各 node 版本的 bin 目录与 multishells
68
+ const fnmVersionsDir = join(home, ".local", "share", "fnm", "node-versions");
69
+ if (existsSync(fnmVersionsDir)) {
70
+ try {
71
+ const vers = readdirSync(fnmVersionsDir);
72
+ for (const v of vers) {
73
+ candidateDirs.push(join(fnmVersionsDir, v, "installation", "bin"));
74
+ }
75
+ }
76
+ catch {
77
+ /* ignore */
78
+ }
79
+ }
80
+ const fnmStateDir = join(home, ".local", "state", "fnm_multishells");
81
+ if (existsSync(fnmStateDir)) {
82
+ try {
83
+ const shells = readdirSync(fnmStateDir);
84
+ for (const s of shells) {
85
+ candidateDirs.push(join(fnmStateDir, s, "bin"));
86
+ }
87
+ }
88
+ catch {
89
+ /* ignore */
90
+ }
91
+ }
92
+ // nvm 当前或各 node 版本的 bin 目录
93
+ const nvmVersionsDir = join(home, ".nvm", "versions", "node");
94
+ if (existsSync(nvmVersionsDir)) {
95
+ try {
96
+ const vers = readdirSync(nvmVersionsDir);
97
+ for (const v of vers) {
98
+ candidateDirs.push(join(nvmVersionsDir, v, "bin"));
99
+ }
100
+ }
101
+ catch {
102
+ /* ignore */
103
+ }
104
+ }
105
+ for (const dir of candidateDirs) {
106
+ const target = join(dir, cmd);
107
+ if (existsSync(target))
108
+ return target;
109
+ }
110
+ }
111
+ return cmd;
112
+ }
22
113
  /**
23
114
  * 快速异步探测系统中是否安装了可用的 Claude Code CLI。
24
115
  */
25
116
  export async function probeClaudeCode(executablePath = "claude") {
117
+ const resolvedPath = resolveClaudeExecutable(executablePath);
26
118
  return new Promise((resolve) => {
27
119
  try {
28
- execFile(executablePath, ["--version"], {
120
+ execFile(resolvedPath, ["--version"], {
29
121
  timeout: 4000,
30
122
  shell: process.platform === "win32",
31
123
  }, (err, stdout) => {
@@ -72,7 +164,7 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
72
164
  currentThinkingLevel = "medium";
73
165
  constructor(cwd, opts) {
74
166
  super(cwd);
75
- this.executablePath = opts?.executablePath ?? "claude";
167
+ this.executablePath = resolveClaudeExecutable(opts?.executablePath ?? "claude");
76
168
  // 默认添加 --dangerously-skip-permissions,防止无头模式下因等待交互式 y/n 确认导致整个生成假死
77
169
  this.extraArgs = opts?.extraArgs ?? ["--dangerously-skip-permissions"];
78
170
  this.currentModel = opts?.defaultModel ?? "claude-3-7-sonnet-20250219";