pi-web-ui 0.111.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 (88) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/bin/pi-web-ui.mjs +325 -45
  4. package/dist/server/agent-service-daemon.js +29 -4
  5. package/dist/server/agent-service.js +1527 -510
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/canvas/canvas-agent-tool.js +8 -0
  11. package/dist/server/canvas/canvas-orchestrator.js +128 -22
  12. package/dist/server/canvas/pstack-skills-data.js +498 -0
  13. package/dist/server/client-state.js +28 -0
  14. package/dist/server/delegate-mode.js +6 -3
  15. package/dist/server/delegate-task.js +18 -3
  16. package/dist/server/dispatch-domain-handlers.js +39 -11
  17. package/dist/server/dsh/dsh-agent-service.js +294 -15
  18. package/dist/server/dsh/dsh-serialize.js +1 -1
  19. package/dist/server/durable/durable-driver.js +112 -107
  20. package/dist/server/durable/durable-event-projector.js +253 -0
  21. package/dist/server/durable/durable-loader.js +1 -14
  22. package/dist/server/durable/durable-models.js +107 -0
  23. package/dist/server/durable/index.js +0 -4
  24. package/dist/server/engine-probe.js +111 -48
  25. package/dist/server/eval-tool.js +28 -3
  26. package/dist/server/goal-service.js +7 -0
  27. package/dist/server/index.js +371 -57
  28. package/dist/server/json-utils.js +57 -0
  29. package/dist/server/marker-service.js +8 -0
  30. package/dist/server/message-window.js +43 -10
  31. package/dist/server/model-admin.js +247 -163
  32. package/dist/server/model-resolver.js +66 -44
  33. package/dist/server/plan-manager.js +3 -6
  34. package/dist/server/plugin-api-catalog.js +1 -0
  35. package/dist/server/plugin-assets.js +238 -0
  36. package/dist/server/plugin-facilities.js +22 -0
  37. package/dist/server/plugin-ui-slots.js +1 -0
  38. package/dist/server/plugins.js +209 -11
  39. package/dist/server/preset-fields.js +25 -1
  40. package/dist/server/preset-share.js +5 -2
  41. package/dist/server/prompt-assembler.js +2 -1
  42. package/dist/server/prompt-composer.js +18 -8
  43. package/dist/server/protocol-version.js +1 -1
  44. package/dist/server/queue-utils.js +156 -0
  45. package/dist/server/remote-ssh-service.js +110 -12
  46. package/dist/server/sdk-builtin-extensions.js +85 -0
  47. package/dist/server/serialize.js +1 -1
  48. package/dist/server/server-config.js +66 -0
  49. package/dist/server/session-parser.js +49 -13
  50. package/dist/server/session-search.js +4 -3
  51. package/dist/server/settings-service.js +74 -53
  52. package/dist/server/setup-page.js +632 -0
  53. package/dist/server/skill-discovery.js +361 -59
  54. package/dist/server/skill-maintenance.js +231 -0
  55. package/dist/server/skill-tool.js +32 -3
  56. package/dist/server/soft-cap.js +30 -6
  57. package/dist/server/subagent-helpers.js +22 -1
  58. package/dist/server/subagent-notify.js +93 -0
  59. package/dist/server/subagent-security-gate.js +282 -0
  60. package/dist/server/subagent-templates.js +8 -0
  61. package/dist/server/subagents.js +390 -48
  62. package/dist/server/terminals.js +196 -8
  63. package/dist/server/text-quote.js +61 -0
  64. package/dist/server/tool-approval.js +63 -4
  65. package/dist/server/tool-guards.js +208 -0
  66. package/dist/server/tool-host-factories.js +48 -10
  67. package/dist/server/tool-manager.js +106 -28
  68. package/dist/server/tool-overrides.js +21 -11
  69. package/dist/server/universal/driver-base.js +8 -0
  70. package/dist/server/universal/drivers/claude-code.js +116 -7
  71. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  72. package/dist/server/universal/index.js +0 -1
  73. package/dist/server/universal/universal-session.js +106 -10
  74. package/dist/server/worktree-service.js +189 -1
  75. package/docs/dsh-engine.md +1 -5
  76. package/package.json +1 -1
  77. package/plugin-sdk/client-utils.mjs +192 -5
  78. package/plugin-sdk/index.d.ts +63 -1
  79. package/plugin-sdk/index.mjs +94 -0
  80. package/plugin-sdk/package.json +5 -1
  81. package/plugins/catalog.json +21 -0
  82. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
  83. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  84. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  85. package/web/dist/index.html +11 -2
  86. package/web/dist/sw.js +1 -1
  87. package/web/dist/assets/index-B0ajS__T.js +0 -697
  88. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -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) => {
@@ -69,9 +161,10 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
69
161
  turnHadText = false;
70
162
  turnCompleteEmitted = false;
71
163
  lastTurnMeta;
164
+ currentThinkingLevel = "medium";
72
165
  constructor(cwd, opts) {
73
166
  super(cwd);
74
- this.executablePath = opts?.executablePath ?? "claude";
167
+ this.executablePath = resolveClaudeExecutable(opts?.executablePath ?? "claude");
75
168
  // 默认添加 --dangerously-skip-permissions,防止无头模式下因等待交互式 y/n 确认导致整个生成假死
76
169
  this.extraArgs = opts?.extraArgs ?? ["--dangerously-skip-permissions"];
77
170
  this.currentModel = opts?.defaultModel ?? "claude-3-7-sonnet-20250219";
@@ -87,6 +180,12 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
87
180
  getActiveSessionId() {
88
181
  return this.activeSessionId;
89
182
  }
183
+ setThinkingLevel(level) {
184
+ this.currentThinkingLevel = level;
185
+ }
186
+ getSupportedThinkingLevels() {
187
+ return ["off", "low", "medium", "high", "xhigh", "max"];
188
+ }
90
189
  async sendPrompt(prompt, attachments, sink) {
91
190
  const mySeq = ++this.turnSeq;
92
191
  this.aborted = false;
@@ -116,7 +215,11 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
116
215
  finalPrompt = `${notes.join("\n")}\n\n${prompt}`;
117
216
  }
118
217
  }
119
- const args = ["-p", finalPrompt, "--output-format", "stream-json", "--verbose", ...this.extraArgs];
218
+ // 提示词通过 stdin 管道写入,argv 仅保留参数选项:
219
+ // 1. 规避 Windows 下 shell: true 拼接命令行导致的注入与 DEP0190 警告;
220
+ // 2. 杜绝 Windows cmd.exe 遇换行 (\n) 截断丢弃后续多行 prompt 的严重缺陷;
221
+ // 3. 避免单次 prompt 超出 Windows 命令行 8191 字符上限。
222
+ const args = ["-p", "--output-format", "stream-json", "--verbose", ...this.extraArgs];
120
223
  // 解析目标模型与对应服务商凭据
121
224
  let targetModel = this.currentModel;
122
225
  let targetProvider = "anthropic";
@@ -134,6 +237,9 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
134
237
  if (targetModel) {
135
238
  args.push("--model", targetModel);
136
239
  }
240
+ if (this.currentThinkingLevel && this.currentThinkingLevel !== "off") {
241
+ args.push("--effort", this.currentThinkingLevel);
242
+ }
137
243
  if (this.activeSessionId) {
138
244
  args.push("--resume", this.activeSessionId);
139
245
  }
@@ -168,8 +274,11 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
168
274
  shell: process.platform === "win32",
169
275
  detached: process.platform !== "win32",
170
276
  });
