pi-web-ui 0.99.0 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +53 -2
  2. package/README.md +2 -1
  3. package/README.zh-CN.md +2 -1
  4. package/bin/pi-web-ui.mjs +174 -36
  5. package/dist/server/agent-service.js +1160 -149
  6. package/dist/server/approval-rules.js +95 -23
  7. package/dist/server/attachments.js +55 -0
  8. package/dist/server/bg-servers.js +82 -2
  9. package/dist/server/claim-files-tool.js +4 -4
  10. package/dist/server/client-state.js +41 -0
  11. package/dist/server/compact-context-tool.js +10 -9
  12. package/dist/server/conversation-read-tool.js +7 -8
  13. package/dist/server/conversation-touches.js +19 -0
  14. package/dist/server/delegate-task.js +10 -14
  15. package/dist/server/dsh/dsh-agent-service.js +116 -12
  16. package/dist/server/edit-soft-tool.js +10 -12
  17. package/dist/server/eval-tool.js +4 -5
  18. package/dist/server/goal-evidence.js +173 -0
  19. package/dist/server/goal-service.js +48 -8
  20. package/dist/server/hashline-engine.js +198 -31
  21. package/dist/server/index.js +55 -9
  22. package/dist/server/load-tools-tool.js +100 -0
  23. package/dist/server/lsp-tool.js +10 -16
  24. package/dist/server/marker-service.js +53 -12
  25. package/dist/server/markers/builtins/action.js +108 -0
  26. package/dist/server/markers/index.js +4 -1
  27. package/dist/server/patch-remote-catalog.js +28 -10
  28. package/dist/server/patch-tool.js +9 -8
  29. package/dist/server/plan-mode.js +7 -6
  30. package/dist/server/plugin-api-catalog.js +10 -3
  31. package/dist/server/plugin-conversation-view.js +47 -0
  32. package/dist/server/plugins.js +113 -26
  33. package/dist/server/present-files-tool.js +10 -11
  34. package/dist/server/preset-fields.js +693 -0
  35. package/dist/server/preset-share.js +1178 -0
  36. package/dist/server/prompt-composer.js +23 -9
  37. package/dist/server/protocol-version.js +1 -1
  38. package/dist/server/read-tool.js +8 -10
  39. package/dist/server/resolve-global-sdk.js +80 -18
  40. package/dist/server/schedule-agent-tool.js +147 -146
  41. package/dist/server/sdk-origin.js +125 -37
  42. package/dist/server/settings-service.js +103 -84
  43. package/dist/server/skill-tool.js +3 -4
  44. package/dist/server/subagents.js +15 -22
  45. package/dist/server/terminals.js +16 -33
  46. package/dist/server/tool-approval.js +3 -1
  47. package/dist/server/tool-manager.js +63 -27
  48. package/dist/server/tool-prompt-overrides.js +158 -0
  49. package/dist/server/tool-prompts.js +42 -0
  50. package/dist/server/tool-signature.js +104 -0
  51. package/dist/server/workspace-snapshot.js +42 -11
  52. package/package.json +5 -3
  53. package/plugin-sdk/README.md +8 -4
  54. package/plugin-sdk/import-check.mjs +210 -0
  55. package/plugin-sdk/index.d.ts +4 -1
  56. package/plugin-sdk/index.mjs +1 -0
  57. package/plugins/catalog.json +33 -2
  58. package/themes/zhupi-dark.css +1 -1
  59. package/themes/zhupi.css +1 -1
  60. package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-C3I1Mc-C.js} +2 -2
  61. package/web/dist/assets/index-B-E2EM_0.css +1 -0
  62. package/web/dist/assets/index-BYumAaGi.js +379 -0
  63. package/web/dist/index.html +2 -2
  64. package/web/dist/sw.js +1 -1
  65. package/web/dist/assets/index-BdMaGCcs.css +0 -1
  66. package/web/dist/assets/index-ByCBN4Kt.js +0 -368
@@ -10,8 +10,8 @@
10
10
  * 4. 寄存器支持(CUT / PUT @reg):支持在跨文件或同文件内部移动代码段。
11
11
  */
12
12
  import { createHash } from "node:crypto";
13
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
14
- import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
13
+ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
15
15
  export const HL_HASH_LENGTH = 4;
16
16
  /** 归一化文本换行符与尾随空白(确保哈希跨平台一致) */
17
17
  export function normalizeLineEndings(text) {
@@ -376,15 +376,121 @@ export function tryRecoverEdits(baseText, currentText, hunks, filePath) {
376
376
  });
377
377
  }
378
378
  else {
379
- return {
380
- success: false,
381
- reason: `目标文件在第 ${firstDiff} 行附近发生外部修改,补丁锚点(第 ${start} 行)产生冲突`,
382
- };
379
+ // 平移后上下文仍不匹配:±6 行窗口内做 trim 归一化重锚定
380
+ const baseCtx = baseLines
381
+ .slice(Math.max(0, start - 2), Math.min(baseLines.length, end + 1))
382
+ .join("\n")
383
+ .trim();
384
+ let matched = null;
385
+ if (baseCtx) {
386
+ for (let w = 1; w <= 6 && matched === null; w++) {
387
+ for (const off of [w, -w]) {
388
+ const s2 = Math.max(1, start + delta + off);
389
+ const e2 = Math.max(1, end + delta + off);
390
+ const curCtx = curLines
391
+ .slice(Math.max(0, s2 - 2), Math.min(curLines.length, e2 + 1))
392
+ .join("\n")
393
+ .trim();
394
+ if (curCtx && curCtx === baseCtx) {
395
+ matched = off;
396
+ break;
397
+ }
398
+ }
399
+ }
400
+ }
401
+ if (matched !== null) {
402
+ remapped.push({
403
+ ...hunk,
404
+ lineStart: Math.max(1, start + delta + matched),
405
+ lineEnd: hunk.lineEnd !== undefined ? Math.max(1, end + delta + matched) : undefined,
406
+ });
407
+ }
408
+ else {
409
+ return {
410
+ success: false,
411
+ reason: `目标文件在第 ${firstDiff} 行附近发生外部修改,补丁锚点(第 ${start} 行)产生冲突`,
412
+ };
413
+ }
383
414
  }
