pi-web-ui 0.110.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 (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  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/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -33,6 +33,7 @@ import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "../bg-servers.js";
33
33
  import { ClientStateStore, DEFAULT_RETRY_MAX_ATTEMPTS, normalizeBgCleanupMinutes, normalizePathKey, normalizeToolWatchdogTimeoutMs, settingsPresetToUi, } from "../client-state.js";
34
34
  import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MESSAGES } from "../client-state.js";
35
35
  import { PLAN_MODE_SYSTEM_PROMPT } from "../plan-mode.js";
36
+ import { buildToolsSchemaText } from "../prompt-composer.js";
36
37
  import { FilesService, workspacePath, desktopDirWire } from "../files-service.js";
37
38
  import { SandboxManager, isSameOrSubpath } from "../sandbox-service.js";
38
39
  import { QuiesceRejectedError } from "../agent-service.js";
@@ -92,7 +93,7 @@ const DSH_PRICE_INPUT = 0.14;
92
93
  const DSH_PRICE_CACHE_READ = 0.0028;
93
94
  const DSH_PRICE_OUTPUT = 0.28;
94
95
  /** 会话 root:<dataDir>/dsh-sessions(与 pi 引擎的会话目录隔离)。 */
95
- export function dshSessionRoot(dataDir) {
96
+ function dshSessionRoot(dataDir) {
96
97
  return join(dataDir, "dsh-sessions");
97
98
  }
98
99
  function estimateCost(t) {
@@ -106,7 +107,7 @@ function estimateCost(t) {
106
107
  /** 把插件工具 execute 的原始返回值归一化成模型可读文本。
107
108
  * 兼容:`{content:[{type:"text",text}...],details}` → text 拼接;string → 原串;
108
109
  * 其它对象 → JSON.stringify;null/undefined → 空串。 */
109
- export function normalizeToolResult(result) {
110
+ function normalizeToolResult(result) {
110
111
  if (typeof result === "string")
111
112
  return result;
112
113
  if (result === null || result === undefined)
@@ -163,6 +164,7 @@ const DEFAULT_SETTINGS = {
163
164
  preserveDraftAcrossConversations: false,
164
165
  promptTemplate: "",
165
166
  promptOverrides: {},
167
+ promptDisabled: [],
166
168
  };
167
169
  // ---------------------------------------------------------------------------
168
170
  // DshClientSession — 一个浏览器客户端
@@ -229,6 +231,11 @@ export class DshClientSession {
229
231
  permissionOptions = [];
230
232
  /** clone 出来的预设 id(roster 名录校验用;空 = 未生成,走 legacy)。 */
231
233
  presetCloneIds = [];
234
+ /** 系统提示词缓存(从运行时 inspectPrompt 异步拉取;未就绪时兜底)。 */
235
+ cachedEffectiveSystemPrompt = "";
236
+ cachedToolsSchema = "";
237
+ cachedPromptSections = [];
238
+ cachedPromptSourceDefaults = {};
232
239
  files;
233
240
  bg;
234
241
  sandboxes;
@@ -359,6 +366,7 @@ export class DshClientSession {
359
366
  preserveDraftAcrossConversations: savedSettings.preserveDraftAcrossConversations ?? false,
360
367
  promptTemplate: savedSettings.promptTemplate ?? "",
361
368
  promptOverrides: savedSettings.promptOverrides ?? {},
369
+ promptDisabled: savedSettings.promptDisabled ?? [],
362
370
  defaultAgentPreset: savedSettings.defaultAgentPreset ?? PRESET_DEFAULT_ID,
363
371
  defaultPermissionPreset: savedSettings.defaultPermissionPreset && PERMISSION_OFFERED.includes(savedSettings.defaultPermissionPreset)
364
372
  ? savedSettings.defaultPermissionPreset
@@ -405,6 +413,7 @@ export class DshClientSession {
405
413
  void cs.refreshAgentPresets();
406
414
  void cs.refreshPermissionOptions().catch(() => { });
407
415
  void cs.refreshActivePermission().catch(() => { });
416
+ void cs.refreshPromptInfo().catch(() => { });
408
417
  };
409
418
  // P0-1 watchdog:意外退出(非 kill/close 主动触发)→ 限频自动重启,保持可用。
410
419
  cs.runtime.onExit = (code, signal, intentional) => {
@@ -415,11 +424,19 @@ export class DshClientSession {
415
424
  // P0-5 启动重试:1s/3s/9s 指数退避,最终失败才发 notice。
416
425
  void cs.startWithRetry().catch((err) => {
417
426
  console.error(`[dsh] runtime.start 失败 (client=${clientId}): ${err.message}`);
427
+ const errMsg = err.message || "";
428
+ const isDepOrRuntimeIssue = /找不到 DSH 运行时树|版本族不匹配|version mismatch|dsh-base|typert|codec|launcher|spawn|node_modules|not found|exit.*code/i.test(errMsg);
429
+ const hintZh = isDepOrRuntimeIssue
430
+ ? "请检查 @deepseek-ai/dsh 依赖安装与版本匹配(详见 docs/dsh-engine.md)。"
431
+ : "请检查 DeepSeek API key(~/.pi/agent/auth.json)与 dsh 依赖安装。";
432
+ const hintEn = isDepOrRuntimeIssue
433
+ ? "Check @deepseek-ai/dsh installation and version compatibility (see docs/dsh-engine.md)."
434
+ : "Check the DeepSeek API key (~/.pi/agent/auth.json) and dsh dependencies.";
418
435
  cs.pendingNotices.push({
419
436
  type: "notice",
420
437
  level: "error",
421
- text: `DSH 运行时启动失败:${err.message}。请检查 DeepSeek API key(~/.pi/agent/auth.json)与 dsh 依赖安装。`,
422
- textEn: `DSH runtime failed to start: ${err.message}. Check the DeepSeek API key (~/.pi/agent/auth.json) and dsh dependencies.`,
438
+ text: `DSH 运行时启动失败:${errMsg}。${hintZh}`,
439
+ textEn: `DSH runtime failed to start: ${errMsg}. ${hintEn}`,
423
440
  });
424
441
  });
425
442
  // P0-3 convs 内存回收定时器(unref:不阻止进程退出)。
@@ -472,11 +489,19 @@ export class DshClientSession {
472
489
  this.runtimeRestart.count += 1;
473
490
  if (this.runtimeRestart.count > DshClientSession.RUNTIME_MAX_RESTARTS) {
474
491
  console.error(`[dsh] runtime 反复崩溃 (code=${code} signal=${signal}),停止自动重启`);
492
+ const tail = this.runtime.getStderrTail();
493
+ const isDepOrRuntimeIssue = /找不到 DSH 运行时树|版本族不匹配|version mismatch|dsh-base|typert|codec/i.test(tail);
494
+ const hintZh = isDepOrRuntimeIssue
495
+ ? "DSH 运行时反复崩溃,已停止自动重启。请检查 dsh 运行时依赖安装与版本匹配(详见 docs/dsh-engine.md)。"
496
+ : "DSH 运行时反复崩溃,已停止自动重启。请检查 DeepSeek API key 与 dsh 依赖安装。";
497
+ const hintEn = isDepOrRuntimeIssue
498
+ ? "DSH runtime keeps crashing; auto-restart stopped. Check dsh runtime dependencies and version compatibility (see docs/dsh-engine.md)."
499
+ : "DSH runtime keeps crashing; auto-restart stopped. Check the DeepSeek API key and dsh dependencies.";
475
500
  this.emit({
476
501
  type: "notice",
477
502
  level: "error",
478
- text: "DSH 运行时反复崩溃,已停止自动重启。请检查 DeepSeek API key 与 dsh 依赖安装。",
479
- textEn: "DSH runtime keeps crashing; auto-restart stopped. Check the DeepSeek API key and dsh dependencies.",
503
+ text: hintZh,
504
+ textEn: hintEn,
480
505
  });
481
506
  this.flushSnapshot();
482
507
  return;
@@ -531,17 +556,23 @@ export class DshClientSession {
531
556
  const cutoff = Date.now() - DshClientSession.SESSION_RETENTION_MS;
532
557
  try {
533
558
  const { readdirSync, rmSync } = await import("node:fs");
534
- const dirLastModified = (dir) => {
559
+ const dirLastModified = (dir, cutoffMs) => {
535
560
  let max = 0;
536
561
  try {
537
562
  for (const e of readdirSync(dir, { withFileTypes: true })) {
538
563
  const p = join(dir, e.name);
539
564
  try {
540
565
  if (e.isDirectory()) {
541
- max = Math.max(max, dirLastModified(p));
566
+ const subMax = dirLastModified(p, cutoffMs);
567
+ if (subMax >= cutoffMs)
568
+ return subMax;
569
+ max = Math.max(max, subMax);
542
570
  }
543
571
  else {
544
- max = Math.max(max, statSync(p).mtimeMs);
572
+ const m = statSync(p).mtimeMs;
573
+ if (m >= cutoffMs)
574
+ return m;
575
+ max = Math.max(max, m);
545
576
  }
546
577
  }
547
578
  catch {
@@ -567,9 +598,10 @@ export class DshClientSession {
567
598
  const p = join(dir, e.name);
568
599
  if (!e.isDirectory())
569
600
  continue;
570
- if (dirLastModified(p) === 0)
601
+ const lastMod = dirLastModified(p, cutoff);
602
+ if (lastMod === 0)
571
603
  continue; // 空目录不删
572
- if (dirLastModified(p) < cutoff) {
604
+ if (lastMod < cutoff) {
573
605
  rmSync(p, { recursive: true, force: true });
574
606
  removed++;
575
607
  }
@@ -1556,6 +1588,7 @@ export class DshClientSession {
1556
1588
  isStreaming: conv.isStreaming,
1557
1589
  isSubagent: false,
1558
1590
  pinned: isPinned,
1591
+ ...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
1559
1592
  // DSH Agent 预设(左栏徽标/详情用;pi 引擎不填)。
1560
1593
  agentPreset: conv.agentPreset,
1561
1594
  presetLocked: conv.presetLocked,
@@ -1785,7 +1818,7 @@ export class DshClientSession {
1785
1818
  * cancel). `index` is the clicked bubble's position (duplicate texts need
1786
1819
  * it); mismatch or omission falls back to first-occurrence text match.
1787
1820
  */
1788
- removeQueued(kind, text, index) {
1821
+ removeQueued(kind, text, index, _id) {
1789
1822
  const conv = this.conv;
1790
1823
  const arr = kind === "steer" ? conv.queue.steering : conv.queue.followUp;
1791
1824
  const next = removeQueuedByIndexOrText(arr, text, index);
@@ -1840,6 +1873,8 @@ export class DshClientSession {
1840
1873
  async promptConv(conv, text, attachments, _queue = false,
1841
1874
  // issue #145 同项目并行提醒:只进运行时上下文,不进用户气泡。
1842
1875
  sysPrefix = "") {
1876
+ let optimisticId;
1877
+ let followUpAdded = false;
1843
1878
  try {
1844
1879
  if (this.quiesceBlocked())
1845
1880
  return;
@@ -1890,14 +1925,19 @@ export class DshClientSession {
1890
1925
  .filter((q) => q !== null),
1891
1926
  },
1892
1927
  };
1928
+ optimisticId = optimistic.id;
1893
1929
  this.appendMessage(conv, optimistic);
1894
1930
  if (conv.isStreaming) {
1895
1931
  // DSH 无 mid-run steering:isStreaming 时入队(followUp),
1896
1932
  // 运行时 inbox 在 run 结束后消费。入队后立即 flushSnapshot 让排队气泡上屏。
1897
1933
  conv.queue.followUp.push(text);
1934
+ followUpAdded = true;
1898
1935
  this.flushSnapshot();
1899
1936
  await this.runtime.prompt(conv.sessionId, blocks);
1900
- conv.queue.followUp = conv.queue.followUp.filter((t) => t !== text);
1937
+ const qIdx = conv.queue.followUp.indexOf(text);
1938
+ if (qIdx !== -1)
1939
+ conv.queue.followUp.splice(qIdx, 1);
1940
+ followUpAdded = false;
1901
1941
  }
1902
1942
  else {
1903
1943
  this.flushSnapshot();
@@ -1910,6 +1950,19 @@ export class DshClientSession {
1910
1950
  }
1911
1951
  }
1912
1952
  catch (err) {
1953
+ // 发送失败事务补偿:回滚乐观用户消息与排队气泡
1954
+ if (optimisticId) {
1955
+ const optIdx = conv.messages.findIndex((m) => m.id === optimisticId);
1956
+ if (optIdx !== -1) {
1957
+ conv.messages.splice(optIdx, 1);
1958
+ conv.messageIds.delete(optimisticId);
1959
+ }
1960
+ }
1961
+ if (followUpAdded) {
1962
+ const qIdx = conv.queue.followUp.indexOf(text);
1963
+ if (qIdx !== -1)
1964
+ conv.queue.followUp.splice(qIdx, 1);
1965
+ }
1913
1966
  this.emit({
1914
1967
  type: "notice",
1915
1968
  level: "error",
@@ -2486,8 +2539,8 @@ export class DshClientSession {
2486
2539
  this.emit({
2487
2540
  type: "notice",
2488
2541
  level: "warning",
2489
- text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端后再移出`,
2490
- textEn: `Conversation "${conv.title}" still has open terminals — close them before removing`,
2542
+ text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端或右键选择「强行关闭」后再移出`,
2543
+ textEn: `Conversation "${conv.title}" still has open terminals — close them or right-click to force-dismiss`,
2491
2544
  });
2492
2545
  return;
2493
2546
  }
@@ -3529,7 +3582,50 @@ export class DshClientSession {
3529
3582
  // -----------------------------------------------------------------------
3530
3583
  // 设置 / 系统提示词
3531
3584
  // -----------------------------------------------------------------------
3585
+ buildFallbackPromptSections() {
3586
+ const identity = "You are an AI agent powered by DeepSeek Harness.";
3587
+ const custom = this.settings.customSystemPrompt.trim();
3588
+ const markerGuidance = this.markerSvc.buildGuidance().trim();
3589
+ const effectiveCustom = [custom, markerGuidance].filter(Boolean).join("\n\n");
3590
+ const sections = [
3591
+ { name: "harness:identity", text: identity, chars: identity.length },
3592
+ ];
3593
+ if (this.settings.promptMode === "replace") {
3594
+ const persona = effectiveCustom ||
3595
+ `You are a coding agent powered by the ${this.model} model. Your working directory is ${this.cwd}.`;
3596
+ sections.push({ name: "deployment:persona-prefix", text: persona, chars: persona.length });
3597
+ }
3598
+ else {
3599
+ const persona = `You are a coding agent powered by the ${this.model} model. Your working directory is ${this.cwd}.`;
3600
+ sections.push({ name: "deployment:persona-prefix", text: persona, chars: persona.length });
3601
+ if (effectiveCustom) {
3602
+ sections.push({ name: "pi-webui:custom-prompt", text: effectiveCustom, chars: effectiveCustom.length });
3603
+ }
3604
+ }
3605
+ return sections;
3606
+ }
3607
+ buildFallbackSystemPrompt() {
3608
+ return this.buildFallbackPromptSections()
3609
+ .map((s) => s.text)
3610
+ .filter(Boolean)
3611
+ .join("\n\n");
3612
+ }
3613
+ buildFallbackPromptSourceDefaults() {
3614
+ const defs = {};
3615
+ for (const s of this.buildFallbackPromptSections()) {
3616
+ defs[s.name] = s.text;
3617
+ }
3618
+ return defs;
3619
+ }
3532
3620
  pushSettings() {
3621
+ if (this.runtime?.alive && !this.cachedEffectiveSystemPrompt) {
3622
+ void this.refreshPromptInfo().catch(() => { });
3623
+ }
3624
+ const effectiveSystemPrompt = this.cachedEffectiveSystemPrompt || this.buildFallbackSystemPrompt();
3625
+ const promptSourceDefaults = Object.keys(this.cachedPromptSourceDefaults).length > 0
3626
+ ? this.cachedPromptSourceDefaults
3627
+ : this.buildFallbackPromptSourceDefaults();
3628
+ const promptSections = this.cachedPromptSections.length > 0 ? this.cachedPromptSections : this.buildFallbackPromptSections();
3533
3629
  const settings = {
3534
3630
  promptMode: this.settings.promptMode,
3535
3631
  customSystemPrompt: this.settings.customSystemPrompt,
@@ -3573,6 +3669,9 @@ export class DshClientSession {
3573
3669
  openRecentSessionOnProjectSwitch: this.settings.openRecentSessionOnProjectSwitch ?? true,
3574
3670
  // DSH 无 skill 全文注入概念,给空保协议完整。
3575
3671
  skillsFullText: [],
3672
+ skillsCatalogMaxDesc: 250,
3673
+ skillsCatalogShowLocation: false,
3674
+ skillsCatalogBudget: 20000,
3576
3675
  visionBridgeEnabled: false,
3577
3676
  visionBridgeModel: null,
3578
3677
  visionBridgePromptMode: "append",
@@ -3590,12 +3689,14 @@ export class DshClientSession {
3590
3689
  uiLayout: normalizeUiLayout(this.settings.uiLayout),
3591
3690
  promptTemplate: this.settings.promptTemplate ?? "",
3592
3691
  promptOverrides: this.settings.promptOverrides ?? {},
3692
+ promptDisabled: [...(this.settings.promptDisabled ?? [])],
3593
3693
  // DSH 无 pi 工具注册表面,逐工具文案覆盖不适用;保协议完整。
3594
3694
  toolPromptOverrides: {},
3595
- effectiveSystemPrompt: this.settings.customSystemPrompt,
3596
- promptSourceDefaults: {},
3597
- // DSH 引擎不接标准 pi 的 customTool 工具 schema(走 goal-rpc),此处给空。
3598
- toolsSchema: "",
3695
+ effectiveSystemPrompt,
3696
+ promptSourceDefaults,
3697
+ promptSections,
3698
+ // DSH 运行时真实的工具 schema 文本(发给模型的工具列表 JSON Schema 格式化文本)。
3699
+ toolsSchema: this.cachedToolsSchema,
3599
3700
  visionBridgeDefaultPrompt: "",
3600
3701
  scmCommitMsgDefaultPrompt: "",
3601
3702
  visionModels: [],
@@ -3629,6 +3730,8 @@ export class DshClientSession {
3629
3730
  this.settings.promptTemplate = partial.promptTemplate;
3630
3731
  if (partial.promptOverrides !== undefined)
3631
3732
  this.settings.promptOverrides = partial.promptOverrides;
3733
+ if (partial.promptDisabled !== undefined)
3734
+ this.settings.promptDisabled = [...partial.promptDisabled];
3632
3735
  if (partial.disabledSkills !== undefined)
3633
3736
  this.settings.disabledSkills = partial.disabledSkills;
3634
3737
  if (partial.disabledExtensions !== undefined)
@@ -3731,12 +3834,15 @@ export class DshClientSession {
3731
3834
  defaultAgentPreset: this.settings.defaultAgentPreset,
3732
3835
  promptTemplate: this.settings.promptTemplate ?? "",
3733
3836
  promptOverrides: this.settings.promptOverrides ?? {},
3837
+ promptDisabled: [...(this.settings.promptDisabled ?? [])],
3734
3838
  });
3735
3839
  // 仅系统提示词或内联标记指引变化才重启运行时(DSH_PERSONA 由 launcher env 注入);
3736
3840
  // 其他设置(开关/隐藏插件等)只存不回写运行时。
3737
3841
  const personaChanged = partial.promptMode !== undefined || partial.customSystemPrompt !== undefined || markerGuidanceChanged;
3738
- if (personaChanged)
3842
+ if (personaChanged) {
3739
3843
  await this.applyPersona();
3844
+ void this.refreshPromptInfo().catch(() => { });
3845
+ }
3740
3846
  // 技能启停(#18):禁用集变化 → 同步运行时(晚 pre-step 钩子过滤目录)并刷新技能列表。
3741
3847
  if (partial.disabledSkills !== undefined) {
3742
3848
  void this.pushDisabledSkillsToRuntime();
@@ -3768,6 +3874,35 @@ export class DshClientSession {
3768
3874
  }
3769
3875
  return Promise.resolve();
3770
3876
  }
3877
+ /** 从运行时异步拉取真实组装的系统提示词、sections 与工具 schema。 */
3878
+ async refreshPromptInfo() {
3879
+ try {
3880
+ if (!this.runtime.alive)
3881
+ return;
3882
+ const res = await this.runtime.inspectPrompt();
3883
+ if (res && !res.error) {
3884
+ if (typeof res.prompt === "string" && res.prompt) {
3885
+ this.cachedEffectiveSystemPrompt = res.prompt;
3886
+ }
3887
+ if (Array.isArray(res.sections)) {
3888
+ this.cachedPromptSections = res.sections;
3889
+ const defaults = {};
3890
+ for (const s of res.sections) {
3891
+ if (s.name)
3892
+ defaults[s.name] = s.text ?? "";
3893
+ }
3894
+ this.cachedPromptSourceDefaults = defaults;
3895
+ }
3896
+ if (Array.isArray(res.tools) && res.tools.length > 0) {
3897
+ this.cachedToolsSchema = buildToolsSchemaText(res.tools);
3898
+ }
3899
+ this.pushSettings();
3900
+ }
3901
+ }
3902
+ catch {
3903
+ /* 忽略拉取失败,保持上一次缓存或兜底 */
3904
+ }
3905
+ }
3771
3906
  async reloadExtensions() {
3772
3907
  // DSH 引擎无 pi 扩展体系。
3773
3908
  this.emit({
@@ -3886,6 +4021,7 @@ export class DshClientSession {
3886
4021
  conv.agentPreset = res.preset ?? target;
3887
4022
  this.emitConversations();
3888
4023
  this.pushSettings();
4024
+ void this.refreshPromptInfo().catch(() => { });
3889
4025
  this.flushSnapshot();
3890
4026
  }
3891
4027
  catch (err) {
@@ -4052,6 +4188,7 @@ export class DshClientSession {
4052
4188
  customSystemPrompt: this.settings.customSystemPrompt,
4053
4189
  promptTemplate: "",
4054
4190
  promptOverrides: {},
4191
+ promptDisabled: [],
4055
4192
  disabledSkills: this.settings.disabledSkills,
4056
4193
  disabledExtensions: this.settings.disabledExtensions,
4057
4194
  // DSH engine: no unified tool gating (no subagent/edit_soft); empty keeps protocol complete.
@@ -4153,6 +4290,7 @@ export class DshClientSession {
4153
4290
  customSystemPrompt: s.customSystemPrompt,
4154
4291
  promptTemplate: "",
4155
4292
  promptOverrides: {},
4293
+ promptDisabled: [],
4156
4294
  disabledSkills: [...(s.disabledSkills ?? [])],
4157
4295
  disabledExtensions: [...(s.disabledExtensions ?? [])],
4158
4296
  disabledAgentTools: [],
@@ -5211,6 +5349,146 @@ export class DshClientSession {
5211
5349
  /* ignore */
5212
5350
  }
5213
5351
  }
5352
+ // -----------------------------------------------------------------------
5353
+ // 插件扩展点(与 pi 引擎的 *ForPlugins 对齐)
5354
+ // -----------------------------------------------------------------------
5355
+ activeConversationId() {
5356
+ return this.activeId;
5357
+ }
5358
+ readConversationForPlugins(opts) {
5359
+ if (opts?.clientId && opts.clientId !== this.clientId)
5360
+ return null;
5361
+ const conv = this.convs.get(this.activeId) ?? [...this.convs.values()][0];
5362
+ if (!conv)
5363
+ return null;
5364
+ return {
5365
+ clientId: this.clientId,
5366
+ conversationId: conv.id,
5367
+ isSubagent: false,
5368
+ sessionId: conv.sessionId,
5369
+ sessionFile: conv.sessionFile,
5370
+ title: conv.title,
5371
+ model: `${this.modelProvider}/${this.model}`,
5372
+ at: conv.lastEventAt || conv.createdAt,
5373
+ isStreaming: conv.isStreaming,
5374
+ messages: conv.messages,
5375
+ streamingMessage: conv.isStreaming && conv.messages.length ? conv.messages[conv.messages.length - 1] : null,
5376
+ stats: {
5377
+ totalMessages: conv.messages.length,
5378
+ tokens: { input: 0, output: 0, total: 0 },
5379
+ cost: 0,
5380
+ },
5381
+ };
5382
+ }
5383
+ listRunningForPlugins() {
5384
+ const out = [];
5385
+ for (const conv of this.convs.values()) {
5386
+ out.push({ id: conv.id, title: conv.title, cwd: conv.cwd, kind: "running", isStreaming: conv.isStreaming });
5387
+ }
5388
+ return out;
5389
+ }
5390
+ async listHistoryForPlugins(limit = 50) {
5391
+ try {
5392
+ const files = findSessionFilesForCwd(this.sessionRoot, this.cwd);
5393
+ const out = [];
5394
+ for (const file of files.slice(0, Math.max(0, limit))) {
5395
+ try {
5396
+ const { events } = readSessionLog(file);
5397
+ const title = sessionLogTitle(events) || firstUserText(events, this.getLang()) || basename(dirname(file));
5398
+ out.push({
5399
+ id: file,
5400
+ title: title.slice(0, 60),
5401
+ cwd: this.cwd,
5402
+ kind: "history",
5403
+ isStreaming: false,
5404
+ });
5405
+ }
5406
+ catch {
5407
+ // 忽略损坏的会话日志
5408
+ }
5409
+ }
5410
+ return out;
5411
+ }
5412
+ catch {
5413
+ return [];
5414
+ }
5415
+ }
5416
+ async searchForPlugins(query, limit = 20) {
5417
+ const q = query.trim().toLowerCase();
5418
+ if (!q)
5419
+ return [];
5420
+ const out = [];
5421
+ for (const conv of this.convs.values()) {
5422
+ if (conv.title.toLowerCase().includes(q))
5423
+ out.push({ id: conv.id, title: conv.title });
5424
+ if (out.length >= limit)
5425
+ return out;
5426
+ }
5427
+ try {
5428
+ const files = findSessionFilesForCwd(this.sessionRoot, this.cwd);
5429
+ for (const file of files) {
5430
+ try {
5431
+ const { events } = readSessionLog(file);
5432
+ const title = sessionLogTitle(events) || firstUserText(events, this.getLang()) || basename(dirname(file));
5433
+ if (title.toLowerCase().includes(q)) {
5434
+ out.push({ id: file, title: title.slice(0, 60) });
5435
+ if (out.length >= limit)
5436
+ break;
5437
+ }
5438
+ }
5439
+ catch { }
5440
+ }
5441
+ }
5442
+ catch { }
5443
+ return out;
5444
+ }
5445
+ async writeForPlugins(id, text) {
5446
+ try {
5447
+ const conv = this.convs.get(id);
5448
+ if (!conv)
5449
+ return { ok: false, error: `未知对话:${id}` };
5450
+ if (!text.trim())
5451
+ return { ok: false, error: "投递文本为空" };
5452
+ if (id !== this.activeId)
5453
+ await this.switchConversation(id);
5454
+ await this.prompt(text);
5455
+ return { ok: true };
5456
+ }
5457
+ catch (err) {
5458
+ return { ok: false, error: err.message };
5459
+ }
5460
+ }
5461
+ async abortForPlugins(id) {
5462
+ try {
5463
+ const conv = this.convs.get(id);
5464
+ if (!conv)
5465
+ return { ok: false, error: `未知对话:${id}` };
5466
+ if (conv.isStreaming) {
5467
+ await this.abort();
5468
+ }
5469
+ return { ok: true };
5470
+ }
5471
+ catch (err) {
5472
+ return { ok: false, error: err.message };
5473
+ }
5474
+ }
5475
+ async steerForPlugins(conversationId, text) {
5476
+ try {
5477
+ if (!text.trim())
5478
+ return { ok: false, error: "空消息" };
5479
+ const conv = this.convs.get(conversationId);
5480
+ if (!conv)
5481
+ return { ok: false, error: `未知对话:${conversationId}` };
5482
+ conv.queue.followUp.push(text.trim());
5483
+ return { ok: true };
5484
+ }
5485
+ catch (err) {
5486
+ return { ok: false, error: err.message };
5487
+ }
5488
+ }
5489
+ async listModelsForPlugins() {
5490
+ return [{ id: `${this.modelProvider}/${this.model}`, provider: this.modelProvider, vision: this.modelVision }];
5491
+ }
5214
5492
  }
5215
5493
  // ---------------------------------------------------------------------------
5216
5494
  // DshAgentService — 服务级:客户端会话管理与引擎分发入口
@@ -5413,6 +5691,10 @@ export class DshAgentService {
5413
5691
  for (const cs of this.clients.values())
5414
5692
  void cs.pushSlashCommands();
5415
5693
  }
5694
+ applyPluginMarkers() {
5695
+ for (const cs of this.clients.values())
5696
+ cs.pushSettings();
5697
+ }
5416
5698
  refreshBackgroundServers() {
5417
5699
  for (const cs of this.clients.values())
5418
5700
  cs.refreshBgTasks();
@@ -5441,4 +5723,59 @@ export class DshAgentService {
5441
5723
  recordInterruptedRuns() {
5442
5724
  /* no-op */
5443
5725
  }
5726
+ // -----------------------------------------------------------------------
5727
+ // 插件扩展点适配层(AAL - Agent Adapter Layer)
5728
+ // -----------------------------------------------------------------------
5729
+ pluginClient() {
5730
+ let fallback;
5731
+ for (const cs of this.clients.values()) {
5732
+ if (!fallback)
5733
+ fallback = cs;
5734
+ try {
5735
+ if (cs.activeConversations() > 0)
5736
+ return cs;
5737
+ }
5738
+ catch { }
5739
+ }
5740
+ return fallback;
5741
+ }
5742
+ readConversationForPlugins(opts) {
5743
+ const targetId = opts?.clientId;
5744
+ if (targetId) {
5745
+ const cs = this.clients.get(targetId);
5746
+ return cs ? cs.readConversationForPlugins({ clientId: targetId }) : null;
5747
+ }
5748
+ for (const cs of this.clients.values()) {
5749
+ const s = cs.readConversationForPlugins();
5750
+ if (s)
5751
+ return s;
5752
+ }
5753
+ return null;
5754
+ }
5755
+ async chatFromPlugin(pluginId, req) {
5756
+ const cs = this.pluginClient();
5757
+ if (!cs)
5758
+ throw new Error("无可用客户端会话");
5759
+ const targetConvId = req.conversationId || cs.activeConversationId();
5760
+ await cs.prompt(req.text);
5761
+ return { conversationId: targetConvId, clientId: cs.clientId };
5762
+ }
5763
+ async completeForPlugins(pluginId, req) {
5764
+ try {
5765
+ if (this.quiesced)
5766
+ return { ok: false, error: "插件 LLM 调用被拒绝,请等服务器恢复后重试" };
5767
+ const cs = this.pluginClient();
5768
+ const agentDir = this.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? "";
5769
+ const env = { cwd: cs?.cwd ?? this.cwd, agentDir };
5770
+ const mod = await import("../plugin-llm.js");
5771
+ const r = await mod.completeWithIsolatedSession(env, { ...req, prompt: String(req?.prompt ?? "") });
5772
+ if (!r.ok)
5773
+ return r;
5774
+ console.log(`[plugin:${pluginId}] dsh llm.complete ok(模型 ${r.model},输出 ${r.text.length} 字)`);
5775
+ return r;
5776
+ }
5777
+ catch (err) {
5778
+ return { ok: false, error: err.message };
5779
+ }
5780
+ }
5444
5781
  }
@@ -164,6 +164,9 @@ export class DshRuntime {
164
164
  env.PI_WEB_DSH_JSONRPC_ENTRY = this.jsonrpcEntry;
165
165
  return { env, activeProvider, bareModelId };
166
166
  }
167
+ getStderrTail() {
168
+ return this.stderrTail;
169
+ }
167
170
  /** 启动子进程 + initialize 握手(幂等;并发调用共享同一个启动任务)。 */
168
171
  start() {
169
172
  if (this.disposed) {
@@ -217,7 +220,8 @@ export class DshRuntime {
217
220
  return;
218
221
  const intentional = this.closed;
219
222
  this.debug("exit", { code, signal, intentional });
220
- const err = new DshTransportError(bilingual(`DSH runtime exited (code=${code} signal=${signal}) stderr: ${this.stderrTail.slice(-400)}`, `DSH runtime 已退出 (code=${code} signal=${signal}) stderr: ${this.stderrTail.slice(-400)}`));
223
+ const stderrSnippet = this.stderrTail.trim().slice(-2000);
224
+ const err = new DshTransportError(bilingual(`DSH runtime exited (code=${code} signal=${signal}) stderr: ${stderrSnippet}`, `DSH runtime 已退出 (code=${code} signal=${signal}) stderr: ${stderrSnippet}`));
221
225
  this.failPending(err);
222
226
  this.initialized = false;
223
227
  this.onExit?.(code, signal, intentional);
@@ -396,6 +400,11 @@ export class DshRuntime {
396
400
  await this.start();
397
401
  return this._request("tools/list", {});
398
402
  }
403
+ /** 检查并获取运行时当前的组装系统提示词、sections 明细和工具 schemas。 */
404
+ async inspectPrompt(sessionId) {
405
+ await this.start();
406
+ return this._request("prompt/inspect", sessionId ? { sessionId } : {});
407
+ }
399
408
  /** 回传一个桥接工具的执行结果(isError=true 时 result 为错误信息)。 */
400
409
  async toolsCallResult(id, result, isError) {
401
410
  await this.start();
@@ -27,7 +27,7 @@ import { parseTextQuote } from "../text-quote.js";
27
27
  import { ARGS_CAP, TEXT_CAP, TOOL_OUTPUT_CAP, truncate } from "../serialize.js";
28
28
  import { stripMarkers } from "../markers/index.js";
29
29
  /** DSH user-role content blocks → UiContentBlock[]。 */
30
- export function serializeUserBlocks(blocks) {
30
+ function serializeUserBlocks(blocks) {
31
31
  if (!Array.isArray(blocks) || blocks.length === 0) {
32
32
  return [{ type: "text", text: "" }];
33
33
  }