171
- // 立即关闭 stdin,防止 CLI 因等待流式输入而挂死
172
- proc.stdin?.end();
277
+ // 经 stdin 写入 prompt 并关闭管道,CLI 读完后流式处理
278
+ if (proc.stdin) {
279
+ proc.stdin.write(finalPrompt);
280
+ proc.stdin.end();
281
+ }
173
282
  }
174
283
  catch (err) {
175
284
  const msg = err instanceof Error ? err.message : String(err);
@@ -85,6 +85,9 @@ export class DshAgentDriver extends BaseAgentDriver {
85
85
  getActiveSessionId() {
86
86
  return this.activeSessionId;
87
87
  }
88
+ getSupportedThinkingLevels() {
89
+ return ["high"];
90
+ }
88
91
  /** 绑定运行时通知事件分发到 Universal 底座的 sink */
89
92
  setupNotificationHandler() {
90
93
  this.runtime.onNotification((method, params) => {
@@ -7,4 +7,3 @@ export { UniversalSession } from "./universal-session.js";
7
7
  export { UniversalAgentService } from "./universal-service.js";
8
8
  export { MockAgentDriver } from "./drivers/mock-driver.js";
9
9
  export { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
10
- export { DshAgentDriver } from "./drivers/dsh-driver.js";
@@ -19,7 +19,7 @@ import { ModelAdminService } from "../model-admin.js";
19
19
  import { WebUIContext } from "../webui-context.js";
20
20
  import { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
21
21
  import { normalizeUiLayout, settingsPresetToUi } from "../client-state.js";
22
- import { readModelsJson } from "../model-resolver.js";
22
+ import { readModelsJson, getModelThinkingLevelFromSettings, saveModelThinkingLevelToSettings, } from "../model-resolver.js";
23
23
  import { DEFAULT_UNIVERSAL_CAPABILITIES } from "../engine-capabilities.js";
24
24
  import { unsupportedToolInfo } from "../tool-info.js";
25
25
  import { SandboxManager } from "../sandbox-service.js";
@@ -31,6 +31,7 @@ import { scanAtMentions, createAttachmentUiMessages, formatPromptWithSkills } fr
31
31
  import { scmCommitContext } from "../scm.js";
32
32
  import { buildCommitMsgInput, sanitizeCommitMessage } from "../scm-commitmsg.js";
33
33
  import { getAppVersion } from "../pkg-info.js";
34
+ import { createQueuedEntry, removeQueuedEntry, toQueuedPromptItems } from "../queue-utils.js";
34
35
  import { SubagentTemplatesStore, DEFAULT_TEMPLATES, pickTemplatePrompt, } from "../subagent-templates.js";
35
36
  import { subagentTitle, isSubagentTerminal, computeWaitCapMs, makeSubagentTools, } from "../subagents.js";
36
37
  import { recordSubagentHandoff, formatSubagentHandoffMessage, } from "../subagent-handoff.js";
@@ -38,6 +39,23 @@ import { pick } from "../i18n.js";
38
39
  import { fetchRemoteSkillMarket, fetchRemoteSkillContent, fetchRemoteMcpMarket } from "../market-service.js";
39
40
  import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
40
41
  const SNAPSHOT_INTERVAL_MS = 60;
42
+ function clampThinkingLevelToSupported(supported, current) {
43
+ if (supported.includes(current))
44
+ return current;
45
+ const order = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
46
+ const curIdx = order.indexOf(current);
47
+ if (curIdx === -1)
48
+ return supported[0] ?? "off";
49
+ for (let i = curIdx; i < order.length; i++) {
50
+ if (supported.includes(order[i]))
51
+ return order[i];
52
+ }
53
+ for (let i = curIdx - 1; i >= 0; i--) {
54
+ if (supported.includes(order[i]))
55
+ return order[i];
56
+ }
57
+ return supported[0] ?? "off";
58
+ }
41
59
  export class UniversalSession {
42
60
  cwd;
43
61
  clientId;
@@ -107,10 +125,11 @@ export class UniversalSession {
107
125
  const templatesPath = join(this.dataDir || process.env.PI_WEB_DATA_DIR || join(homedir(), ".pi-web"), "subagent-templates.json");
108
126
  this.subagentTemplates = new SubagentTemplatesStore(templatesPath);
109
127
  this.subagentHost = {
110
- spawnSubagent: async (prompt, type, cwd, templateName, model, parentId, persist) => {
111
- const { convId } = await this.spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist);
128
+ spawnSubagent: async (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, _isolation, _extra) => {
129
+ const { convId } = await this.spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist, undefined, thinking, notifyOnDone);
112
130
  return convId;
113
131
  },
132
+ finalizeSubagentWorktree: async (_convId) => { },
114
133
  getSubagent: (convId) => {
115
134
  const conv = this.conversations.get(convId);
116
135
  if (!conv || !conv.isSubagent)
@@ -120,6 +139,7 @@ export class UniversalSession {
120
139
  listSubagents: (scope) => this.listSubagents(scope),
121
140
  steerSubagent: (convId, message) => this.steerSubagent(convId, message),
122
141
  stopSubagent: (convId) => this.stopSubagent(convId),
142
+ markSubagentsConsumed: (_runIds) => { },
123
143
  listTemplates: () => this.subagentTemplates
124
144
  .list()
125
145
  .filter((t) => t.enabled !== false)
@@ -134,6 +154,19 @@ export class UniversalSession {
134
154
  const t = this.subagentTemplates.get(name);
135
155
  return !!t && t.enabled !== false;
136
156
  },
157
+ getActiveConversationId: () => this.activeConvId,
158
+ dismissSubagent: async (convId, opts) => {
159
+ const conv = this.conversations.get(convId);
160
+ if (!conv)
161
+ return { ok: false, reason: "not_found" };
162
+ if (convId === this.activeConvId)
163
+ return { ok: false, reason: "active" };
164
+ if (!conv.isSubagent && !conv.subagentParentId)
165
+ return { ok: false, reason: "not_subagent" };
166
+ await this.dismissConversation(convId, true, opts?.force);
167
+ const stillThere = this.conversations.has(convId);
168
+ return stillThere ? { ok: false, reason: "retained" } : { ok: true };
169
+ },
137
170
  getWatchdogTimeoutMs: () => 20 * 60_000,
138
171
  handoffSubagent: (fromRunId, toRunId, payload) => this.handoffSubagent(fromRunId, toRunId, payload),
139
172
  lang: () => this.lang,
@@ -242,6 +275,20 @@ export class UniversalSession {
242
275
  if (savedModel) {
243
276
  this.currentModel = savedModel;
244
277
  }
278
+ // 恢复思考强度记忆:模型专属记忆 > 全局默认 > 既有默认
279
+ const rememberedThinking = getModelThinkingLevelFromSettings(this.currentModel, this.agentDir);
280
+ if (rememberedThinking) {
281
+ this.thinkingLevel = rememberedThinking;
282
+ }
283
+ if (typeof this.driver.getSupportedThinkingLevels === "function") {
284
+ const supported = this.driver.getSupportedThinkingLevels(this.currentModel);
285
+ if (supported.length > 0 && !supported.includes(this.thinkingLevel)) {
286
+ this.thinkingLevel = clampThinkingLevelToSupported(supported, this.thinkingLevel);
287
+ }
288
+ }
289
+ if (typeof this.driver.setThinkingLevel === "function") {
290
+ this.driver.setThinkingLevel(this.thinkingLevel);
291
+ }
245
292
  this.modelAdmin = new ModelAdminService({
246
293
  agentDir: this.agentDir,
247
294
  emit: (msg) => this.send(msg),
@@ -459,10 +506,16 @@ export class UniversalSession {
459
506
  vision: curModel.vision,
460
507
  },
461
508
  thinkingLevel: this.thinkingLevel,
462
- availableThinkingLevels: ["off", "low", "medium", "high"],
509
+ availableThinkingLevels: typeof this.driver.getSupportedThinkingLevels === "function"
510
+ ? this.driver.getSupportedThinkingLevels(this.currentModel)
511
+ : ["off", "minimal", "low", "medium", "high", "xhigh", "max"],
463
512
  queue: {
464
513
  steering: [],
465
514
  followUp: this.followUpQueue.map((q) => q.text),
515
+ entries: {
516
+ steering: [],
517
+ followUp: toQueuedPromptItems(this.followUpQueue),
518
+ },
466
519
  },
467
520
  tools: [],
468
521
  version: this.version,
@@ -504,7 +557,8 @@ export class UniversalSession {
504
557
  async prompt(text, attachments, _queue) {
505
558
  if (this.isStreaming) {
506
559
  if (_queue === true) {
507
- this.followUpQueue.push({ text, attachments });
560
+ const entry = createQueuedEntry(text, { attachments });
561
+ this.followUpQueue.push(entry);
508
562
  this.flushSnapshot();
509
563
  this.emitNotice("info", "已加入排队,将在当前回复生成完成后自动发送", "Queued — will send after current response settles");
510
564
  return;
@@ -770,14 +824,18 @@ export class UniversalSession {
770
824
  }
771
825
  this.isStreaming = false;
772
826
  this.streamingThinking = "";
827
+ // 先取本轮全文再清空:内联标记解析在清空之后读 streamingText,
828
+ // 条件恒为 false,[[conv:rename]]/[[action:suggest]] 在 universal
829
+ // 引擎(claude/durable 等驱动)下从不被解析。
830
+ const finalText = this.streamingText;
773
831
  this.streamingText = "";
774
832
  conv.updatedAt = Date.now();
775
833
  if (!conv.isEphemeral) {
776
834
  this.store.saveConversation(this.cwd, conv);
777
835
  }
778
836
  // 解析本轮生成的内联标记(如 [[conv:rename:...]] / [[action:suggest:...]])
779
- if (this.streamingText && this.streamingText.includes("[[")) {
780
- void this.markerSvc.handleAssistantText(conv.id, this.streamingText);
837
+ if (finalText && finalText.includes("[[")) {
838
+ void this.markerSvc.handleAssistantText(conv.id, finalText);
781
839
  }
782
840
  this.flushSnapshot();
783
841
  void this.refreshSessions();
@@ -812,8 +870,14 @@ export class UniversalSession {
812
870
  }
813
871
  }
814
872
  }
815
- removeQueued() {
816
- /* 通用底座暂无插队队列 */
873
+ removeQueued(kind, text, index, id) {
874
+ if (kind === "followUp") {
875
+ const next = removeQueuedEntry(this.followUpQueue, { id, text, index });
876
+ if (next.length !== this.followUpQueue.length) {
877
+ this.followUpQueue = next;
878
+ this.flushSnapshot();
879
+ }
880
+ }
817
881
  }
818
882
  // ---------------------------------------------------------------------------
819
883
  // 对话生命周期
@@ -1320,6 +1384,12 @@ export class UniversalSession {
1320
1384
  getTerminalManager() {
1321
1385
  return this.terminals;
1322
1386
  }
1387
+ getUserTerminalManager() {
1388
+ return this.terminals;
1389
+ }
1390
+ findTerminalManager() {
1391
+ return this.terminals;
1392
+ }
1323
1393
  getTerminalCwd() {
1324
1394
  return this.cwd;
1325
1395
  }
@@ -1392,6 +1462,22 @@ export class UniversalSession {
1392
1462
  if (this.driver.setModel) {
1393
1463
  await this.driver.setModel(modelId);
1394
1464
  }
1465
+ // 优先恢复该模型的全局思考强度记忆或全局默认强度
1466
+ const remembered = getModelThinkingLevelFromSettings(modelId, this.agentDir);
1467
+ if (remembered) {
1468
+ this.thinkingLevel = remembered;
1469
+ }
1470
+ // 校验并平滑适应新模型支持的思考强度
1471
+ if (typeof this.driver.getSupportedThinkingLevels === "function") {
1472
+ const supported = this.driver.getSupportedThinkingLevels(modelId);
1473
+ if (supported.length > 0 && !supported.includes(this.thinkingLevel)) {
1474
+ const clamped = clampThinkingLevelToSupported(supported, this.thinkingLevel);
1475
+ this.thinkingLevel = clamped;
1476
+ }
1477
+ }
1478
+ if (typeof this.driver.setThinkingLevel === "function") {
1479
+ this.driver.setThinkingLevel(this.thinkingLevel);
1480
+ }
1395
1481
  const info = this.resolveCurrentModelInfo();
1396
1482
  this.emitNotice("info", `已切换到模型:${info.name}`, `Switched to model: ${info.name}`);
1397
1483
  this.flushSnapshot();
@@ -1414,6 +1500,13 @@ export class UniversalSession {
1414
1500
  }
1415
1501
  setThinking(level) {
1416
1502
  this.thinkingLevel = level;
1503
+ if (typeof this.driver.setThinkingLevel === "function") {
1504
+ this.driver.setThinkingLevel(level);
1505
+ }
1506
+ // 同步持久化至全局 settings.json 的 modelThinkingLevels
1507
+ if (this.currentModel) {
1508
+ saveModelThinkingLevelToSettings(this.currentModel, level, this.agentDir);
1509
+ }
1417
1510
  this.flushSnapshot();
1418
1511
  }
1419
1512
  async setCwd(path) {
@@ -1845,6 +1938,7 @@ export class UniversalSession {
1845
1938
  uiLayout: normalizeUiLayout(s?.uiLayout),
1846
1939
  promptTemplate: s?.promptTemplate ?? "",
1847
1940
  promptOverrides: s?.promptOverrides ?? {},
1941
+ promptDisabled: [...(s?.promptDisabled ?? [])],
1848
1942
  toolPromptOverrides: {},
1849
1943
  effectiveSystemPrompt: "",
1850
1944
  promptSourceDefaults: {},
@@ -2006,6 +2100,7 @@ export class UniversalSession {
2006
2100
  customSystemPrompt: s.customSystemPrompt,
2007
2101
  promptTemplate: s.promptTemplate,
2008
2102
  promptOverrides: s.promptOverrides ? { ...s.promptOverrides } : {},
2103
+ promptDisabled: [...(s.promptDisabled ?? [])],
2009
2104
  disabledSkills: [...(s?.disabledSkills ?? [])],
2010
2105
  disabledExtensions: [...(s?.disabledExtensions ?? [])],
2011
2106
  reviewPrompt: s.reviewPrompt ?? "",
@@ -2030,6 +2125,7 @@ export class UniversalSession {
2030
2125
  this.stateStore.saveSettings(this.clientId, {
2031
2126
  promptMode: found.promptMode,
2032
2127
  customSystemPrompt: found.customSystemPrompt,
2128
+ promptDisabled: [...(found.promptDisabled ?? [])],
2033
2129
  disabledSkills: [...(found.disabledSkills ?? [])],
2034
2130
  disabledExtensions: [...(found.disabledExtensions ?? [])],
2035
2131
  reviewPrompt: found.reviewPrompt ?? "",
@@ -2249,7 +2345,7 @@ export class UniversalSession {
2249
2345
  return count;
2250
2346
  }
2251
2347
  /** 创建并启动一个子代理会话 */
2252
- async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title) {
2348
+ async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title, _thinking, _notifyOnDone) {
2253
2349
  const maxSubagents = Number(process.env.PI_WEB_MAX_SUBAGENTS) || 8;
2254
2350
  const liveCount = this.getLiveSubagentsCount();
2255
2351
  if (liveCount >= maxSubagents) {
@@ -232,7 +232,20 @@ export async function removeWorktree(cwd, targetPathInput, force = false, lang)
232
232
  if (force)
233
233
  args.push("--force");
234
234
  args.push(targetPath);
235
- await runGit(cwd, args);
235
+ let lastErr;
236
+ for (let attempt = 0; attempt < 3; attempt++) {
237
+ try {
238
+ await runGit(cwd, args);
239
+ return;
240
+ }
241
+ catch (err) {
242
+ lastErr = err;
243
+ if (attempt < 2) {
244
+ await new Promise((r) => setTimeout(r, 200));
245
+ }
246
+ }
247
+ }
248
+ throw lastErr;
236
249
  }
237
250
  /** 获取当前目录的完整工作树上下文元数据(用于 UI 横幅与快照)。 */
238
251
  export async function getWorktreeContext(cwd) {
@@ -260,3 +273,178 @@ export async function getWorktreeContext(cwd) {
260
273
  return null;
261
274
  }
262
275
  }
276
+ /** 仓库级异步操作互斥锁(防止多个子代理并发创建/删除工作树时碰撞 Git 内部文件锁)。 */
277
+ const repoLocks = new Map();
278
+ export async function withRepoLock(repoPath, task) {
279
+ const key = normalizeWirePath(repoPath);
280
+ const prev = repoLocks.get(key) ?? Promise.resolve();
281
+ let release;
282
+ const gate = new Promise((resolve) => {
283
+ release = resolve;
284
+ });
285
+ repoLocks.set(key, prev.catch(() => { }).then(() => gate));
286
+ try {
287
+ await prev.catch(() => { });
288
+ return await task();
289
+ }
290
+ finally {
291
+ release();
292
+ if (repoLocks.get(key) === gate) {
293
+ repoLocks.delete(key);
294
+ }
295
+ }
296
+ }
297
+ /** 自动将 .worktrees/ 加入 .git/info/exclude(零污染:防止未在 .gitignore 忽略此目录的用户仓库出现 untracked 脏状态)。 */
298
+ export async function ensureWorktreeExcluded(repoPath) {
299
+ try {
300
+ const gitCommonDir = (await runGit(repoPath, ["rev-parse", "--git-common-dir"], FAST_GIT_TIMEOUT_MS)).trim();
301
+ const absGitCommon = resolve(repoPath, gitCommonDir);
302
+ const excludeFile = resolve(absGitCommon, "info", "exclude");
303
+ const { existsSync, readFileSync, appendFileSync, mkdirSync, writeFileSync } = await import("node:fs");
304
+ if (existsSync(excludeFile)) {
305
+ const content = readFileSync(excludeFile, "utf-8");
306
+ if (!content.includes(".worktrees")) {
307
+ appendFileSync(excludeFile, "\n# pi-web-ui worktrees\n.worktrees/\n");
308
+ }
309
+ }
310
+ else {
311
+ mkdirSync(resolve(absGitCommon, "info"), { recursive: true });
312
+ writeFileSync(excludeFile, "# pi-web-ui worktrees\n.worktrees/\n", "utf-8");
313
+ }
314
+ }
315
+ catch {
316
+ // non-fatal
317
+ }
318
+ }
319
+ /**
320
+ * 为子代理创建专用的 Git 工作树与分支(issue #728)。
321
+ * 自动从当前 HEAD 检出,并建立依赖软链接(node_modules/.venv 等),使子代理可立即执行测试。
322
+ */
323
+ export async function createSubagentWorktree(baseCwd, subagentId, lang) {
324
+ const l = lang?.() ?? "en";
325
+ const inside = await isInsideGitRepo(baseCwd);
326
+ if (!inside) {
327
+ throw new Error(pick(l, `Git 工作树隔离失败:目录「${baseCwd}」不是 Git 仓库。worktree 隔离模式要求工作区位于有效的 Git 仓库中。`, `Git worktree isolation failed: "${baseCwd}" is not a Git repository. Worktree isolation mode requires a valid Git repository.`, "worktree.isolation.not_git", { baseCwd }));
328
+ }
329
+ const rawText = await runGit(baseCwd, ["worktree", "list", "--porcelain"]);
330
+ const rawItems = parseWorktreePorcelain(rawText);
331
+ const mainRepoPath = rawItems[0]?.path || normalizeWirePath(resolve(baseCwd));
332
+ const worktreeDir = normalizeWirePath(resolve(mainRepoPath, ".worktrees", subagentId));
333
+ const branchName = `subagent/${subagentId}`;
334
+ // 获取创建时刻的当前 HEAD SHA 作为基准
335
+ const baseCommit = (await runGit(baseCwd, ["rev-parse", "HEAD"])).trim();
336
+ // 确定子代理的执行目录(若 baseCwd 在 mainRepoPath 的子目录中,则映射至工作树对应子目录)
337
+ const normBase = normalizeWirePath(resolve(baseCwd));
338
+ const normMain = normalizeWirePath(resolve(mainRepoPath));
339
+ let subagentCwd = worktreeDir;
340
+ if (normBase.startsWith(normMain + "/")) {
341
+ const rel = normBase.slice(normMain.length + 1);
342
+ subagentCwd = normalizeWirePath(resolve(worktreeDir, rel));
343
+ }
344
+ await withRepoLock(mainRepoPath, async () => {
345
+ await ensureWorktreeExcluded(mainRepoPath);
346
+ const { mkdirSync, existsSync, symlinkSync } = await import("node:fs");
347
+ mkdirSync(resolve(mainRepoPath, ".worktrees"), { recursive: true });
348
+ // 使用 -B 确保分支已存在时安全重置,HEAD 确保从当前状态检出
349
+ await runGit(mainRepoPath, ["worktree", "add", "-B", branchName, worktreeDir, "HEAD"]);
350
+ // 依赖桥接:若主仓库根有 node_modules 或 .venv,在工作树中建立目录软连接/Junction,
351
+ // 这样子代理可立即运行 npm test / python 测试,无需耗时重装依赖
352
+ for (const depDir of ["node_modules", ".venv"]) {
353
+ const src = resolve(mainRepoPath, depDir);
354
+ const dest = resolve(worktreeDir, depDir);
355
+ if (existsSync(src) && !existsSync(dest)) {
356
+ try {
357
+ symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
358
+ }
359
+ catch {
360
+ // 软链接失败不阻断工作树核心流程
361
+ }
362
+ }
363
+ }
364
+ });
365
+ return {
366
+ worktreePath: worktreeDir,
367
+ mainRepoPath,
368
+ branch: branchName,
369
+ baseCommit,
370
+ subagentCwd,
371
+ };
372
+ }
373
+ /**
374
+ * 终态判定与清理(issue #728):
375
+ * 双重判定改动(未提交修改 + 领先 commit 数):
376
+ * - 无改动:自动安全清理工作树并删除临时分支;
377
+ * - 有改动:保留工作树与分支供父对话审阅、合并或清理。
378
+ */
379
+ export async function finalizeSubagentWorktree(wt, lang) {
380
+ if (wt.finalized)
381
+ return wt;
382
+ const { existsSync } = await import("node:fs");
383
+ if (!existsSync(wt.worktreePath)) {
384
+ wt.finalized = true;
385
+ wt.cleanedUp = true;
386
+ return wt;
387
+ }
388
+ try {
389
+ const { isDirty, count: uncommittedCount } = await getUncommittedCount(wt.worktreePath);
390
+ let aheadCount = 0;
391
+ try {
392
+ const currentHead = (await runGit(wt.worktreePath, ["rev-parse", "HEAD"])).trim();
393
+ if (currentHead !== wt.baseCommit) {
394
+ aheadCount = await getAheadCount(wt.worktreePath, wt.baseCommit);
395
+ if (aheadCount === 0 && currentHead !== wt.baseCommit) {
396
+ aheadCount = 1;
397
+ }
398
+ }
399
+ }
400
+ catch {
401
+ aheadCount = 0;
402
+ }
403
+ wt.isDirty = isDirty;
404
+ wt.uncommittedCount = uncommittedCount;
405
+ wt.aheadCount = aheadCount;
406
+ const hasChanges = isDirty || aheadCount > 0;
407
+ if (!hasChanges) {
408
+ // 没有改动 -> 自动清理工作树与临时分支
409
+ await withRepoLock(wt.mainRepoPath, async () => {
410
+ // 先移除建立的软链接/Junction,防止 Windows 下锁死目录句柄
411
+ for (const depDir of ["node_modules", ".venv"]) {
412
+ const p = resolve(wt.worktreePath, depDir);
413
+ if (existsSync(p)) {
414
+ try {
415
+ const { unlinkSync } = await import("node:fs");
416
+ unlinkSync(p);
417
+ }
418
+ catch { }
419
+ }
420
+ }
421
+ await removeWorktree(wt.mainRepoPath, wt.worktreePath, true, lang);
422
+ try {
423
+ await runGit(wt.mainRepoPath, ["branch", "-D", wt.branch]);
424
+ }
425
+ catch { }
426
+ });
427
+ wt.cleanedUp = true;
428
+ }
429
+ else {
430
+ // 有改动 -> 完整保留,由父对话决定合并还是清理
431
+ wt.cleanedUp = false;
432
+ }
433
+ wt.finalized = true;
434
+ }
435
+ catch (err) {
436
+ wt.finalized = true;
437
+ wt.error = err.message;
438
+ }
439
+ return wt;
440
+ }
441
+ /** 剪枝清理已损坏或残留的孤儿工作树 */
442
+ export async function pruneOrphanSubagentWorktrees(cwd) {
443
+ try {
444
+ const inside = await isInsideGitRepo(cwd);
445
+ if (!inside)
446
+ return;
447
+ await runGit(cwd, ["worktree", "prune"], FAST_GIT_TIMEOUT_MS);
448
+ }
449
+ catch { }
450
+ }
@@ -279,11 +279,7 @@ E:/pi-web-ui/server/dsh/
279
279
  - **设置面板**:第二轮后全量存储回显(promptMode/customSystemPrompt/terminalToolsEnabled/terminalBash/thinkingWrap/toolsWrap/disabledSkills/disabledExtensions/disabledPlugins/reviewPrompt 经 ClientStateStore 持久化,跨重连存活);仅 prompt 相关变化才重启运行时(DSH_PERSONA env 注入);引擎专属设置项扩展机制(Engine-Contributed Settings)动态呈现 DSH 预设与三档权限、补丁与市场、问卷调研;通用底座设置项全量兼容。
280
280
  - **视觉桥**:✅ 完成(§2.7)—— 真 image block(attachment/save + read RPC + vision-exp 模型 + 回放补图)。图片附件/工作区图片文件都走附件存储。注意:仅 deepseek-v4-flash-vision-exp 模型看图。
281
281
  - **第三方自定义端点与模型接入(models.json)**:✅ 完成 —— DSH 引擎接入公共模型底座,自动枚举 `models.json` 中配置的第三方自定义端点模型(如 `antigravity-openai/gemini-3.8-flash` 等);切换时动态解析 BaseURL 与 API Key 并注入子进程环境变量 `DEEPSEEK_BASE_URL` 与 `DEEPSEEK_API_KEY`,RPC 握手传递真实模型 ID,实现第三方 OpenAI 兼容端点在 DSH 运行时的直接调用执行。
282
- - **Universal Agent 底座驱动化(DshAgentDriver)**:✅ 完成 —— 在 `server/universal/drivers/dsh-driver.ts` 中完整实现 `BaseAgentDriver` 契约,使 DSH 能作为标准驱动插装至 Universal Agent 底座(`server/universal/`):
283
- - 具备完整的能力矩阵声明(`AgentCapabilities`: `supportsModelSwitch: true, supportsThinkingLevels: true, supportsAskUser: true`);
284
- - 将 DSH stdio JSON-RPC 的 `assistant/chunk`(`reasoning-delta` / `text-delta`)、`tool/call`、`tool/result` 与 `assistant/message` 统一投影至底座的 `AgentEventSink`(`onThinkingDelta` / `onTextDelta` / `onToolStart` / `onToolEnd` / `onTurnComplete`);
285
- - 自动结合 `normalizeDshUsage` 计算 Token 四桶统计与成本;
286
- - `UniversalSession` 原生适配 DSH 默认高思考等级与预设模型,实现真正的驱动插拔式底座化!
282
+ - **Universal Agent 底座驱动化(DshAgentDriver)**:⚠️ 已退役 —— 曾尝试在 `server/universal/drivers/dsh-driver.ts` 实现 `BaseAgentDriver`,但由于 DSH 为具备 4 预设克隆挂载、独立 RPC 守护进程与原生 Goal 状态机的复合引擎(非简单单进程驱动),将复合引擎降格为轻量 Driver 存在抽象层级错配。为避免产生未经检验的第三套 DSH 运行时,该驱动已于 #733 彻底清理;DSH 与通用底座的收敛未来统一走 #469(自顶向下抽取共享 `BaseAgentService`)。
287
283
  - **对话框(dialog_response)/ 扩展 UI 桥**:DSH 侧已有提问桥(question_pending/question_answer,§2.7);pi 扩展 dialog(dialog_response)v1 仍忽略。
288
284
  - **目标调研向导(startGoalWizard)**:✅ 完成(§2.7)—— 交互式(模型 ask_user_question 逐题提问 + 前端对话框 + GOAL: 收敛 + 自动设目标)。
289
285
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.111.0",
3
+ "version": "0.113.0",
4
4
  "description": "Just open your browser to get all your work done — browser cockpit for AI coding agents (chat, code, files, terminal, Git in one tab)",
5
5
  "license": "MIT",
6
6
  "author": {