pi-web-ui 0.111.0 → 0.112.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 (77) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/dist/server/agent-service.js +1325 -488
  4. package/dist/server/approval-audit.js +119 -0
  5. package/dist/server/approval-default-rules.js +4 -4
  6. package/dist/server/approval-rules.js +42 -17
  7. package/dist/server/attachment-store.js +8 -8
  8. package/dist/server/canvas/canvas-agent-tool.js +6 -0
  9. package/dist/server/canvas/canvas-orchestrator.js +88 -21
  10. package/dist/server/client-state.js +28 -0
  11. package/dist/server/delegate-mode.js +6 -3
  12. package/dist/server/delegate-task.js +18 -3
  13. package/dist/server/dispatch-domain-handlers.js +3 -0
  14. package/dist/server/dsh/dsh-agent-service.js +242 -11
  15. package/dist/server/dsh/dsh-serialize.js +1 -1
  16. package/dist/server/durable/durable-driver.js +75 -9
  17. package/dist/server/durable/durable-loader.js +1 -14
  18. package/dist/server/durable/durable-models.js +107 -0
  19. package/dist/server/durable/index.js +0 -4
  20. package/dist/server/engine-probe.js +76 -37
  21. package/dist/server/eval-tool.js +28 -3
  22. package/dist/server/goal-service.js +7 -0
  23. package/dist/server/index.js +344 -56
  24. package/dist/server/json-utils.js +57 -0
  25. package/dist/server/marker-service.js +8 -0
  26. package/dist/server/message-window.js +43 -10
  27. package/dist/server/model-admin.js +68 -106
  28. package/dist/server/model-resolver.js +66 -44
  29. package/dist/server/plan-manager.js +3 -6
  30. package/dist/server/plugin-api-catalog.js +1 -0
  31. package/dist/server/plugin-assets.js +238 -0
  32. package/dist/server/plugin-facilities.js +22 -0
  33. package/dist/server/plugin-ui-slots.js +1 -0
  34. package/dist/server/plugins.js +199 -5
  35. package/dist/server/preset-fields.js +25 -1
  36. package/dist/server/preset-share.js +5 -2
  37. package/dist/server/prompt-assembler.js +2 -1
  38. package/dist/server/prompt-composer.js +18 -8
  39. package/dist/server/protocol-version.js +1 -1
  40. package/dist/server/queue-utils.js +156 -0
  41. package/dist/server/sdk-builtin-extensions.js +85 -0
  42. package/dist/server/server-config.js +66 -0
  43. package/dist/server/session-parser.js +49 -13
  44. package/dist/server/session-search.js +4 -3
  45. package/dist/server/settings-service.js +38 -5
  46. package/dist/server/soft-cap.js +8 -6
  47. package/dist/server/subagent-helpers.js +22 -1
  48. package/dist/server/subagent-notify.js +93 -0
  49. package/dist/server/subagent-security-gate.js +282 -0
  50. package/dist/server/subagent-templates.js +8 -0
  51. package/dist/server/subagents.js +144 -17
  52. package/dist/server/terminals.js +196 -8
  53. package/dist/server/text-quote.js +61 -0
  54. package/dist/server/tool-approval.js +63 -4
  55. package/dist/server/tool-guards.js +208 -0
  56. package/dist/server/tool-host-factories.js +46 -10
  57. package/dist/server/tool-overrides.js +21 -11
  58. package/dist/server/universal/driver-base.js +8 -0
  59. package/dist/server/universal/drivers/claude-code.js +20 -3
  60. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  61. package/dist/server/universal/index.js +0 -1
  62. package/dist/server/universal/universal-session.js +87 -10
  63. package/dist/server/worktree-service.js +189 -1
  64. package/docs/dsh-engine.md +1 -5
  65. package/package.json +1 -1
  66. package/plugin-sdk/client-utils.mjs +192 -5
  67. package/plugin-sdk/index.d.ts +63 -1
  68. package/plugin-sdk/index.mjs +94 -0
  69. package/plugin-sdk/package.json +5 -1
  70. package/plugins/catalog.json +11 -0
  71. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-Dqr1dK28.js} +1 -1
  72. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  73. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  74. package/web/dist/index.html +11 -2
  75. package/web/dist/sw.js +1 -1
  76. package/web/dist/assets/index-B0ajS__T.js +0 -697
  77. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -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)
