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,6 +19,7 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
19
19
  import { pick } from "./i18n.js";
20
20
  import { DELEGATE_TASK_TOOL_NAME } from "./tool-manager.js";
21
21
  import { subagentTitle } from "./subagents.js";
22
+ import { parseRequiredTools, resolveSecurityMode } from "./subagent-security-gate.js";
22
23
  /** 工具名(唯一值在 tool-manager.ts;本别名保留:前端派单卡片与旧导入沿用它)。 */
23
24
  export const DELEGATE_TOOL_NAME = DELEGATE_TASK_TOOL_NAME;
24
25
  /** 各段最小长度(trim 后字符数):TASK 必须具体,OUTCOME 必须可验收,其余段不许空着。 */
@@ -159,11 +160,21 @@ export function makeDelegateTaskTool(host, lang) {
159
160
  if (err)
160
161
  return text(err, { delegated: false, agent: input.agent });
161
162
  const prompt = buildDelegationPrompt(input, getLang());
163
+ const parsedTools = parseRequiredTools(input.required_tools);
164
+ const matchedTemplate = host.listTemplates().find((t) => t.name === input.agent);
165
+ let securityMode = resolveSecurityMode(input.agent, matchedTemplate);
166
+ if (parsedTools.requestedReadOnly && securityMode === "normal") {
167
+ securityMode = "readonly";
168
+ }
169
+ const extra = {
170
+ allowedTools: parsedTools.allowedTools,
171
+ securityMode,
172
+ };
162
173
  // 与 subagent_spawn 同理:spawn 通道是唯一的失败面(数量上限 / runtime
163
174
  // 创建失败都经由 host 抛错),转成返回文本让 AI 能读到原因并修正重试。
164
175
  let convId;
165
176
  try {
166
- convId = await host.spawnSubagent(prompt, "delegate", ctx.cwd, input.agent, input.model, undefined, input.persist);
177
+ convId = await host.spawnSubagent(prompt, "delegate", ctx.cwd, input.agent, input.model, undefined, input.persist, undefined, undefined, undefined, extra);
167
178
  }
168
179
  catch (err) {
169
180
  const msg = err instanceof Error ? err.message : String(err);
@@ -174,9 +185,13 @@ export function makeDelegateTaskTool(host, lang) {
174
185
  const title = subagentTitle(prompt);
175
186
  const modelLineZh = input.model ? `\n模型:${input.model}` : "";
176
187
  const modelLineEn = input.model ? `\nModel: ${input.model}` : "";
177
- return text(pick(getLang(), `已派单:${convId}\n模板:${input.agent} · 标题:${title}${modelLineZh}` +
188
+ const toolsLineZh = parsedTools.allowedTools ? `\n工具白名单:${parsedTools.allowedTools.join(", ")}` : "";
189
+ const toolsLineEn = parsedTools.allowedTools ? `\nAllowed tools: ${parsedTools.allowedTools.join(", ")}` : "";
190
+ const securityLineZh = securityMode !== "normal" ? `\n安全模式:${securityMode === "readonly" ? "严格只读" : "审查验证"}` : "";
191
+ const securityLineEn = securityMode !== "normal" ? `\nSecurity mode: ${securityMode}` : "";
192
+ return text(pick(getLang(), `已派单:${convId}\n模板:${input.agent} · 标题:${title}${modelLineZh}${toolsLineZh}${securityLineZh}` +
178
193
  `\n子代理已在左栏运行列表中。用 subagent(action="wait_all") 一次等全部完成(不用轮询)、subagent(action="get_result") 取单个结果;` +
179
- `追问请在同一子代理会话里继续(subagent(action="steer")),不要重复派单。拿到结果后必须验证再汇报。`, `Delegated: ${convId}\nTemplate: ${input.agent} · Title: ${title}${modelLineEn}` +
194
+ `追问请在同一子代理会话里继续(subagent(action="steer")),不要重复派单。拿到结果后必须验证再汇报。`, `Delegated: ${convId}\nTemplate: ${input.agent} · Title: ${title}${modelLineEn}${toolsLineEn}${securityLineEn}` +
180
195
  `\nThe subagent is in the left running list. Use subagent(action="wait_all") to wait for all at once (no polling), ` +
181
196
  `subagent(action="get_result") for a single result; continue follow-ups in the SAME subagent session (subagent(action="steer")), ` +
182
197
  `do not delegate again. Verify the result before reporting.`, "delegate.started", {
@@ -571,6 +571,7 @@ export function handleSettingsMessage(msg, cs) {
571
571
  customSystemPrompt: msg.customSystemPrompt,
572
572
  promptTemplate: msg.promptTemplate,
573
573
  promptOverrides: msg.promptOverrides,
574
+ promptDisabled: msg.promptDisabled,
574
575
  toolPromptOverrides: msg.toolPromptOverrides,
575
576
  disabledSkills: msg.disabledSkills,
576
577
  disabledExtensions: msg.disabledExtensions,
@@ -607,6 +608,8 @@ export function handleSettingsMessage(msg, cs) {
607
608
  visionBridgePromptMode: msg.visionBridgePromptMode,
608
609
  visionBridgePrompt: msg.visionBridgePrompt,
609
610
  subagentDefaultModel: msg.subagentDefaultModel,
611
+ subagentMaxDepth: msg.subagentMaxDepth,
612
+ subagentAutoWakeMaxTurns: msg.subagentAutoWakeMaxTurns,
610
613
  retryMaxAttempts: msg.retryMaxAttempts,
611
614
  softCapTokens: msg.softCapTokens,
612
615
  softCapByModel: msg.softCapByModel,
@@ -93,7 +93,7 @@ const DSH_PRICE_INPUT = 0.14;
93
93
  const DSH_PRICE_CACHE_READ = 0.0028;
94
94
  const DSH_PRICE_OUTPUT = 0.28;
95
95
  /** 会话 root:<dataDir>/dsh-sessions(与 pi 引擎的会话目录隔离)。 */
96
- export function dshSessionRoot(dataDir) {
96
+ function dshSessionRoot(dataDir) {
97
97
  return join(dataDir, "dsh-sessions");
98
98
  }
99
99
  function estimateCost(t) {
@@ -107,7 +107,7 @@ function estimateCost(t) {
107
107
  /** 把插件工具 execute 的原始返回值归一化成模型可读文本。
108
108
  * 兼容:`{content:[{type:"text",text}...],details}` → text 拼接;string → 原串;
109
109
  * 其它对象 → JSON.stringify;null/undefined → 空串。 */
110
- export function normalizeToolResult(result) {
110
+ function normalizeToolResult(result) {
111
111
  if (typeof result === "string")
112
112
  return result;
113
113
  if (result === null || result === undefined)
@@ -164,6 +164,7 @@ const DEFAULT_SETTINGS = {
164
164
  preserveDraftAcrossConversations: false,
165
165
  promptTemplate: "",
166
166
  promptOverrides: {},
167
+ promptDisabled: [],
167
168
  };
168
169
  // ---------------------------------------------------------------------------
169
170
  // DshClientSession — 一个浏览器客户端
@@ -365,6 +366,7 @@ export class DshClientSession {
365
366
  preserveDraftAcrossConversations: savedSettings.preserveDraftAcrossConversations ?? false,
366
367
  promptTemplate: savedSettings.promptTemplate ?? "",
367
368
  promptOverrides: savedSettings.promptOverrides ?? {},
369
+ promptDisabled: savedSettings.promptDisabled ?? [],
368
370
  defaultAgentPreset: savedSettings.defaultAgentPreset ?? PRESET_DEFAULT_ID,
369
371
  defaultPermissionPreset: savedSettings.defaultPermissionPreset && PERMISSION_OFFERED.includes(savedSettings.defaultPermissionPreset)
370
372
  ? savedSettings.defaultPermissionPreset
@@ -554,17 +556,23 @@ export class DshClientSession {
554
556
  const cutoff = Date.now() - DshClientSession.SESSION_RETENTION_MS;
555
557
  try {
556
558
  const { readdirSync, rmSync } = await import("node:fs");
557
- const dirLastModified = (dir) => {
559
+ const dirLastModified = (dir, cutoffMs) => {
558
560
  let max = 0;
559
561
  try {
560
562
  for (const e of readdirSync(dir, { withFileTypes: true })) {
561
563
  const p = join(dir, e.name);
562
564
  try {
563
565
  if (e.isDirectory()) {
564
- 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);
565
570
  }
566
571
  else {
567
- 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);
568
576
  }
569
577
  }
570
578
  catch {
@@ -590,9 +598,10 @@ export class DshClientSession {
590
598
  const p = join(dir, e.name);
591
599
  if (!e.isDirectory())
592
600
  continue;
593
- if (dirLastModified(p) === 0)
601
+ const lastMod = dirLastModified(p, cutoff);
602
+ if (lastMod === 0)
594
603
  continue; // 空目录不删
595
- if (dirLastModified(p) < cutoff) {
604
+ if (lastMod < cutoff) {
596
605
  rmSync(p, { recursive: true, force: true });
597
606
  removed++;
598
607
  }
@@ -1579,6 +1588,7 @@ export class DshClientSession {
1579
1588
  isStreaming: conv.isStreaming,
1580
1589
  isSubagent: false,
1581
1590
  pinned: isPinned,
1591
+ ...(conv.terminals.countUserBlockingLive() > 0 ? { hasUserTerminals: true } : {}),
1582
1592
  // DSH Agent 预设(左栏徽标/详情用;pi 引擎不填)。
1583
1593
  agentPreset: conv.agentPreset,
1584
1594
  presetLocked: conv.presetLocked,
@@ -1808,7 +1818,7 @@ export class DshClientSession {
1808
1818
  * cancel). `index` is the clicked bubble's position (duplicate texts need
1809
1819
  * it); mismatch or omission falls back to first-occurrence text match.
1810
1820
  */
1811
- removeQueued(kind, text, index) {
1821
+ removeQueued(kind, text, index, _id) {
1812
1822
  const conv = this.conv;
1813
1823
  const arr = kind === "steer" ? conv.queue.steering : conv.queue.followUp;
1814
1824
  const next = removeQueuedByIndexOrText(arr, text, index);
@@ -1863,6 +1873,8 @@ export class DshClientSession {
1863
1873
  async promptConv(conv, text, attachments, _queue = false,
1864
1874
  // issue #145 同项目并行提醒:只进运行时上下文,不进用户气泡。
1865
1875
  sysPrefix = "") {
1876
+ let optimisticId;
1877
+ let followUpAdded = false;
1866
1878
  try {
1867
1879
  if (this.quiesceBlocked())
1868
1880
  return;
@@ -1913,14 +1925,19 @@ export class DshClientSession {
1913
1925
  .filter((q) => q !== null),
1914
1926
  },
1915
1927
  };
1928
+ optimisticId = optimistic.id;
1916
1929
  this.appendMessage(conv, optimistic);
1917
1930
  if (conv.isStreaming) {
1918
1931
  // DSH 无 mid-run steering:isStreaming 时入队(followUp),
1919
1932
  // 运行时 inbox 在 run 结束后消费。入队后立即 flushSnapshot 让排队气泡上屏。
1920
1933
  conv.queue.followUp.push(text);
1934
+ followUpAdded = true;
1921
1935
  this.flushSnapshot();
1922
1936
  await this.runtime.prompt(conv.sessionId, blocks);
1923
- 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;
1924
1941
  }
1925
1942
  else {
1926
1943
  this.flushSnapshot();
@@ -1933,6 +1950,19 @@ export class DshClientSession {
1933
1950
  }
1934
1951
  }
1935
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
+ }
1936
1966
  this.emit({
1937
1967
  type: "notice",
1938
1968
  level: "error",
@@ -2509,8 +2539,8 @@ export class DshClientSession {
2509
2539
  this.emit({
2510
2540
  type: "notice",
2511
2541
  level: "warning",
2512
- text: `对话「${conv.title}」还有未关闭的终端,请先关闭终端后再移出`,
2513
- 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`,
2514
2544
  });
2515
2545
  return;
2516
2546
  }
@@ -3659,6 +3689,7 @@ export class DshClientSession {
3659
3689
  uiLayout: normalizeUiLayout(this.settings.uiLayout),
3660
3690
  promptTemplate: this.settings.promptTemplate ?? "",
3661
3691
  promptOverrides: this.settings.promptOverrides ?? {},
3692
+ promptDisabled: [...(this.settings.promptDisabled ?? [])],
3662
3693
  // DSH 无 pi 工具注册表面,逐工具文案覆盖不适用;保协议完整。
3663
3694
  toolPromptOverrides: {},
3664
3695
  effectiveSystemPrompt,
@@ -3699,6 +3730,8 @@ export class DshClientSession {
3699
3730
  this.settings.promptTemplate = partial.promptTemplate;
3700
3731
  if (partial.promptOverrides !== undefined)
3701
3732
  this.settings.promptOverrides = partial.promptOverrides;
3733
+ if (partial.promptDisabled !== undefined)
3734
+ this.settings.promptDisabled = [...partial.promptDisabled];
3702
3735
  if (partial.disabledSkills !== undefined)
3703
3736
  this.settings.disabledSkills = partial.disabledSkills;
3704
3737
  if (partial.disabledExtensions !== undefined)
@@ -3801,6 +3834,7 @@ export class DshClientSession {
3801
3834
  defaultAgentPreset: this.settings.defaultAgentPreset,
3802
3835
  promptTemplate: this.settings.promptTemplate ?? "",
3803
3836
  promptOverrides: this.settings.promptOverrides ?? {},
3837
+ promptDisabled: [...(this.settings.promptDisabled ?? [])],
3804
3838
  });
3805
3839
  // 仅系统提示词或内联标记指引变化才重启运行时(DSH_PERSONA 由 launcher env 注入);
3806
3840
  // 其他设置(开关/隐藏插件等)只存不回写运行时。
@@ -4154,6 +4188,7 @@ export class DshClientSession {
4154
4188
  customSystemPrompt: this.settings.customSystemPrompt,
4155
4189
  promptTemplate: "",
4156
4190
  promptOverrides: {},
4191
+ promptDisabled: [],
4157
4192
  disabledSkills: this.settings.disabledSkills,
4158
4193
  disabledExtensions: this.settings.disabledExtensions,
4159
4194
  // DSH engine: no unified tool gating (no subagent/edit_soft); empty keeps protocol complete.
@@ -4255,6 +4290,7 @@ export class DshClientSession {
4255
4290
  customSystemPrompt: s.customSystemPrompt,
4256
4291
  promptTemplate: "",
4257
4292
  promptOverrides: {},
4293
+ promptDisabled: [],
4258
4294
  disabledSkills: [...(s.disabledSkills ?? [])],
4259
4295
  disabledExtensions: [...(s.disabledExtensions ?? [])],
4260
4296
  disabledAgentTools: [],
@@ -5313,6 +5349,146 @@ export class DshClientSession {
5313
5349
  /* ignore */
5314
5350
  }
5315
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
+ }
5316
5492
  }
5317
5493
  // ---------------------------------------------------------------------------
5318
5494
  // DshAgentService — 服务级:客户端会话管理与引擎分发入口
@@ -5547,4 +5723,59 @@ export class DshAgentService {
5547
5723
  recordInterruptedRuns() {
5548
5724
  /* no-op */
5549
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
+ }
5550
5781
  }
@@ -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
  }
@@ -10,8 +10,9 @@
10
10
  import { BaseAgentDriver } from "../universal/driver-base.js";
11
11
  import { openDurableStorage } from "./durable-storage.js";
12
12
  import { setupDurableRegistry } from "./durable-tools.js";
13
- import { listGlobalAvailableModels, setupDurableModels, resolveDurableModelChoice, } from "./durable-models.js";
13
+ import { listGlobalAvailableModels, setupDurableModels, resolveDurableModelChoice, resolveDurableThinkingLevels, } from "./durable-models.js";
14
14
  import { loadDurableModule, loadDurablePeerModule } from "./durable-loader.js";
15
+ import { DEFAULT_DURABLE_CAPABILITIES } from "../engine-capabilities.js";
15
16
  export class DurableAgentDriver extends BaseAgentDriver {
16
17
  id = "durable";
17
18
  name = "Pi Durable Agent";
@@ -24,6 +25,9 @@ export class DurableAgentDriver extends BaseAgentDriver {
24
25
  supportsAskUser: true,
25
26
  supportsSubagents: true,
26
27
  };
28
+ getEngineCapabilities() {
29
+ return DEFAULT_DURABLE_CAPABILITIES;
30
+ }
27
31
  dataDir;
28
32
  agentDir;
29
33
  currentModelId;
@@ -34,16 +38,50 @@ export class DurableAgentDriver extends BaseAgentDriver {
34
38
  storage = null;
35
39
  harness = null;
36
40
  backgroundContext = null;
41
+ models = null;
37
42
  initPromise = null;
38
43
  initError = null;
39
44
  currentConversationId = null;
40
45
  activeWatch = null;
41
46
  currentRunningConv = null;
47
+ currentThinkingLevel = "medium";
42
48
  constructor(cwd, opts) {
43
49
  super(cwd);
44
50
  this.dataDir = opts?.dataDir ?? process.cwd();
45
51
  this.agentDir = opts?.agentDir;
46
52
  }
53
+ setThinkingLevel(level) {
54
+ this.currentThinkingLevel = level;
55
+ // 动态应用到当前活动或持久会话,确保后续思考轮次即刻生效
56
+ if (this.currentRunningConv && typeof this.currentRunningConv.configure === "function") {
57
+ try {
58
+ void this.currentRunningConv.configure({ thinkingLevel: level }, this.backgroundContext).catch(() => { });
59
+ }
60
+ catch {
61
+ /* best effort */
62
+ }
63
+ }
64
+ else if (this.harness && this.currentConversationId) {
65
+ const numericId = Number(this.currentConversationId);
66
+ if (Number.isSafeInteger(numericId) && numericId > 0 && typeof this.harness.conversation === "function") {
67
+ void this.harness
68
+ .conversation(numericId, this.backgroundContext)
69
+ .then((conv) => {
70
+ if (conv && typeof conv.configure === "function") {
71
+ return conv.configure({ thinkingLevel: level }, this.backgroundContext);
72
+ }
73
+ })
74
+ .catch(() => { });
75
+ }
76
+ }
77
+ }
78
+ getSupportedThinkingLevels(modelId) {
79
+ return resolveDurableThinkingLevels(modelId || this.currentModelId, {
80
+ modelsContainer: this.models,
81
+ cachedModels: this.cachedModels,
82
+ agentDir: this.agentDir,
83
+ });
84
+ }
47
85
  /**
48
86
  * 初始化 Pi Durable 运行环境(按需异步单例)。
49
87
  */
@@ -68,6 +106,7 @@ export class DurableAgentDriver extends BaseAgentDriver {
68
106
  const { registry } = await setupDurableRegistry(this.cwd);
69
107
  // 5. 继承全局模型配置(读取 models.json、auth.json 并装配 Providers)
70
108
  const models = await setupDurableModels(this.agentDir);
109
+ this.models = models;
71
110
  // 6. 动态加载本地执行环境(支撑 read/write/edit/bash 等官方编码工具)
72
111
  const envModule = await loadDurableModule("env/node").catch(() => null);
73
112
  const envFactory = envModule?.NodeExecutionEnv
@@ -105,7 +144,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
105
144
  if (this.harness && typeof this.harness.createConversation === "function") {
106
145
  try {
107
146
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
108
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : {};
147
+ const agentOpts = {
148
+ agent: {
149
+ ...(modelChoice ? { model: modelChoice } : {}),
150
+ thinkingLevel: this.currentThinkingLevel,
151
+ },
152
+ };
109
153
  const conv = await this.harness.createConversation({
110
154
  ownership: { kind: "ownerless" },
111
155
  ...agentOpts,
@@ -131,7 +175,13 @@ export class DurableAgentDriver extends BaseAgentDriver {
131
175
  this.harness &&
132
176
  typeof this.harness.conversation === "function") {
133
177
  try {
134
- await this.harness.conversation(numericId, this.backgroundContext);
178
+ const conv = await this.harness.conversation(numericId, this.backgroundContext);
179
+ if (conv && typeof conv.agent === "function") {
180
+ const agent = await conv.agent(this.backgroundContext).catch(() => null);
181
+ if (agent?.thinkingLevel) {
182
+ this.currentThinkingLevel = agent.thinkingLevel;
183
+ }
184
+ }
135
185
  }
136
186
  catch {
137
187
  /* fallback */
@@ -151,7 +201,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
151
201
  const parentConv = await this.harness.conversation(numericId, this.backgroundContext);
152
202
  if (parentConv && typeof parentConv.fork === "function") {
153
203
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
154
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : {};
204
+ const agentOpts = {
205
+ agent: {
206
+ ...(modelChoice ? { model: modelChoice } : {}),
207
+ thinkingLevel: this.currentThinkingLevel,
208
+ },
209
+ };
155
210
  const forked = await parentConv.fork(atEntryId, {
156
211
  ownership: { kind: "ownerless" },
157
212
  ...agentOpts,
@@ -188,7 +243,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
188
243
  try {
189
244
  // 获取当前活动会话或工作区根会话
190
245
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
191
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : undefined;
246
+ const agentOpts = {
247
+ agent: {
248
+ ...(modelChoice ? { model: modelChoice } : {}),
249
+ thinkingLevel: this.currentThinkingLevel,
250
+ },
251
+ };
192
252
  let targetConv = null;
193
253
  const numericId = this.currentConversationId ? Number(this.currentConversationId) : NaN;
194
254
  if (Number.isSafeInteger(numericId) &&
@@ -202,10 +262,13 @@ export class DurableAgentDriver extends BaseAgentDriver {
202
262
  }
203
263
  if (this.aborted)
204
264
  return;
205
- // 若指定了模型选择,确保目标会话已应用最新模型配置
206
- if (modelChoice && typeof targetConv.configure === "function") {
265
+ // 若指定了模型选择或思考强度,确保目标会话已应用最新配置
266
+ if (typeof targetConv.configure === "function") {
207
267
  try {
208
- await targetConv.configure({ model: modelChoice }, this.backgroundContext);
268
+ await targetConv.configure({
269
+ ...(modelChoice ? { model: modelChoice } : {}),
270
+ thinkingLevel: this.currentThinkingLevel,
271
+ }, this.backgroundContext);
209
272
  }
210
273
  catch {
211
274
  /* best effort */
@@ -448,7 +511,10 @@ export class DurableAgentDriver extends BaseAgentDriver {
448
511
  if (conv && typeof conv.configure === "function") {
449
512
  const choice = resolveDurableModelChoice(modelId, this.cachedModels, this.agentDir);
450
513
  if (choice) {
451
- await conv.configure({ model: choice }, this.backgroundContext);
514
+ await conv.configure({
515
+ model: choice,
516
+ thinkingLevel: this.currentThinkingLevel,
517
+ }, this.backgroundContext);
452
518
  }
453
519
  }
454
520
  }
@@ -3,20 +3,8 @@
3
3
  *
4
4
  * 统一委托给通用全局加载器,消除代码冗余。
5
5
  */
6
- import { dynamicImportGlobalPackage, probeGlobalPackage, resolvePackageRoot, resolvePackageEntryFile, } from "../global-loader.js";
6
+ import { dynamicImportGlobalPackage } from "../global-loader.js";
7
7
  const DURABLE_PKG = "@earendil-works/pi-durable";
8
- /**
9
- * 解析并定位 @earendil-works/pi-durable 包的物理安装根目录。
10
- */
11
- export function findDurablePackageRoot(forceRefresh = false) {
12
- return resolvePackageRoot(DURABLE_PKG, { refresh: forceRefresh });
13
- }
14
- /**
15
- * 探测 Pi Durable 引擎的安装元数据(包版本号与物理路径)。
16
- */
17
- export function probeDurableInstallation(forceRefresh = false) {
18
- return probeGlobalPackage(DURABLE_PKG, { refresh: forceRefresh });
19
- }
20
8
  /**
21
9
  * 动态加载 @earendil-works/pi-durable 核心模块或其子路径模块。
22
10
  * @param subpath 子路径标识,如 ""(主包)、"tools"、"storage/sqlite/node"、"storage/memory"
@@ -35,4 +23,3 @@ export async function loadDurablePeerModule(packageName, subpath = "") {
35
23
  return null;
36
24
  }
37
25
  }
38
- export { resolvePackageEntryFile };