pi-web-ui 0.111.0 → 0.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/bin/pi-web-ui.mjs +325 -45
  4. package/dist/server/agent-service-daemon.js +29 -4
  5. package/dist/server/agent-service.js +1527 -510
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/canvas/canvas-agent-tool.js +8 -0
  11. package/dist/server/canvas/canvas-orchestrator.js +128 -22
  12. package/dist/server/canvas/pstack-skills-data.js +498 -0
  13. package/dist/server/client-state.js +28 -0
  14. package/dist/server/delegate-mode.js +6 -3
  15. package/dist/server/delegate-task.js +18 -3
  16. package/dist/server/dispatch-domain-handlers.js +39 -11
  17. package/dist/server/dsh/dsh-agent-service.js +294 -15
  18. package/dist/server/dsh/dsh-serialize.js +1 -1
  19. package/dist/server/durable/durable-driver.js +112 -107
  20. package/dist/server/durable/durable-event-projector.js +253 -0
  21. package/dist/server/durable/durable-loader.js +1 -14
  22. package/dist/server/durable/durable-models.js +107 -0
  23. package/dist/server/durable/index.js +0 -4
  24. package/dist/server/engine-probe.js +111 -48
  25. package/dist/server/eval-tool.js +28 -3
  26. package/dist/server/goal-service.js +7 -0
  27. package/dist/server/index.js +371 -57
  28. package/dist/server/json-utils.js +57 -0
  29. package/dist/server/marker-service.js +8 -0
  30. package/dist/server/message-window.js +43 -10
  31. package/dist/server/model-admin.js +247 -163
  32. package/dist/server/model-resolver.js +66 -44
  33. package/dist/server/plan-manager.js +3 -6
  34. package/dist/server/plugin-api-catalog.js +1 -0
  35. package/dist/server/plugin-assets.js +238 -0
  36. package/dist/server/plugin-facilities.js +22 -0
  37. package/dist/server/plugin-ui-slots.js +1 -0
  38. package/dist/server/plugins.js +209 -11
  39. package/dist/server/preset-fields.js +25 -1
  40. package/dist/server/preset-share.js +5 -2
  41. package/dist/server/prompt-assembler.js +2 -1
  42. package/dist/server/prompt-composer.js +18 -8
  43. package/dist/server/protocol-version.js +1 -1
  44. package/dist/server/queue-utils.js +156 -0
  45. package/dist/server/remote-ssh-service.js +110 -12
  46. package/dist/server/sdk-builtin-extensions.js +85 -0
  47. package/dist/server/serialize.js +1 -1
  48. package/dist/server/server-config.js +66 -0
  49. package/dist/server/session-parser.js +49 -13
  50. package/dist/server/session-search.js +4 -3
  51. package/dist/server/settings-service.js +74 -53
  52. package/dist/server/setup-page.js +632 -0
  53. package/dist/server/skill-discovery.js +361 -59
  54. package/dist/server/skill-maintenance.js +231 -0
  55. package/dist/server/skill-tool.js +32 -3
  56. package/dist/server/soft-cap.js +30 -6
  57. package/dist/server/subagent-helpers.js +22 -1
  58. package/dist/server/subagent-notify.js +93 -0
  59. package/dist/server/subagent-security-gate.js +282 -0
  60. package/dist/server/subagent-templates.js +8 -0
  61. package/dist/server/subagents.js +390 -48
  62. package/dist/server/terminals.js +196 -8
  63. package/dist/server/text-quote.js +61 -0
  64. package/dist/server/tool-approval.js +63 -4
  65. package/dist/server/tool-guards.js +208 -0
  66. package/dist/server/tool-host-factories.js +48 -10
  67. package/dist/server/tool-manager.js +106 -28
  68. package/dist/server/tool-overrides.js +21 -11
  69. package/dist/server/universal/driver-base.js +8 -0
  70. package/dist/server/universal/drivers/claude-code.js +116 -7
  71. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  72. package/dist/server/universal/index.js +0 -1
  73. package/dist/server/universal/universal-session.js +106 -10
  74. package/dist/server/worktree-service.js +189 -1
  75. package/docs/dsh-engine.md +1 -5
  76. package/package.json +1 -1
  77. package/plugin-sdk/client-utils.mjs +192 -5
  78. package/plugin-sdk/index.d.ts +63 -1
  79. package/plugin-sdk/index.mjs +94 -0
  80. package/plugin-sdk/package.json +5 -1
  81. package/plugins/catalog.json +21 -0
  82. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
  83. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  84. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  85. package/web/dist/index.html +11 -2
  86. package/web/dist/sw.js +1 -1
  87. package/web/dist/assets/index-B0ajS__T.js +0 -697
  88. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -10,8 +10,10 @@
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 { DurableEventProjector } from "./durable-event-projector.js";
16
+ import { DEFAULT_DURABLE_CAPABILITIES } from "../engine-capabilities.js";
15
17
  export class DurableAgentDriver extends BaseAgentDriver {
16
18
  id = "durable";
17
19
  name = "Pi Durable Agent";
@@ -24,6 +26,9 @@ export class DurableAgentDriver extends BaseAgentDriver {
24
26
  supportsAskUser: true,
25
27
  supportsSubagents: true,
26
28
  };
29
+ getEngineCapabilities() {
30
+ return DEFAULT_DURABLE_CAPABILITIES;
31
+ }
27
32
  dataDir;
28
33
  agentDir;
29
34
  currentModelId;
@@ -34,16 +39,50 @@ export class DurableAgentDriver extends BaseAgentDriver {
34
39
  storage = null;
35
40
  harness = null;
36
41
  backgroundContext = null;
42
+ models = null;
37
43
  initPromise = null;
38
44
  initError = null;
39
45
  currentConversationId = null;
40
46
  activeWatch = null;
41
47
  currentRunningConv = null;
48
+ currentThinkingLevel = "medium";
42
49
  constructor(cwd, opts) {
43
50
  super(cwd);
44
51
  this.dataDir = opts?.dataDir ?? process.cwd();
45
52
  this.agentDir = opts?.agentDir;
46
53
  }
54
+ setThinkingLevel(level) {
55
+ this.currentThinkingLevel = level;
56
+ // 动态应用到当前活动或持久会话,确保后续思考轮次即刻生效
57
+ if (this.currentRunningConv && typeof this.currentRunningConv.configure === "function") {
58
+ try {
59
+ void this.currentRunningConv.configure({ thinkingLevel: level }, this.backgroundContext).catch(() => { });
60
+ }
61
+ catch {
62
+ /* best effort */
63
+ }
64
+ }
65
+ else if (this.harness && this.currentConversationId) {
66
+ const numericId = Number(this.currentConversationId);
67
+ if (Number.isSafeInteger(numericId) && numericId > 0 && typeof this.harness.conversation === "function") {
68
+ void this.harness
69
+ .conversation(numericId, this.backgroundContext)
70
+ .then((conv) => {
71
+ if (conv && typeof conv.configure === "function") {
72
+ return conv.configure({ thinkingLevel: level }, this.backgroundContext);
73
+ }
74
+ })
75
+ .catch(() => { });
76
+ }
77
+ }
78
+ }
79
+ getSupportedThinkingLevels(modelId) {
80
+ return resolveDurableThinkingLevels(modelId || this.currentModelId, {
81
+ modelsContainer: this.models,
82
+ cachedModels: this.cachedModels,
83
+ agentDir: this.agentDir,
84
+ });
85
+ }
47
86
  /**
48
87
  * 初始化 Pi Durable 运行环境(按需异步单例)。
49
88
  */
@@ -68,6 +107,7 @@ export class DurableAgentDriver extends BaseAgentDriver {
68
107
  const { registry } = await setupDurableRegistry(this.cwd);
69
108
  // 5. 继承全局模型配置(读取 models.json、auth.json 并装配 Providers)
70
109
  const models = await setupDurableModels(this.agentDir);
110
+ this.models = models;
71
111
  // 6. 动态加载本地执行环境(支撑 read/write/edit/bash 等官方编码工具)
72
112
  const envModule = await loadDurableModule("env/node").catch(() => null);
73
113
  const envFactory = envModule?.NodeExecutionEnv
@@ -105,7 +145,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
105
145
  if (this.harness && typeof this.harness.createConversation === "function") {
106
146
  try {
107
147
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
108
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : {};
148
+ const agentOpts = {
149
+ agent: {
150
+ ...(modelChoice ? { model: modelChoice } : {}),
151
+ thinkingLevel: this.currentThinkingLevel,
152
+ },
153
+ };
109
154
  const conv = await this.harness.createConversation({
110
155
  ownership: { kind: "ownerless" },
111
156
  ...agentOpts,
@@ -131,7 +176,13 @@ export class DurableAgentDriver extends BaseAgentDriver {
131
176
  this.harness &&
132
177
  typeof this.harness.conversation === "function") {
133
178
  try {
134
- await this.harness.conversation(numericId, this.backgroundContext);
179
+ const conv = await this.harness.conversation(numericId, this.backgroundContext);
180
+ if (conv && typeof conv.agent === "function") {
181
+ const agent = await conv.agent(this.backgroundContext).catch(() => null);
182
+ if (agent?.thinkingLevel) {
183
+ this.currentThinkingLevel = agent.thinkingLevel;
184
+ }
185
+ }
135
186
  }
136
187
  catch {
137
188
  /* fallback */
@@ -151,7 +202,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
151
202
  const parentConv = await this.harness.conversation(numericId, this.backgroundContext);
152
203
  if (parentConv && typeof parentConv.fork === "function") {
153
204
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
154
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : {};
205
+ const agentOpts = {
206
+ agent: {
207
+ ...(modelChoice ? { model: modelChoice } : {}),
208
+ thinkingLevel: this.currentThinkingLevel,
209
+ },
210
+ };
155
211
  const forked = await parentConv.fork(atEntryId, {
156
212
  ownership: { kind: "ownerless" },
157
213
  ...agentOpts,
@@ -188,7 +244,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
188
244
  try {
189
245
  // 获取当前活动会话或工作区根会话
190
246
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
191
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : undefined;
247
+ const agentOpts = {
248
+ agent: {
249
+ ...(modelChoice ? { model: modelChoice } : {}),
250
+ thinkingLevel: this.currentThinkingLevel,
251
+ },
252
+ };
192
253
  let targetConv = null;
193
254
  const numericId = this.currentConversationId ? Number(this.currentConversationId) : NaN;
194
255
  if (Number.isSafeInteger(numericId) &&
@@ -202,85 +263,39 @@ export class DurableAgentDriver extends BaseAgentDriver {
202
263
  }
203
264
  if (this.aborted)
204
265
  return;
205
- // 若指定了模型选择,确保目标会话已应用最新模型配置
206
- if (modelChoice && typeof targetConv.configure === "function") {
266
+ // 若指定了模型选择或思考强度,确保目标会话已应用最新配置
267
+ if (typeof targetConv.configure === "function") {
207
268
  try {
208
- await targetConv.configure({ model: modelChoice }, this.backgroundContext);
269
+ await targetConv.configure({
270
+ ...(modelChoice ? { model: modelChoice } : {}),
271
+ thinkingLevel: this.currentThinkingLevel,
272
+ }, this.backgroundContext);
209
273
  }
210
274
  catch {
211
275
  /* best effort */
212
276
  }
213
277
  }
214
278
  this.currentRunningConv = targetConv;
215
- // 启动 Durable 反应式实时流 (LiveDoc / entries / tools 增量监听)
216
- let emittedTextLen = 0;
217
- let emittedThinkingLen = 0;
218
- const startedToolCalls = new Set();
219
- const finishedToolCalls = new Set();
279
+ // 启动 Durable 反应式事件流(正文/思考增量 + 工具入参与回执,全部来自引擎事件,见 durable-event-projector.ts)
280
+ const projector = new DurableEventProjector();
220
281
  let watch = null;
221
- if (typeof targetConv.watch === "function") {
282
+ const watchEventsFn = this.durableModule?.watchEvents;
283
+ const numericConvId = Number(targetConv?.id ?? this.currentConversationId);
284
+ if (typeof watchEventsFn === "function" && Number.isSafeInteger(numericConvId) && numericConvId > 0) {
222
285
  try {
223
- watch = await targetConv.watch(this.backgroundContext);
286
+ watch = await watchEventsFn(this.harness, numericConvId, this.backgroundContext);
224
287
  this.activeWatch = watch;
225
- watch.start((value) => {
288
+ // 挂接前可能已有在飞的半截回复(重启续跑/自愈),先把快照里的部分补上再吃增量
289
+ if (watch?.snapshot)
290
+ projector.primeSnapshot(watch.snapshot, sink);
291
+ watch.start(async (events) => {
226
292
  if (this.aborted)
227
293
  return;
228
- const live = value?.docs?.["pi.live"];
229
- if (!live)
230
- return;
231
- // 1. 实时流式捕获思考与正文内容
232
- const genMessage = live.generation?.message;
233
- if (genMessage?.content && Array.isArray(genMessage.content)) {
234
- for (const block of genMessage.content) {
235
- if (block.type === "thinking" && typeof block.thinking === "string") {
236
- const delta = block.thinking.slice(emittedThinkingLen);
237
- if (delta) {
238
- emittedThinkingLen = block.thinking.length;
239
- sink.onThinkingDelta(delta);
240
- }
241
- }
242
- else if (block.type === "text" && typeof block.text === "string") {
243
- const delta = block.text.slice(emittedTextLen);
244
- if (delta) {
245
- emittedTextLen = block.text.length;
246
- sink.onTextDelta(delta);
247
- }
248
- }
249
- }
250
- }
251
- // 2. 实时流式捕获任务图中的工具槽位执行状态
252
- const toolSlots = live.tools || live.nestedTools;
253
- if (Array.isArray(toolSlots)) {
254
- for (const slot of toolSlots) {
255
- if (!slot || !slot.callId)
256
- continue;
257
- const callId = String(slot.callId);
258
- // 工具开始运行:发射 onToolStart
259
- if (!startedToolCalls.has(callId) && (slot.status === "running" || slot.status === "done")) {
260
- startedToolCalls.add(callId);
261
- sink.onToolStart?.(callId, slot.name || slot.tool || "tool", slot.input ?? {});
262
- }
263
- // 工具执行结束:发射 onToolEnd
264
- if (startedToolCalls.has(callId) &&
265
- !finishedToolCalls.has(callId) &&
266
- (slot.status === "done" || slot.status === "error")) {
267
- finishedToolCalls.add(callId);
268
- const outputText = typeof slot.output === "string"
269
- ? slot.output
270
- : slot.output
271
- ? JSON.stringify(slot.output, null, 2)
272
- : "";
273
- sink.onToolEnd?.(callId, {
274
- output: outputText,
275
- error: slot.error ? String(slot.error) : undefined,
276
- });
277
- }
278
- }
279
- }
294
+ projector.project(events, sink);
280
295
  });
281
296
  }
282
297
  catch {
283
- /* watch 启动失败安全回退到等待模式 */
298
+ /* 事件流不可用时退化为仅最终回执(不阻断执行) */
284
299
  }
285
300
  }
286
301
  // 提交任务到 Durable 引擎
@@ -300,31 +315,16 @@ export class DurableAgentDriver extends BaseAgentDriver {
300
315
  const entryData = await this.storage.entry(settled.answer);
301
316
  const modelTurn = entryData?.entry?.model?.[0];
302
317
  finalUsage = modelTurn?.usage;
303
- if (modelTurn?.content && Array.isArray(modelTurn.content)) {
304
- for (const block of modelTurn.content) {
305
- if (block.type === "thinking" && typeof block.thinking === "string") {
306
- const delta = block.thinking.slice(emittedThinkingLen);
307
- if (delta) {
308
- emittedThinkingLen = block.thinking.length;
309
- sink.onThinkingDelta(delta);
310
- }
311
- }
312
- else if (block.type === "text" && typeof block.text === "string") {
313
- const delta = block.text.slice(emittedTextLen);
314
- if (delta) {
315
- emittedTextLen = block.text.length;
316
- sink.onTextDelta(delta);
317
- }
318
- }
319
- }
320
- }
318
+ // 存储里的完整回复作为最后一道保险:投影器按 contentIndex 记账,已流式下发的部分不会重发
319
+ if (modelTurn)
320
+ projector.projectMessage(modelTurn, sink);
321
321
  }
322
322
  catch {
323
323
  /* fallback */
324
324
  }
325
325
  }
326
326
  // 若流式期间未发射出正文且 answer 为文本或对象,进行最终保底输出
327
- if (emittedTextLen === 0 && settled.answer) {
327
+ if (!projector.emittedAnyText && settled.answer) {
328
328
  const text = typeof settled.answer === "string" ? settled.answer : JSON.stringify(settled.answer);
329
329
  sink.onTextDelta(text);
330
330
  }
@@ -365,29 +365,31 @@ export class DurableAgentDriver extends BaseAgentDriver {
365
365
  });
366
366
  }
367
367
  finally {
368
- if (this.activeWatch) {
369
- try {
370
- await this.activeWatch.stop();
371
- }
372
- catch {
373
- /* ignore */
374
- }
375
- this.activeWatch = null;
376
- }
368
+ await this.haltActiveWatch();
377
369
  this.currentRunningConv = null;
378
370
  }
379
371
  }
372
+ /**
373
+ * 停掉当前活动的事件流:ConversationWatch 用 `cancel()`,AgentEventStream 用 `stop()`,两种均不得抛。
374
+ */
375
+ haltActiveWatch() {
376
+ const watch = this.activeWatch;
377
+ this.activeWatch = null;
378
+ if (!watch)
379
+ return Promise.resolve();
380
+ try {
381
+ const pending = typeof watch.cancel === "function" ? watch.cancel() : watch.stop?.();
382
+ return Promise.resolve(pending)
383
+ .then(() => undefined)
384
+ .catch(() => undefined);
385
+ }
386
+ catch {
387
+ return Promise.resolve();
388
+ }
389
+ }
380
390
  async abort() {
381
391
  this.aborted = true;
382
- if (this.activeWatch) {
383
- try {
384
- this.activeWatch.cancel();
385
- }
386
- catch {
387
- /* ignore */
388
- }
389
- this.activeWatch = null;
390
- }
392
+ void this.haltActiveWatch();
391
393
  if (this.currentRunningConv && typeof this.currentRunningConv.abort === "function") {
392
394
  try {
393
395
  await this.currentRunningConv.abort(this.backgroundContext);
@@ -448,7 +450,10 @@ export class DurableAgentDriver extends BaseAgentDriver {
448
450
  if (conv && typeof conv.configure === "function") {
449
451
  const choice = resolveDurableModelChoice(modelId, this.cachedModels, this.agentDir);
450
452
  if (choice) {
451
- await conv.configure({ model: choice }, this.backgroundContext);
453
+ await conv.configure({
454
+ model: choice,
455
+ thinkingLevel: this.currentThinkingLevel,
456
+ }, this.backgroundContext);
452
457
  }
453
458
  }
454
459
  }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * durable-event-projector.ts — 把 @earendil-works/pi-durable 的 AgentEvent 批次投影为宿主 AgentEventSink 事件。
3
+ *
4
+ * 事实源:pi-durable `harness/events.d.ts`(`AgentEvent` / `ToolEventCall` / `MessageChange`)。
5
+ *
6
+ * 关键契约(别再回到读 `pi.live` 槽位的老路):
7
+ * 1. `pi.live` 只是「运行期进度投影」——槽位**只有 running 期间**带 `output`,结算是全部剪掉;
8
+ * 槽位**从不携带 `input`**(模型发起调用的入参在工具任务的 checkpoint 里,事件层已解析好)。
9
+ * 2. 因此工具入参唯一来源是 `tool_execution_start.args`,
10
+ * 工具结果唯一来源是 `tool_execution_end.entry`(模型调用)或 `tool_execution_end.result`(嵌套调用)。
11
+ * 3. 正文/思考走 `message_start` / `message_update(changes)` / `message_end`,
12
+ * 投影层按 `contentIndex` 记账已下发长度,保证流式增量与整段回执不重复、不丢字。
13
+ */
14
+ /** 富文本内容块转纯文本(字符串 / `{type:"text"}` 数组两种形态)。 */
15
+ export function contentToText(content) {
16
+ if (typeof content === "string")
17
+ return content;
18
+ if (!Array.isArray(content))
19
+ return "";
20
+ const parts = [];
21
+ for (const item of content) {
22
+ if (typeof item === "string") {
23
+ parts.push(item);
24
+ continue;
25
+ }
26
+ if (item && typeof item === "object") {
27
+ const block = item;
28
+ if (block.type === "text" && typeof block.text === "string")
29
+ parts.push(block.text);
30
+ }
31
+ }
32
+ return parts.join("\n");
33
+ }
34
+ /**
35
+ * 工具回执(`tool_execution_end`)里的正文与错误标记。
36
+ * 成功只带 `output`,失败只带 `error`(宿主以 `error` 是否存在判定 isError)。
37
+ */
38
+ export function readToolEnd(event) {
39
+ const message = event?.entry?.model?.[0];
40
+ if (message) {
41
+ const text = contentToText(message.content);
42
+ return message.isError ? { error: text || "error" } : { output: text };
43
+ }
44
+ const result = event?.result;
45
+ if (result) {
46
+ const diagnostics = Array.isArray(result.diagnostics)
47
+ ? result.diagnostics
48
+ .map((d) => (typeof d?.message === "string" ? d.message : ""))
49
+ .filter(Boolean)
50
+ .join("\n")
51
+ : "";
52
+ const text = contentToText(result.structuredOutput) || diagnostics;
53
+ return result.isError ? { error: text || "error" } : { output: text };
54
+ }
55
+ return { output: "" };
56
+ }
57
+ /**
58
+ * 一次投影器实例 = 一次 prompt 轮次的展示状态(每个对话每轮新建,避免跨轮串味)。
59
+ */
60
+ export class DurableEventProjector {
61
+ /** 每个正文内容块(contentIndex)已下发的字符数 */
62
+ textSent = new Map();
63
+ /** 每个思考内容块已下发的字符数 */
64
+ thinkingSent = new Map();
65
+ /** 每个工具调用已下发的进度输出窗口(用于把 `set` / `append` 换算成增量) */
66
+ toolOutput = new Map();
67
+ /** 已发过 onToolStart 的调用(未见过开始的回执不单独出结果卡) */
68
+ startedTools = new Set();
69
+ /** 是否已经下发过任何正文(供“流式全文都没出来”时最后一手兜底判断)。 */
70
+ get emittedAnyText() {
71
+ for (const length of this.textSent.values()) {
72
+ if (length > 0)
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+ /**
78
+ * 附着时的快照:若挂接时已有在飞的半截回复(重启续跑/自愈),把它当作已下发内容补上,
79
+ * 否则随后的 `message_update` 增量只有尾巴、正文会从中间开始。正常时序(先挂接再 submit)下是空操作。
80
+ */
81
+ primeSnapshot(snapshot, sink) {
82
+ this.textSent.clear();
83
+ this.thinkingSent.clear();
84
+ this.projectMessage(snapshot?.generation?.message, sink);
85
+ }
86
+ /** 投影一批 AgentEvent。 */
87
+ project(events, sink) {
88
+ if (!Array.isArray(events))
89
+ return;
90
+ // 引擎在同一个提交里会先发 `tool_execution_start`、后发该轮正文的 message 事件(见 events.js 的 Progress 段),
91
+ // 而正文在时间上早于工具调用——“我来看下目录”类的文字必须落在工具卡之前,所以把工具开始推迟到批末
92
+ // (同一批里它自己的 `tool_execution_update` 跟着一起推,避免先到进度后到卡片)。
93
+ const deferred = [];
94
+ const deferredCallIds = new Set();
95
+ for (const event of events) {
96
+ const type = event?.type;
97
+ if (type === "tool_execution_start") {
98
+ deferred.push(event);
99
+ deferredCallIds.add(String(event?.toolCallId ?? ""));
100
+ continue;
101
+ }
102
+ if (type === "tool_execution_update" && deferredCallIds.has(String(event?.toolCallId ?? ""))) {
103
+ deferred.push(event);
104
+ continue;
105
+ }
106
+ this.projectSafely(event, sink);
107
+ }
108
+ for (const event of deferred)
109
+ this.projectSafely(event, sink);
110
+ }
111
+ projectSafely(event, sink) {
112
+ try {
113
+ this.projectOne(event, sink);
114
+ }
115
+ catch {
116
+ /* 单条事件投影失败不拖垮整批(事件是外部包产物,字段可能随版本微调) */
117
+ }
118
+ }
119
+ projectOne(event, sink) {
120
+ if (!event || typeof event !== "object")
121
+ return;
122
+ switch (event.type) {
123
+ case "message_start": {
124
+ // 新一轮助手消息:contentIndex 记账归零,避免沿用上一条消息的下发长度
125
+ this.textSent.clear();
126
+ this.thinkingSent.clear();
127
+ this.projectMessage(event.message, sink);
128
+ return;
129
+ }
130
+ case "message_update": {
131
+ const changes = Array.isArray(event.changes) ? event.changes : [];
132
+ for (const change of changes) {
133
+ if (change?.type === "text_delta" && typeof change.delta === "string") {
134
+ this.emitDelta(this.textSent, change.contentIndex, change.delta, (d) => sink.onTextDelta(d));
135
+ }
136
+ else if (change?.type === "thinking_delta" && typeof change.delta === "string") {
137
+ this.emitDelta(this.thinkingSent, change.contentIndex, change.delta, (d) => sink.onThinkingDelta(d));
138
+ }
139
+ else if (change?.type === "message") {
140
+ this.projectMessage(change.message, sink);
141
+ }
142
+ else if (typeof change?.contentIndex === "number" && change?.block) {
143
+ // text_start / thinking_start / block:块整体送达,按已下发长度补齐剩余部分
144
+ this.projectBlock(change.contentIndex, change.block, sink);
145
+ }
146
+ }
147
+ return;
148
+ }
149
+ case "snapshot": {
150
+ // 流溢出时引擎以快照替换未投递批次:只补在飞消息的剩余正文(历史条目/工具卡已在先前批次发过)
151
+ this.projectMessage(event.generation?.message, sink);
152
+ return;
153
+ }
154
+ case "message_end": {
155
+ // 提交后的完整助手消息:补齐流式期间遗漏的尾部
156
+ this.projectMessage(event.entry?.model?.[0], sink);
157
+ return;
158
+ }
159
+ case "tool_execution_start": {
160
+ // 嵌套调用(`parentCallId` 存在)是父调用内部的子步骤,不单独出卡片,保持与既往展示口径一致
161
+ if (event.parentToolCallId !== undefined)
162
+ return;
163
+ const callId = String(event.toolCallId ?? "");
164
+ if (!callId)
165
+ return;
166
+ this.toolOutput.delete(callId);
167
+ const args = event.args && typeof event.args === "object" && !Array.isArray(event.args) ? event.args : {};
168
+ this.startedTools.add(callId);
169
+ sink.onToolStart?.(callId, String(event.toolName ?? "tool"), args);
170
+ return;
171
+ }
172
+ case "tool_execution_update": {
173
+ if (event.parentToolCallId !== undefined)
174
+ return;
175
+ this.projectToolUpdate(String(event.toolCallId ?? ""), event.output, sink);
176
+ return;
177
+ }
178
+ case "tool_execution_end": {
179
+ if (event.parentToolCallId !== undefined)
180
+ return;
181
+ const callId = String(event.toolCallId ?? "");
182
+ if (!callId)
183
+ return;
184
+ this.toolOutput.delete(callId);
185
+ if (!this.startedTools.delete(callId)) {
186
+ // 边缘情形:附着前就已开始的调用(崩溃恢复/自愈续跑)。入参无事件可捞,宁可不编造;至少不丢回执
187
+ sink.onToolStart?.(callId, String(event.toolName ?? "tool"), {});
188
+ }
189
+ const { output, error } = readToolEnd(event);
190
+ sink.onToolEnd?.(callId, error !== undefined ? { error } : { output });
191
+ return;
192
+ }
193
+ default:
194
+ return;
195
+ }
196
+ }
197
+ /** 按已下发长度补齐一条完整助手消息(含 thinking / text)。 */
198
+ projectMessage(message, sink) {
199
+ const blocks = message?.content;
200
+ if (!Array.isArray(blocks))
201
+ return;
202
+ blocks.forEach((block, index) => this.projectBlock(index, block, sink));
203
+ }
204
+ projectBlock(index, block, sink) {
205
+ if (!block || typeof block !== "object")
206
+ return;
207
+ if (block.type === "text" && typeof block.text === "string") {
208
+ this.emitRemainder(this.textSent, index, block.text, (d) => sink.onTextDelta(d));
209
+ }
210
+ else if (block.type === "thinking" && typeof block.thinking === "string") {
211
+ this.emitRemainder(this.thinkingSent, index, block.thinking, (d) => sink.onThinkingDelta(d));
212
+ }
213
+ }
214
+ emitDelta(sent, index, delta, emit) {
215
+ if (!delta)
216
+ return;
217
+ emit(delta);
218
+ sent.set(index, (sent.get(index) ?? 0) + delta.length);
219
+ }
220
+ emitRemainder(sent, index, text, emit) {
221
+ const already = sent.get(index) ?? 0;
222
+ if (text.length <= already)
223
+ return;
224
+ sent.set(index, text.length);
225
+ emit(text.slice(already));
226
+ }
227
+ /**
228
+ * 运行期进度输出 → 增量。
229
+ * 引擎侧窗口语义只有两种:`{ trimStart, append }`(修剪后追加)与 `{ set }`(整体替换)。
230
+ */
231
+ projectToolUpdate(callId, output, sink) {
232
+ if (!callId || !output || typeof output !== "object")
233
+ return;
234
+ if (!sink.onToolUpdate)
235
+ return;
236
+ const previous = this.toolOutput.get(callId) ?? "";
237
+ if (typeof output.set === "string") {
238
+ const next = output.set;
239
+ this.toolOutput.set(callId, next);
240
+ // 无法回撤已下发内容:仅在窗口是纯追加时补增量
241
+ if (next.startsWith(previous) && next.length > previous.length) {
242
+ sink.onToolUpdate(callId, next.slice(previous.length));
243
+ }
244
+ return;
245
+ }
246
+ const trim = typeof output.trimStart === "number" && output.trimStart > 0 ? output.trimStart : 0;
247
+ const base = trim ? previous.slice(trim) : previous;
248
+ const append = typeof output.append === "string" ? output.append : "";
249
+ this.toolOutput.set(callId, base + append);
250
+ if (append)
251
+ sink.onToolUpdate(callId, append);
252
+ }
253
+ }
@@ -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 };