@@ -242,6 +262,20 @@ export class UniversalSession {
242
262
  if (savedModel) {
243
263
  this.currentModel = savedModel;
244
264
  }
265
+ // 恢复思考强度记忆:模型专属记忆 > 全局默认 > 既有默认
266
+ const rememberedThinking = getModelThinkingLevelFromSettings(this.currentModel, this.agentDir);
267
+ if (rememberedThinking) {
268
+ this.thinkingLevel = rememberedThinking;
269
+ }
270
+ if (typeof this.driver.getSupportedThinkingLevels === "function") {
271
+ const supported = this.driver.getSupportedThinkingLevels(this.currentModel);
272
+ if (supported.length > 0 && !supported.includes(this.thinkingLevel)) {
273
+ this.thinkingLevel = clampThinkingLevelToSupported(supported, this.thinkingLevel);
274
+ }
275
+ }
276
+ if (typeof this.driver.setThinkingLevel === "function") {
277
+ this.driver.setThinkingLevel(this.thinkingLevel);
278
+ }
245
279
  this.modelAdmin = new ModelAdminService({
246
280
  agentDir: this.agentDir,
247
281
  emit: (msg) => this.send(msg),
@@ -459,10 +493,16 @@ export class UniversalSession {
459
493
  vision: curModel.vision,
460
494
  },
461
495
  thinkingLevel: this.thinkingLevel,
462
- availableThinkingLevels: ["off", "low", "medium", "high"],
496
+ availableThinkingLevels: typeof this.driver.getSupportedThinkingLevels === "function"
497
+ ? this.driver.getSupportedThinkingLevels(this.currentModel)
498
+ : ["off", "minimal", "low", "medium", "high", "xhigh", "max"],
463
499
  queue: {
464
500
  steering: [],
465
501
  followUp: this.followUpQueue.map((q) => q.text),
502
+ entries: {
503
+ steering: [],
504
+ followUp: toQueuedPromptItems(this.followUpQueue),
505
+ },
466
506
  },
467
507
  tools: [],
468
508
  version: this.version,
@@ -504,7 +544,8 @@ export class UniversalSession {
504
544
  async prompt(text, attachments, _queue) {
505
545
  if (this.isStreaming) {
506
546
  if (_queue === true) {
507
- this.followUpQueue.push({ text, attachments });
547
+ const entry = createQueuedEntry(text, { attachments });
548
+ this.followUpQueue.push(entry);
508
549
  this.flushSnapshot();
509
550
  this.emitNotice("info", "已加入排队,将在当前回复生成完成后自动发送", "Queued — will send after current response settles");
510
551
  return;
@@ -770,14 +811,18 @@ export class UniversalSession {
770
811
  }
771
812
  this.isStreaming = false;
772
813
  this.streamingThinking = "";
814
+ // 先取本轮全文再清空:内联标记解析在清空之后读 streamingText,
815
+ // 条件恒为 false,[[conv:rename]]/[[action:suggest]] 在 universal
816
+ // 引擎(claude/durable 等驱动)下从不被解析。
817
+ const finalText = this.streamingText;
773
818
  this.streamingText = "";
774
819
  conv.updatedAt = Date.now();
775
820
  if (!conv.isEphemeral) {
776
821
  this.store.saveConversation(this.cwd, conv);
777
822
  }
778
823
  // 解析本轮生成的内联标记(如 [[conv:rename:...]] / [[action:suggest:...]])
779
- if (this.streamingText && this.streamingText.includes("[[")) {
780
- void this.markerSvc.handleAssistantText(conv.id, this.streamingText);
824
+ if (finalText && finalText.includes("[[")) {
825
+ void this.markerSvc.handleAssistantText(conv.id, finalText);
781
826
  }
782
827
  this.flushSnapshot();
783
828
  void this.refreshSessions();
@@ -812,8 +857,14 @@ export class UniversalSession {
812
857
  }
813
858
  }
814
859
  }
815
- removeQueued() {
816
- /* 通用底座暂无插队队列 */
860
+ removeQueued(kind, text, index, id) {
861
+ if (kind === "followUp") {
862
+ const next = removeQueuedEntry(this.followUpQueue, { id, text, index });
863
+ if (next.length !== this.followUpQueue.length) {
864
+ this.followUpQueue = next;
865
+ this.flushSnapshot();
866
+ }
867
+ }
817
868
  }
818
869
  // ---------------------------------------------------------------------------
819
870
  // 对话生命周期
@@ -1392,6 +1443,22 @@ export class UniversalSession {
1392
1443
  if (this.driver.setModel) {
1393
1444
  await this.driver.setModel(modelId);
1394
1445
  }
1446
+ // 优先恢复该模型的全局思考强度记忆或全局默认强度
1447
+ const remembered = getModelThinkingLevelFromSettings(modelId, this.agentDir);
1448
+ if (remembered) {
1449
+ this.thinkingLevel = remembered;
1450
+ }
1451
+ // 校验并平滑适应新模型支持的思考强度
1452
+ if (typeof this.driver.getSupportedThinkingLevels === "function") {
1453
+ const supported = this.driver.getSupportedThinkingLevels(modelId);
1454
+ if (supported.length > 0 && !supported.includes(this.thinkingLevel)) {
1455
+ const clamped = clampThinkingLevelToSupported(supported, this.thinkingLevel);
1456
+ this.thinkingLevel = clamped;
1457
+ }
1458
+ }
1459
+ if (typeof this.driver.setThinkingLevel === "function") {
1460
+ this.driver.setThinkingLevel(this.thinkingLevel);
1461
+ }
1395
1462
  const info = this.resolveCurrentModelInfo();
1396
1463
  this.emitNotice("info", `已切换到模型:${info.name}`, `Switched to model: ${info.name}`);
1397
1464
  this.flushSnapshot();
@@ -1414,6 +1481,13 @@ export class UniversalSession {
1414
1481
  }
1415
1482
  setThinking(level) {
1416
1483
  this.thinkingLevel = level;
1484
+ if (typeof this.driver.setThinkingLevel === "function") {
1485
+ this.driver.setThinkingLevel(level);
1486
+ }
1487
+ // 同步持久化至全局 settings.json 的 modelThinkingLevels
1488
+ if (this.currentModel) {
1489
+ saveModelThinkingLevelToSettings(this.currentModel, level, this.agentDir);
1490
+ }
1417
1491
  this.flushSnapshot();
1418
1492
  }
1419
1493
  async setCwd(path) {
@@ -1845,6 +1919,7 @@ export class UniversalSession {
1845
1919
  uiLayout: normalizeUiLayout(s?.uiLayout),
1846
1920
  promptTemplate: s?.promptTemplate ?? "",
1847
1921
  promptOverrides: s?.promptOverrides ?? {},
1922
+ promptDisabled: [...(s?.promptDisabled ?? [])],
1848
1923
  toolPromptOverrides: {},
1849
1924
  effectiveSystemPrompt: "",
1850
1925
  promptSourceDefaults: {},
@@ -2006,6 +2081,7 @@ export class UniversalSession {
2006
2081
  customSystemPrompt: s.customSystemPrompt,
2007
2082
  promptTemplate: s.promptTemplate,
2008
2083
  promptOverrides: s.promptOverrides ? { ...s.promptOverrides } : {},
2084
+ promptDisabled: [...(s.promptDisabled ?? [])],
2009
2085
  disabledSkills: [...(s?.disabledSkills ?? [])],
2010
2086
  disabledExtensions: [...(s?.disabledExtensions ?? [])],
2011
2087
  reviewPrompt: s.reviewPrompt ?? "",
@@ -2030,6 +2106,7 @@ export class UniversalSession {
2030
2106
  this.stateStore.saveSettings(this.clientId, {
2031
2107
  promptMode: found.promptMode,
2032
2108
  customSystemPrompt: found.customSystemPrompt,
2109
+ promptDisabled: [...(found.promptDisabled ?? [])],
2033
2110
  disabledSkills: [...(found.disabledSkills ?? [])],
2034
2111
  disabledExtensions: [...(found.disabledExtensions ?? [])],
2035
2112
  reviewPrompt: found.reviewPrompt ?? "",
@@ -2249,7 +2326,7 @@ export class UniversalSession {
2249
2326
  return count;
2250
2327
  }
2251
2328
  /** 创建并启动一个子代理会话 */
2252
- async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title) {
2329
+ async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title, _thinking, _notifyOnDone) {
2253
2330
  const maxSubagents = Number(process.env.PI_WEB_MAX_SUBAGENTS) || 8;
2254
2331
  const liveCount = this.getLiveSubagentsCount();
2255
2332
  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.112.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": {
@@ -22,7 +22,7 @@ export function esc(s) {
22
22
  * @returns {any} 宿主 API 对象或 null
23
23
  */
24
24
  export function hostApi() {
25
- return typeof window !== "undefined" ? window.__piWebUiHost ?? null : null;
25
+ return typeof window !== "undefined" ? (window.__piWebUiHost ?? null) : null;
26
26
  }
27
27
 
28
28
  /**
@@ -58,10 +58,7 @@ export function formatBytes(bytes, decimals = 1) {
58
58
  * @returns {Promise<T>}
59
59
  */
60
60
  export function withTimeout(promise, timeoutMs, errorMsg = "Operation timed out") {
61
- return Promise.race([
62
- promise,
63
- new Promise((_, reject) => setTimeout(() => reject(new Error(errorMsg)), timeoutMs)),
64
- ]);
61
+ return Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error(errorMsg)), timeoutMs))]);
65
62
  }
66
63
 
67
64
  /**
@@ -90,3 +87,193 @@ export function normalizeRel(p) {
90
87
  .replace(/^\.?\/+/, "")
91
88
  .replace(/\/+$/, "");
92
89
  }
90
+
91
+ /**
92
+ * 为容器创建 Shadow DOM 并注入基础主题继承样式。
93
+ * @param {HTMLElement} hostEl 宿主容器元素
94
+ * @param {string} [customCss] 额外注入该组件的隔离样式
95
+ * @returns {ShadowRoot} 创建或已存在的 open 模式 ShadowRoot
96
+ */
97
+ export function attachShadowRoot(hostEl, customCss = "") {
98
+ let shadow = hostEl.shadowRoot;
99
+ if (!shadow) {
100
+ try {
101
+ shadow = hostEl.attachShadow({ mode: "open" });
102
+ } catch {
103
+ shadow = hostEl.shadowRoot;
104
+ }
105
+ }
106
+ if (!shadow) return hostEl;
107
+
108
+ shadow.replaceChildren();
109
+ const style = document.createElement("style");
110
+ style.textContent = `
111
+ :host {
112
+ display: block;
113
+ width: 100%;
114
+ height: 100%;
115
+ box-sizing: border-box;
116
+ color: var(--text, inherit);
117
+ font-family: inherit;
118
+ font-size: var(--text-base, 13.5px);
119
+ line-height: 1.5;
120
+ }
121
+ *, *::before, *::after {
122
+ box-sizing: inherit;
123
+ }
124
+ ${customCss}
125
+ `;
126
+ shadow.appendChild(style);
127
+ return shadow;
128
+ }
129
+
130
+ /**
131
+ * 带有 Shadow DOM 样式隔离的视图挂载辅助器。
132
+ * @param {HTMLElement} container 挂载目标容器
133
+ * @param {(root: HTMLElement) => void | (() => void)} mountFn 实际挂载函数
134
+ * @param {string} [customCss] 隔离样式
135
+ * @returns {() => void} 清理函数
136
+ */
137
+ export function mountIsolated(container, mountFn, customCss = "") {
138
+ const shadow = attachShadowRoot(container, customCss);
139
+ const inner = document.createElement("div");
140
+ inner.className = "plugin-isolated-body";
141
+ inner.style.cssText = "width:100%;height:100%;display:flex;flex-direction:column;";
142
+ shadow.appendChild(inner);
143
+
144
+ const cleanup = mountFn(inner);
145
+ return () => {
146
+ if (typeof cleanup === "function") {
147
+ try {
148
+ cleanup();
149
+ } catch {}
150
+ }
151
+ inner.replaceChildren();
152
+ shadow.replaceChildren();
153
+ };
154
+ }
155
+
156
+ const DEFAULT_CHUNK_LIMIT = 3800;
157
+ const CODE_FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;
158
+
159
+ /**
160
+ * 计算安全的截断位置,避免割裂 UTF-16 代理对(Surrogate Pair Emoji/特异字符)。
161
+ * @param {string} value
162
+ * @param {number} limit
163
+ * @returns {number}
164
+ */
165
+ export function safeSliceIndex(value, limit) {
166
+ let index = Math.min(limit, value.length);
167
+ if (index <= 0) return 0;
168
+ const before = value.charCodeAt(index - 1);
169
+ const after = value.charCodeAt(index);
170
+ if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) {
171
+ index -= 1;
172
+ }
173
+ return Math.max(1, index);
174
+ }
175
+
176
+ function openingFence(line) {
177
+ const normalized = line.endsWith("\r") ? line.slice(0, -1) : line;
178
+ const match = CODE_FENCE_OPEN.exec(normalized);
179
+ if (!match) return null;
180
+ if (match[2][0] === "`" && match[3].includes("`")) return null;
181
+ return { delimiter: match[2], info: match[3], indent: match[1].length };
182
+ }
183
+
184
+ function closesFence(line, opening) {
185
+ const match = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(line);
186
+ return Boolean(match && match[1][0] === opening.delimiter[0] && match[1].length >= opening.delimiter.length);
187
+ }
188
+
189
+ function splitRawText(text, limit) {
190
+ if (text.length <= limit) return [text];
191
+ const parts = [];
192
+ let remaining = text;
193
+ while (remaining.length > limit) {
194
+ let index = safeSliceIndex(remaining, limit);
195
+ const newline = remaining.lastIndexOf("\n", index - 1);
196
+ if (newline >= 0 && newline >= Math.floor(limit * 0.4)) {
197
+ index = newline + 1;
198
+ }
199
+ parts.push(remaining.slice(0, index));
200
+ remaining = remaining.slice(index);
201
+ }
202
+ if (remaining || parts.length === 0) parts.push(remaining);
203
+ return parts;
204
+ }
205
+
206
+ /**
207
+ * 结构感知 Markdown 分块工具(专为 IM 机器人、通知卡片与受限文本通道设计)。
208
+ * 跨分块边界保护代码围栏(``` 或 ~~~),自动在上一块末尾闭合并在下一块开头重新打开,
209
+ * 确保代码高亮不破损、超长行不断字。
210
+ *
211
+ * @param {string} text 待分块 Markdown 文本
212
+ * @param {number} [limit=3800] 单块最大字符数(必须 > 20)
213
+ * @returns {string[]} 分块数组
214
+ */
215
+ export function chunkMarkdownText(text, limit = DEFAULT_CHUNK_LIMIT) {
216
+ const raw = String(text ?? "").trim();
217
+ if (!raw) return [];
218
+ const bound = Math.max(50, Number(limit) || DEFAULT_CHUNK_LIMIT);
219
+ if (raw.length <= bound) return [raw];
220
+
221
+ const lines = raw.split("\n");
222
+ const chunks = [];
223
+ let currentLines = [];
224
+ let currentLen = 0;
225
+ let activeFence = null;
226
+
227
+ function flushChunk() {
228
+ if (currentLines.length === 0) return;
229
+ if (activeFence) {
230
+ currentLines.push(activeFence.delimiter);
231
+ chunks.push(currentLines.join("\n"));
232
+ currentLines = [`${activeFence.delimiter}${activeFence.info}`];
233
+ currentLen = currentLines[0].length + 1;
234
+ } else {
235
+ chunks.push(currentLines.join("\n"));
236
+ currentLines = [];
237
+ currentLen = 0;
238
+ }
239
+ }
240
+
241
+ for (let i = 0; i < lines.length; i++) {
242
+ const line = lines[i];
243
+ const lineLen = line.length + 1;
244
+
245
+ if (activeFence) {
246
+ if (closesFence(line, activeFence)) {
247
+ activeFence = null;
248
+ }
249
+ } else {
250
+ const open = openingFence(line);
251
+ if (open) {
252
+ activeFence = open;
253
+ }
254
+ }
255
+
256
+ if (currentLen + lineLen > bound) {
257
+ if (currentLines.length === 0) {
258
+ const parts = splitRawText(line, bound - (activeFence ? 20 : 0));
259
+ for (let p = 0; p < parts.length; p++) {
260
+ currentLines.push(parts[p]);
261
+ if (p < parts.length - 1) flushChunk();
262
+ }
263
+ currentLen = currentLines.join("\n").length + 1;
264
+ continue;
265
+ }
266
+
267
+ flushChunk();
268
+ }
269
+
270
+ currentLines.push(line);
271
+ currentLen += lineLen;
272
+ }
273
+
274
+ if (currentLines.length > 0) {
275
+ chunks.push(currentLines.join("\n"));
276
+ }
277
+
278
+ return chunks;
279
+ }