384
415
  }
385
416
  }
386
417
  return { success: true, remappedHunks: remapped };
387
418
  }
419
+ /**
420
+ * 错误消息附带当前内容摘录(行号: 内容,锚点附近 ±2 行),
421
+ * 让模型基于现内容一次重试到位,而不是被迫整文件重读。
422
+ */
423
+ function patchFileExcerpt(lines, aroundLine, filePath, hash) {
424
+ let n = lines.length;
425
+ if (n > 0 && lines[n - 1] === "")
426
+ n--; // 尾随换行 split 出的幻影空行不计入行数(与引擎 lines 口径一致)
427
+ const head = `当前共 ${n} 行,最新锚点:[${filePath}#${hash}]`;
428
+ if (n === 0)
429
+ return `${head}(空文件)`;
430
+ const center = Math.max(1, Math.min(n, aroundLine ?? n));
431
+ const lo = Math.max(1, center - 2);
432
+ const hi = Math.min(n, center + 2);
433
+ const rows = [];
434
+ for (let i = lo; i <= hi; i++)
435
+ rows.push(`${i}: ${String(lines[i - 1]).slice(0, 160)}`);
436
+ return `${head};第 ${lo}-${hi} 行现内容:\n${rows.join("\n")}`;
437
+ }
438
+ /** 同名文件解析时跳过的高风险/重目录 */
439
+ const SAME_BASENAME_SKIP_DIRS = new Set([
440
+ "node_modules",
441
+ ".git",
442
+ "__pycache__",
443
+ ".venv",
444
+ "venv",
445
+ "dist",
446
+ "build",
447
+ ".pytest_cache",
448
+ ".mypy_cache",
449
+ "target",
450
+ ".next",
451
+ ]);
452
+ /**
453
+ * 带锚头但文件读不到时:工作区内找同名唯一文件(典型场景:模型写错目录层级)。
454
+ * 只接受唯一命中;歧义/无命中交回原错误路径并附候选清单。
455
+ */
456
+ function findUniqueSameBasename(cwd, targetPath) {
457
+ const base = basename(targetPath);
458
+ if (!base || base.startsWith("."))
459
+ return { status: "none", candidates: [] };
460
+ const same = [];
461
+ const ci = [];
462
+ const walk = (dir, depth) => {
463
+ if (depth > 6 || same.length + ci.length > 16)
464
+ return;
465
+ let entries;
466
+ try {
467
+ entries = readdirSync(dir, { withFileTypes: true });
468
+ }
469
+ catch {
470
+ return;
471
+ }
472
+ for (const e of entries) {
473
+ if (e.name.startsWith("."))
474
+ continue;
475
+ const full = join(dir, e.name);
476
+ if (e.isDirectory()) {
477
+ if (!SAME_BASENAME_SKIP_DIRS.has(e.name))
478
+ walk(full, depth + 1);
479
+ continue;
480
+ }
481
+ if (e.name === base)
482
+ same.push(full);
483
+ else if (e.name.toLowerCase() === base.toLowerCase())
484
+ ci.push(full);
485
+ }
486
+ };
487
+ walk(cwd, 0);
488
+ if (same.length === 1)
489
+ return { status: "resolved", path: relative(cwd, same[0]) || same[0], candidates: same };
490
+ if (same.length === 0 && ci.length === 1)
491
+ return { status: "resolved", path: relative(cwd, ci[0]) || ci[0], candidates: ci };
492
+ return { status: same.length + ci.length > 1 ? "ambiguous" : "none", candidates: [...same, ...ci].slice(0, 8) };
493
+ }
388
494
  /**
389
495
  * 应用 Hashline 补丁
390
496
  * 支持传入虚拟或物理文件读写器(便于单元测试或沙箱执行)
@@ -420,8 +526,12 @@ export function applyHashlinePatch(patchText, options = {}) {
420
526
  return { ok: false, summary: "未能从输入中解析出有效的 [path#TAG] 补丁段", results: [] };
421
527
  }
422
528
  const clipboard = new Map(); // 命名剪切板寄存器
423
- const plannedWrites = new Map(); // path -> 新内容
529
+ const plannedWrites = new Map(); // foldKey(absPath) -> 新内容
424
530
  const plannedDeletes = new Set();
531
+ // Windows 文件系统大小写不敏感:键做大小写折叠,避免 [a]/[A] 变体绕过路径归一化造成双写覆盖;
532
+ // plannedPaths 记录首次见到的原始路径(保持相对/绝对形态)供落盘与自定义读写器使用。
533
+ const foldKey = (abs) => (process.platform === "win32" ? abs.toLowerCase() : abs);
534
+ const plannedPaths = new Map();
425
535
  const results = [];
426
536
  // ===== 阶段 1: 预检所有文件并计算目标内容 =====
427
537
  for (const sec of sections) {
@@ -439,15 +549,45 @@ export function applyHashlinePatch(patchText, options = {}) {
439
549
  error: `Path traversal denied: ${sec.filePath}`,
440
550
  };
441
551
  }
442
- // 同一次 patch 内对同文件的后续段落,优先使用前面段落生成的新内容
443
- const currentText = plannedWrites.get(sec.filePath) ?? read(sec.filePath);
552
+ // 同一次 patch 内对同文件的后续段落,优先使用前面段落生成的新内容。
553
+ // plannedWrites/plannedDeletes 一律按折叠绝对路径做键:[a] 与 [./a]、大小写变体视为同一文件。
554
+ let currentText = plannedWrites.get(foldKey(resolve(cwd, sec.filePath))) ?? read(sec.filePath);
555
+ let fuzzyNote = "";
556
+ if (currentText === null && sec.expectedHash) {
557
+ // 带 #TAG 却读不到:先尝试工作区内同名唯一文件解析(典型:模型写错目录层级)
558
+ const cand = findUniqueSameBasename(cwd, sec.filePath);
559
+ if (cand.status === "resolved" && cand.path) {
560
+ fuzzyNote = `(路径 ${sec.filePath} 不存在,已解析为同名文件 ${cand.path})`;
561
+ sec.filePath = cand.path;
562
+ currentText = plannedWrites.get(foldKey(resolve(cwd, sec.filePath))) ?? read(cand.path);
563
+ }
564
+ }
565
+ const isNewFile = currentText === null;
444
566
  if (currentText === null) {
445
- return {
446
- ok: false,
447
- summary: `文件不存在:${sec.filePath}(hashline 仅支持修改已存在的文件,新建文件请使用 write 工具)`,
448
- results: [],
449
- error: `File not found: ${sec.filePath}`,
450
- };
567
+ // [path] 段头(无 #TAG)+ 内容 hunk = 创建新文件
568
+ if (sec.hunks.some((h) => h.kind === "remove_file" || h.kind === "move_file")) {
569
+ return {
570
+ ok: false,
571
+ summary: `文件不存在,无法 REM/MV:${sec.filePath}(新建文件请用 [path] 段头 + PUT <1: 提供内容)`,
572
+ results: [],
573
+ error: `File not found: ${sec.filePath}`,
574
+ };
575
+ }
576
+ if (sec.expectedHash) {
577
+ // 附工作区相近文件候选(相对路径),有候选时不建议新建遮蔽
578
+ const cand = findUniqueSameBasename(cwd, sec.filePath);
579
+ const candRel = cand.candidates.map((c) => relative(cwd, c) || c);
580
+ const advice = candRel.length
581
+ ? `工作区内相近文件:${candRel.join("、")}。请核对目录层级后用上述路径重试,勿新建同名文件遮蔽。`
582
+ : `新建文件时段头不能带 #TAG(无法对不存在的文件校验哈希),请写 [${sec.filePath}] 并用 PUT <1: 提供内容。`;
583
+ return {
584
+ ok: false,
585
+ summary: `文件不存在:${sec.filePath}。${advice}`,
586
+ results: [],
587
+ error: `Tagged header on nonexistent file: ${sec.filePath}`,
588
+ };
589
+ }
590
+ currentText = ""; // 新建:从空文件起步
451
591
  }
452
592
  const isCrlf = currentText.includes("\r\n");
453
593
  const eol = isCrlf ? "\r\n" : "\n";
@@ -465,18 +605,24 @@ export function applyHashlinePatch(patchText, options = {}) {
465
605
  isRecovered = true;
466
606
  }
467
607
  else {
608
+ // 附现内容摘录,模型可基于现内容一次重锚定
609
+ const excerptLines = normalizeLineEndings(currentText).split("\n");
610
+ const firstHunk = sec.hunks.find((h) => h.kind !== "remove_file" && h.kind !== "move_file");
468
611
  return {
469
612
  ok: false,
470
- summary: `文件内容已发生变动,且三方合流失败:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash};${recovery.reason ?? "冲突"})\n请重新使用 read 工具查看该文件最新内容后再提交 patch。`,
613
+ summary: `文件内容已发生变动,且三方合流失败:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash};${recovery.reason ?? "冲突"})\n${patchFileExcerpt(excerptLines, firstHunk?.lineStart, sec.filePath, liveHash)}\n请基于上述现内容修正行号后重提交,或重新使用 read 工具查看该文件。`,
471
614
  results: [],
472
615
  error: `Hash mismatch and recovery failed on ${sec.filePath}`,
473
616
  };
474
617
  }
475
618
  }
476
619
  else {
620
+ // 附现内容摘录,模型可基于现内容一次重锚定
621
+ const excerptLines = normalizeLineEndings(currentText).split("\n");
622
+ const firstHunk = sec.hunks.find((h) => h.kind !== "remove_file" && h.kind !== "move_file");
477
623
  return {
478
624
  ok: false,
479
- summary: `文件内容与锚点不一致:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash})\n请重新使用 read 工具读取该文件以获取最新行号与 #TAG。`,
625
+ summary: `文件内容与锚点不一致:${sec.filePath}(预期哈希 #${sec.expectedHash},实际哈希 #${liveHash})${fuzzyNote}\n${patchFileExcerpt(excerptLines, firstHunk?.lineStart, sec.filePath, liveHash)}\n请基于上述现内容修正行号后重提交,或重新使用 read 工具读取该文件。`,
480
626
  results: [],
481
627
  error: `Hash mismatch on ${sec.filePath} (#${sec.expectedHash} vs #${liveHash})`,
482
628
  };
@@ -487,6 +633,9 @@ export function applyHashlinePatch(patchText, options = {}) {
487
633
  if (hasTrailingNewline && lines.length > 0 && lines[lines.length - 1] === "") {
488
634
  lines.pop();
489
635
  }
636
+ if (isNewFile) {
637
+ lines = []; // 新文件按 0 行处理,PUT <1: / PUT >$: 直接写入内容
638
+ }
490
639
  let isDeleted = false;
491
640
  let moveDest = undefined;
492
641
  // 倒序/顺序处理 hunks。为了保证行号不受前面 hunk 影响,从后往前执行行号替换;
@@ -536,10 +685,12 @@ export function applyHashlinePatch(patchText, options = {}) {
536
685
  }
537
686
  }
538
687
  if (isDeleted) {
539
- plannedDeletes.add(sec.filePath);
688
+ plannedDeletes.add(foldKey(absFilePath));
689
+ plannedPaths.set(foldKey(absFilePath), sec.filePath);
540
690
  results.push({
541
691
  filePath: sec.filePath,
542
692
  op: "deleted",
693
+ note: fuzzyNote || undefined,
543
694
  oldHash: liveHash,
544
695
  linesChanged: lines.length,
545
696
  });
@@ -551,9 +702,10 @@ export function applyHashlinePatch(patchText, options = {}) {
551
702
  continue;
552
703
  if (h.lineStart !== -1 && typeof h.lineStart === "number") {
553
704
  if (h.lineStart < 1 || h.lineStart > Math.max(1, lines.length)) {
705
+ // 附文件尾部摘录,模型可自行改用 PUT >$ 或修正行号
554
706
  return {
555
707
  ok: false,
556
- summary: `行号越界:${sec.filePath} 第 ${h.lineStart} 行(文件总共只有 ${lines.length} 行)。请重新使用 read 工具核验行号。`,
708
+ summary: `行号越界:${sec.filePath} 第 ${h.lineStart} 行(文件总共只有 ${lines.length} 行)。${patchFileExcerpt(lines, lines.length, sec.filePath, liveHash)}`,
557
709
  results: [],
558
710
  error: `Line out of bounds: line ${h.lineStart} in ${sec.filePath} (${lines.length} lines total)`,
559
711
  };
@@ -561,7 +713,7 @@ export function applyHashlinePatch(patchText, options = {}) {
561
713
  if (h.lineEnd !== undefined && h.lineEnd > Math.max(1, lines.length)) {
562
714
  return {
563
715
  ok: false,
564
- summary: `行号越界:${sec.filePath} 结束行 ${h.lineEnd} 超过文件总行数(总共 ${lines.length} 行)。`,
716
+ summary: `行号越界:${sec.filePath} 结束行 ${h.lineEnd} 超过文件总行数(总共 ${lines.length} 行)。${patchFileExcerpt(lines, h.lineStart, sec.filePath, liveHash)}`,
565
717
  results: [],
566
718
  error: `Line out of bounds: end line ${h.lineEnd} in ${sec.filePath} (${lines.length} lines total)`,
567
719
  };
@@ -650,13 +802,21 @@ export function applyHashlinePatch(patchText, options = {}) {
650
802
  linesChangedCount += Math.max(count, contentToInsert.length);
651
803
  }
652
804
  }
653
- const newContent = lines.join(eol) + (hasTrailingNewline ? eol : "");
805
+ const newContent = isNewFile
806
+ ? lines.length > 0
807
+ ? lines.join(eol) + eol
808
+ : ""
809
+ : lines.join(eol) + (hasTrailingNewline ? eol : "");
654
810
  if (moveDest) {
655
- plannedDeletes.add(sec.filePath);
656
- plannedWrites.set(moveDest, newContent);
811
+ const moveKey = foldKey(resolve(cwd, moveDest));
812
+ plannedDeletes.add(foldKey(absFilePath));
813
+ plannedPaths.set(foldKey(absFilePath), sec.filePath);
814
+ plannedWrites.set(moveKey, newContent);
815
+ plannedPaths.set(moveKey, moveDest);
657
816
  results.push({
658
817
  filePath: sec.filePath,
659
818
  op: "moved",
819
+ note: fuzzyNote || undefined,
660
820
  oldHash: liveHash,
661
821
  newHash: computeFileHash(newContent),
662
822
  linesChanged: linesChangedCount,
@@ -665,10 +825,14 @@ export function applyHashlinePatch(patchText, options = {}) {
665
825
  });
666
826
  }
667
827
  else {
668
- plannedWrites.set(sec.filePath, newContent);
828
+ const updateKey = foldKey(absFilePath);
829
+ plannedWrites.set(updateKey, newContent);
830
+ plannedPaths.set(updateKey, sec.filePath);
669
831
  results.push({
670
832
  filePath: sec.filePath,
671
833
  op: "updated",
834
+ created: isNewFile,
835
+ note: fuzzyNote || undefined,
672
836
  oldHash: liveHash,
673
837
  newHash: computeFileHash(newContent),
674
838
  linesChanged: linesChangedCount,
@@ -678,22 +842,25 @@ export function applyHashlinePatch(patchText, options = {}) {
678
842
  }
679
843
  // ===== 阶段 2: 全部校验通过,统一落盘 =====
680
844
  // 先执行所有写入,确保新文件与移动目标成功落盘,避免先删后写异常时永久丢失源文件
681
- for (const [p, content] of plannedWrites.entries()) {
845
+ for (const [key, content] of plannedWrites.entries()) {
846
+ const p = plannedPaths.get(key) ?? key;
682
847
  write(p, content);
683
848
  // 记住新快照(统一采用绝对路径隔离多工作区)
684
849
  store.record(resolve(cwd, p), content);
685
850
  }
686
- for (const p of plannedDeletes) {
687
- if (!plannedWrites.has(p)) {
688
- remove(p);
851
+ for (const key of plannedDeletes) {
852
+ if (!plannedWrites.has(key)) {
853
+ remove(plannedPaths.get(key) ?? key);
689
854
  }
690
855
  }
691
856
  const summaryParts = results.map((r) => {
692
857
  if (r.op === "deleted")
693
- return `删除 ${r.filePath}`;
858
+ return `删除 ${r.filePath}${r.note ?? ""}`;
859
+ if (r.created)
860
+ return `新建 ${r.filePath}(${r.linesChanged} 行,新哈希 #${r.newHash})${r.note ?? ""}`;
694
861
  if (r.op === "moved")
695
- return `移动 ${r.filePath} -> ${r.newPath}(新哈希 #${r.newHash})`;
696
- return `修改 ${r.filePath}(${r.linesChanged} 行变动,新哈希 #${r.newHash}${r.recovered ? ",三方自愈" : ""})`;
862
+ return `移动 ${r.filePath} -> ${r.newPath}(新哈希 #${r.newHash})${r.note ?? ""}`;
863
+ return `修改 ${r.filePath}(${r.linesChanged} 行变动,新哈希 #${r.newHash}${r.recovered ? ",三方自愈" : ""})${r.note ?? ""}`;
697
864
  });
698
865
  return {
699
866
  ok: true,
@@ -1373,8 +1373,10 @@ service.onRunEvent = (ev) => pluginMgr.emitRunEvent(ev);
1373
1373
  // 插件扩展点:对话切换通知(轨迹视图切会话后即重拉;dsh 引擎暂无)。
1374
1374
  service.onConversationChanged = () => pluginMgr.emitConversationChanged();
1375
1375
  // 插件扩展点:当前打开对话的快照(轨迹视图直接显示打开对话的时间线;
1376
- // dsh 引擎无此方法时回退 null,插件显示空态)。
1377
- pluginMgr.conversationProvider = () => service.readConversationForPlugins?.() ?? null;
1376
+ // dsh 引擎无此方法时回退 null,插件显示空态)。#542:透传 {clientId} 选本标签页的对话。
1377
+ pluginMgr.conversationProvider = (opts) => service.readConversationForPlugins?.(opts) ?? null;
1378
+ // 插件扩展点:模型切换成功事件(#542;dsh 引擎无此钩子 = 不发事件)。
1379
+ service.onClientModelChanged = (snap) => pluginMgr.emitClientModelChanged(snap);
1378
1380
  // 插件扩展点:无头调用 agent(微信通道等经 host.chat 投递外部消息,无浏览器也能跑)。
1379
1381
  pluginMgr.chatProvider = (pluginId, req) => service.chatFromPlugin?.(pluginId, req) ?? Promise.reject(new Error("当前引擎不支持无头调用(仅标准 pi 引擎)"));
1380
1382
  // 插件扩展点:插件注册的 AI 工具(registerAgentTool)+ MCP 桥工具 → 会话创建时
@@ -1391,7 +1393,7 @@ service.pluginCommandsProvider = () => pluginMgr.listCommands();
1391
1393
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1392
1394
  service.pluginBgTasksProvider = () => pluginMgr.bgTasks();
1393
1395
  service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
1394
- // 定时任务 Agent 工具的数据源(schedule_task/list/cancel):标准 pi 引擎的
1396
+ // 定时任务 Agent 工具的数据源(schedule 单 action:create/list/cancel):标准 pi 引擎的
1395
1397
  // AgentService 才有 schedulerStore 字段,DSH service 没有 —— 有才设。
1396
1398
  if ("schedulerStore" in service) {
1397
1399
  service.schedulerStore = scheduler;
@@ -1631,13 +1633,15 @@ wss.on("connection", (ws) => {
1631
1633
  if ((msg.type === "snapshot" || msg.type === "snapshot_delta") &&
1632
1634
  lastSnapshotBytes > 0 &&
1633
1635
  ws.bufferedAmount > Math.max(SNAPSHOT_BACKPRESSURE_MIN_BYTES, SNAPSHOT_BACKPRESSURE_FACTOR * lastSnapshotBytes)) {
1636
+ const wasFull = msg.type === "snapshot";
1634
1637
  // 真正的慢客户端:丢弃是安全的,但不能「丢完就没了」——安排一次延迟
1635
1638
  // 重发,等缓冲排空后快照最终必达(否则若此后再无事件,客户端将永久
1636
- // 停留在旧快照)。重发仍走 flushSnapshot:缓冲未排空则再次顺延。
1639
+ // 停留在旧快照)。重发仍走 flushSnapshot:缓冲未排空则再次顺延;
1640
+ // 若被丢弃的是全量快照(snapshot),重发必须强制 forceFull 保证客户端能拿到完整基线。
1637
1641
  if (!snapshotRetryTimer) {
1638
1642
  snapshotRetryTimer = setTimeout(() => {
1639
1643
  snapshotRetryTimer = null;
1640
- service.get(clientId ?? "")?.flushSnapshot();
1644
+ service.get(clientId ?? "")?.flushSnapshot(wasFull);
1641
1645
  }, SNAPSHOT_RETRY_MS);
1642
1646
  }
1643
1647
  return;
@@ -1728,6 +1732,12 @@ wss.on("connection", (ws) => {
1728
1732
  case "list_bg_servers":
1729
1733
  void cs.listBgServers();
1730
1734
  break;
1735
+ case "set_bg_keep":
1736
+ cs.setBackgroundKeep(msg.port, msg.keep);
1737
+ break;
1738
+ case "clean_bg_leftovers":
1739
+ void cs.cleanBackgroundLeftovers(msg.minutes);
1740
+ break;
1731
1741
  case "new_chat":
1732
1742
  void cs.newChat(msg.preset, msg.ephemeral);
1733
1743
  break;
@@ -1759,6 +1769,15 @@ wss.on("connection", (ws) => {
1759
1769
  send({ type: "tool_info", name: msg.name, found: false, unsupported: true });
1760
1770
  }
1761
1771
  break;
1772
+ case "get_tool_prompt":
1773
+ // 设置页逐工具文案编辑器:取「出厂默认 + 当前覆盖」。
1774
+ if (typeof cs.getToolPrompt === "function") {
1775
+ void cs.getToolPrompt(msg.name);
1776
+ }
1777
+ else {
1778
+ send({ type: "tool_prompt", name: msg.name, found: false, unsupported: true });
1779
+ }
1780
+ break;
1762
1781
  case "get_compacted_messages":
1763
1782
  void cs.getCompactedMessages?.(msg.compactionMessageId, msg.conversationId);
1764
1783
  break;
@@ -2122,6 +2141,7 @@ wss.on("connection", (ws) => {
2122
2141
  customSystemPrompt: msg.customSystemPrompt,
2123
2142
  promptTemplate: msg.promptTemplate,
2124
2143
  promptOverrides: msg.promptOverrides,
2144
+ toolPromptOverrides: msg.toolPromptOverrides,
2125
2145
  disabledSkills: msg.disabledSkills,
2126
2146
  disabledExtensions: msg.disabledExtensions,
2127
2147
  disabledAgentTools: msg.disabledAgentTools,
@@ -2133,6 +2153,8 @@ wss.on("connection", (ws) => {
2133
2153
  terminalBashMaxForegroundMs: msg.terminalBashMaxForegroundMs,
2134
2154
  toolWatchdogTimeoutMs: msg.toolWatchdogTimeoutMs,
2135
2155
  readDirEnabled: msg.readDirEnabled,
2156
+ bgAutoCleanupMin: msg.bgAutoCleanupMin,
2157
+ toolLazyLoading: msg.toolLazyLoading,
2136
2158
  toolApprovalEnabled: msg.toolApprovalEnabled,
2137
2159
  editSoftEnabled: msg.editSoftEnabled,
2138
2160
  questionnaireEnabled: msg.questionnaireEnabled,
@@ -2555,6 +2577,22 @@ wss.on("connection", (ws) => {
2555
2577
  case "save_preset":
2556
2578
  void cs.savePreset(msg.name);
2557
2579
  break;
2580
+ // -- 预设分享(server/preset-share.ts,docs/preset-sharing.md)------
2581
+ case "preset_export":
2582
+ void cs.exportPreset(msg);
2583
+ break;
2584
+ case "preset_import":
2585
+ void cs.importPreset(msg);
2586
+ break;
2587
+ case "preset_import_url":
2588
+ void cs.importPresetFromUrl(msg);
2589
+ break;
2590
+ case "preset_catalog":
2591
+ void cs.pushPresetCatalog(msg);
2592
+ break;
2593
+ case "preset_share":
2594
+ void cs.sharePreset(msg);
2595
+ break;
2558
2596
  case "save_subagent_template":
2559
2597
  void cs.saveSubagentTemplate(msg.template);
2560
2598
  break;
@@ -2711,8 +2749,10 @@ wss.on("connection", (ws) => {
2711
2749
  .attach(cid, send)
2712
2750
  .then((cs) => {
2713
2751
  clearTimeout(slowTimer);
2714
- if (closed)
2752
+ if (closed) {
2753
+ service.detach(cid, send);
2715
2754
  return;
2755
+ }
2716
2756
  // Plugin catalog: re-scan + activate new dirs on every attach so
2717
2757
  // freshly dropped plugins show up without a server restart.
2718
2758
  pluginMgr
@@ -2740,7 +2780,9 @@ wss.on("connection", (ws) => {
2740
2780
  // 插件清单【先于】快照推送:前端渲染历史消息前就拿到 renderer
2741
2781
  // 注册表(plugin-fence.ts),`` ```lang `` 围栏才能立即命中插件;
2742
2782
  // 否则消息先落成普通代码块,清单后到也不会重渲。
2743
- cs.flushSnapshot();
2783
+ // 新连接/新客户端 attach 首次快照必须强制全量(forceFull=true),
2784
+ // 保证新标签页/刷新页能立刻拿到完整的会话基线,绝不因增量 delta 而卡在加载中。
2785
+ cs.flushSnapshot(true);
2744
2786
  // 内置定时任务列表随附推一次(后续变更经 pushSchedulerTasks 广播)。
2745
2787
  try {
2746
2788
  send({ type: "scheduler_tasks", tasks: scheduler.list() });
@@ -2754,8 +2796,8 @@ wss.on("connection", (ws) => {
2754
2796
  if (closed)
2755
2797
  return;
2756
2798
  // ensureLoaded 失败(如磁盘读错)不能卡死快照——前端 30s 无消息
2757
- // 会重连,重连又失败会陷入循环。至少把状态推下去。
2758
- cs.flushSnapshot();
2799
+ // 会重连,重连又失败会陷入循环。至少把状态推下去(同样强制全量)。
2800
+ cs.flushSnapshot(true);
2759
2801
  replayQueued();
2760
2802
  });
2761
2803
  // hello may carry the UI locale — persist it before replaying
@@ -2775,6 +2817,10 @@ wss.on("connection", (ws) => {
2775
2817
  };
2776
2818
  })
2777
2819
  .catch((err) => {
2820
+ clearTimeout(slowTimer);
2821
+ if (closed) {
2822
+ service.detach(cid, send);
2823
+ }
2778
2824
  // Admission refused (quiesce): close the socket so the browser
2779
2825
  // reconnect loop keeps retrying until admission reopens. Do NOT
2780
2826
  // leave a half-alive connection that can only show an error.
@@ -0,0 +1,100 @@
1
+ // ---------------------------------------------------------------------------
2
+ // load-tools-tool.ts — 延迟加载模式下模型拉取工具 schema 的唯一入口。
3
+ // ---------------------------------------------------------------------------
4
+ // 背景:模型每轮都会拿到**全部活跃工具**的名字 + 完整参数 schema,几十个工具加起来
5
+ // 是几万字符的常驻开销(设置页「查看工具 schema」能看到了多少)。延迟加载把工具分成
6
+ // 两层:
7
+ // - 常驻:核心工具(bash/read/edit/write)+ 本工具;
8
+ // - 目录:其余工具只在系统提示词里以「名字 + 一行摘要」出现(见 prompt-composer 的
9
+ // tool catalog 段)。
10
+ // 模型要用某个目录里的工具时先调本工具,那批工具才会被激活 —— SDK 的中途工具变更会
11
+ // 把新增工具以 defer_loading / tool_search 的形式注入(见 agent-session 的
12
+ // `_preparePromptAndToolLoadout`),不占首轮上下文。
13
+ //
14
+ // 与 skills 的 `skill` 工具同构:名录常驻、正文按需。区别只在「正文」是工具 schema。
15
+ //
16
+ // 文案约定:工具 definition(description/promptSnippet/promptGuidelines)纯英文;
17
+ // per-call 返回文本按 lang 走 pick(lang, zh, en, key)。
18
+ // ---------------------------------------------------------------------------
19
+ import { defineTool } from "@earendil-works/pi-coding-agent";
20
+ import { Type } from "typebox";
21
+ import { pick } from "./i18n.js";
22
+ import { LOAD_TOOLS_TOOL_NAME } from "./tool-manager.js";
23
+ /** 单次最多加载多少(防模型一口气把整个目录塞回来)。 */
24
+ export const LOAD_TOOLS_MAX = 20;
25
+ function describe(t) {
26
+ const text = (t.description ?? t.summary ?? "").trim().split("\n")[0] ?? "";
27
+ return text.length > 240 ? `${text.slice(0, 240)}…` : text;
28
+ }
29
+ export function makeLoadToolsTool(host, lang) {
30
+ const getLang = lang ?? (() => "en");
31
+ const text = (t, details = {}) => ({
32
+ content: [{ type: "text", text: t }],
33
+ details,
34
+ });
35
+ return defineTool({
36
+ name: LOAD_TOOLS_TOOL_NAME,
37
+ label: "Load tools",
38
+ description: "Attach the full parameter schema of tools listed in the system prompt's tool catalog. " +
39
+ "Tools whose schema is not loaded are shown there by name + one-line summary; load the ones you need " +
40
+ "BEFORE calling them. Loaded tools stay available for the rest of the conversation.",
41
+ promptSnippet: "load catalog tools you are about to use",
42
+ promptGuidelines: [
43
+ "When a task needs a tool that is only listed in the catalog (name + one-line summary, no schema yet), " +
44
+ "call load_tools with its name first instead of guessing arguments",
45
+ "Load every tool you expect to need in ONE call — each load re-declares the tool set",
46
+ ],
47
+ parameters: Type.Object({
48
+ tools: Type.Array(Type.String(), {
49
+ description: `Tool names to load (1-${LOAD_TOOLS_MAX} per call), exactly as listed in the catalog.`,
50
+ minItems: 1,
51
+ maxItems: LOAD_TOOLS_MAX,
52
+ }),
53
+ }),
54
+ execute: async (_id, params) => {
55
+ const l = getLang();
56
+ const asked = params.tools;
57
+ const names = Array.isArray(asked)
58
+ ? [
59
+ ...new Set(asked
60
+ .filter((n) => typeof n === "string")
61
+ .map((n) => n.trim())
62
+ .filter(Boolean)),
63
+ ]
64
+ : [];
65
+ if (names.length === 0) {
66
+ return text(pick(l, "没有给出要加载的工具名。", "No tool names given.", "loadtools.names.empty"), {
67
+ loaded: [],
68
+ rejected: [],
69
+ });
70
+ }
71
+ const { loaded, rejected } = host.load(names.slice(0, LOAD_TOOLS_MAX));
72
+ const lines = [];
73
+ if (loaded.length > 0) {
74
+ lines.push(pick(l, `已加载 ${loaded.length} 个工具(完整参数 schema 已附上,本对话后续轮次都可用):`, `Loaded ${loaded.length} tool(s) — their full parameter schema is now attached for the rest of this conversation:`, "loadtools.loaded", { count: loaded.length }));
75
+ for (const t of loaded) {
76
+ const d = describe(t);
77
+ lines.push(`- ${t.name}${d ? `: ${d}` : ""}`);
78
+ // guidelines 不进系统提示词(会随加载变化、打坏前缀缓存),在此随回执交付。
79
+ for (const g of t.guidelines ?? []) {
80
+ const rule = g.trim();
81
+ if (rule)
82
+ lines.push(` - ${rule}`);
83
+ }
84
+ }
85
+ }
86
+ for (const r of rejected) {
87
+ lines.push(pick(l, `- ${r.name}: ${r.reason}`, `- ${r.name}: ${r.reason}`, "loadtools.rejected", {
88
+ name: r.name,
89
+ reason: r.reason,
90
+ }));
91
+ }
92
+ if (loaded.length === 0 && rejected.length === 0) {
93
+ const catalog = host.listLoadable();
94
+ lines.push(pick(l, "没有可加载的工具了。当前可加载:", "No tools left to load. Available:", "loadtools.none"));
95
+ lines.push(...catalog.map((t) => `- ${t.name}`));
96
+ }
97
+ return text(lines.join("\n"), { loaded: loaded.map((t) => t.name), rejected });
98
+ },
99
+ });
100
+ }
@@ -856,18 +856,12 @@ export function makeLspTool(options) {
856
856
  const getLang = options.lang ?? (() => "en");
857
857
  return defineTool({
858
858
  name: LSP_TOOL_NAME,
859
- promptSnippet: "IDE-grade semantic analysis (LSP) across the workspace: definition, references, hover, diagnostics, symbols, impact check",
859
+ promptSnippet: "semantic code intelligence (definitions, references, diagnostics, impact)",
860
860
  label: "LSP code intelligence",
861
- description: `IDE-grade semantic analysis (LSP) across the workspace. Actions:
862
- - \`definition\`: definition of the symbol at \`line\`/\`character\` in \`path\` (file, line, snippet).
863
- - \`references\`: all workspace usages of that symbol.
864
- - \`hover\`: type signature and docs for that symbol.
865
- - \`diagnostics\`: compiler/type errors and warnings for \`path\` (whole file).
866
- - \`documentSymbol\`: hierarchical symbol outline with line spans for \`path\`.
867
- - \`read_symbol\`: read the body of \`symbol\` in \`path\` (e.g. "parseConfig").
868
- - \`workspaceSymbol\`: search symbols across the workspace by \`query\`.
869
- - \`cascade\`: impact check for \`path\` — report diagnostics of files referencing it.
870
- Lines are 1-indexed.`,
861
+ description: "IDE-grade semantic analysis (LSP) across the workspace (lines are 1-indexed). `definition` / `references` / `hover`: " +
862
+ "resolve the symbol at `line`/`character` in `path` to its definition, workspace usages, or type and docs. `diagnostics`: " +
863
+ "file errors/warnings. `documentSymbol`: symbol outline. `read_symbol`: body of `symbol` in `path`. `workspaceSymbol`: " +
864
+ "symbols matching `query`. `cascade`: diagnostics of files referencing `path`.",
871
865
  parameters: Type.Object({
872
866
  action: Type.Unsafe({
873
867
  type: "string",
@@ -884,16 +878,16 @@ Lines are 1-indexed.`,
884
878
  description: "The LSP operation to perform.",
885
879
  }),
886
880
  path: Type.Optional(Type.String({
887
- description: "Workspace-relative or absolute path to the target source file (required for all actions except workspaceSymbol).",
881
+ description: "Workspace-relative or absolute file path (required for every action except workspaceSymbol).",
888
882
  })),
889
883
  symbol: Type.Optional(Type.String({
890
- description: "Symbol name to read for 'read_symbol' action (e.g. 'functionName' or 'ClassName.methodName').",
884
+ description: "Symbol for 'read_symbol' (e.g. 'fn' or 'Class.method').",
891
885
  })),
892
886
  query: Type.Optional(Type.String({
893
- description: "Search query for 'workspaceSymbol' action.",
887
+ description: "Search query for 'workspaceSymbol'.",
894
888
  })),
895
889
  line: Type.Optional(Type.Number({
896
- description: "1-indexed line number in the source file.",
890
+ description: "1-indexed line in the file.",
897
891
  })),
898
892
  character: Type.Optional(Type.Number({
899
893
  description: "1-indexed column/character position (defaults to 1).",
@@ -901,7 +895,7 @@ Lines are 1-indexed.`,
901
895
  timeout: Type.Optional(Type.Number({
902
896
  minimum: 1,
903
897
  maximum: 120,
904
- description: "Timeout in seconds (1-120, defaults to 15).",
898
+ description: "Timeout in seconds (default 15).",
905
899
  })),
906
900
  allowInstall: Type.Optional(Type.Boolean({
907
901
  description: "Install the missing language server into ~/.pi-web/lsp-servers (user-space, no sudo). Default false: the tool returns an installHint instead.",