@vuagent/server 0.3.0 → 0.6.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 (154) hide show
  1. package/README.md +49 -16
  2. package/dist/adapters/anthropic-driver.d.ts +41 -0
  3. package/dist/adapters/anthropic-driver.d.ts.map +1 -1
  4. package/dist/adapters/anthropic-driver.js +62 -1
  5. package/dist/adapters/anthropic-driver.js.map +1 -1
  6. package/dist/adapters/openai-driver.d.ts.map +1 -1
  7. package/dist/adapters/openai-driver.js +8 -0
  8. package/dist/adapters/openai-driver.js.map +1 -1
  9. package/dist/core/action-envelope.d.ts +64 -0
  10. package/dist/core/action-envelope.d.ts.map +1 -0
  11. package/dist/core/action-envelope.js +110 -0
  12. package/dist/core/action-envelope.js.map +1 -0
  13. package/dist/core/action-hub.d.ts +67 -0
  14. package/dist/core/action-hub.d.ts.map +1 -1
  15. package/dist/core/action-hub.js +74 -0
  16. package/dist/core/action-hub.js.map +1 -1
  17. package/dist/core/agent-loop.d.ts +8 -0
  18. package/dist/core/agent-loop.d.ts.map +1 -1
  19. package/dist/core/agent-loop.js +94 -27
  20. package/dist/core/agent-loop.js.map +1 -1
  21. package/dist/core/config-schema.d.ts +8 -4
  22. package/dist/core/config-schema.d.ts.map +1 -1
  23. package/dist/core/config-schema.js +56 -9
  24. package/dist/core/config-schema.js.map +1 -1
  25. package/dist/core/context-compactor.d.ts.map +1 -1
  26. package/dist/core/context-compactor.js +12 -1
  27. package/dist/core/context-compactor.js.map +1 -1
  28. package/dist/core/event-sink.d.ts +31 -1
  29. package/dist/core/event-sink.d.ts.map +1 -1
  30. package/dist/core/event-sink.js +54 -1
  31. package/dist/core/event-sink.js.map +1 -1
  32. package/dist/core/http-body-guards.d.ts +74 -0
  33. package/dist/core/http-body-guards.d.ts.map +1 -0
  34. package/dist/core/http-body-guards.js +263 -0
  35. package/dist/core/http-body-guards.js.map +1 -0
  36. package/dist/core/metrics-registry.d.ts +45 -1
  37. package/dist/core/metrics-registry.d.ts.map +1 -1
  38. package/dist/core/metrics-registry.js +183 -2
  39. package/dist/core/metrics-registry.js.map +1 -1
  40. package/dist/core/ops-reporter.d.ts +4 -0
  41. package/dist/core/ops-reporter.d.ts.map +1 -1
  42. package/dist/core/ops-reporter.js +22 -0
  43. package/dist/core/ops-reporter.js.map +1 -1
  44. package/dist/core/otlp-trace-sink.d.ts +54 -0
  45. package/dist/core/otlp-trace-sink.d.ts.map +1 -0
  46. package/dist/core/otlp-trace-sink.js +272 -0
  47. package/dist/core/otlp-trace-sink.js.map +1 -0
  48. package/dist/core/patch-stash.d.ts +57 -0
  49. package/dist/core/patch-stash.d.ts.map +1 -0
  50. package/dist/core/patch-stash.js +84 -0
  51. package/dist/core/patch-stash.js.map +1 -0
  52. package/dist/core/rate-limit.d.ts +49 -0
  53. package/dist/core/rate-limit.d.ts.map +1 -0
  54. package/dist/core/rate-limit.js +112 -0
  55. package/dist/core/rate-limit.js.map +1 -0
  56. package/dist/core/recovery.d.ts.map +1 -1
  57. package/dist/core/recovery.js +2 -1
  58. package/dist/core/recovery.js.map +1 -1
  59. package/dist/core/redis-externalize.d.ts +56 -0
  60. package/dist/core/redis-externalize.d.ts.map +1 -0
  61. package/dist/core/redis-externalize.js +119 -0
  62. package/dist/core/redis-externalize.js.map +1 -0
  63. package/dist/core/result-digest.d.ts +100 -0
  64. package/dist/core/result-digest.d.ts.map +1 -0
  65. package/dist/core/result-digest.js +274 -0
  66. package/dist/core/result-digest.js.map +1 -0
  67. package/dist/core/secret-store.d.ts +76 -0
  68. package/dist/core/secret-store.d.ts.map +1 -0
  69. package/dist/core/secret-store.js +77 -0
  70. package/dist/core/secret-store.js.map +1 -0
  71. package/dist/core/session-execution-hub.d.ts +53 -1
  72. package/dist/core/session-execution-hub.d.ts.map +1 -1
  73. package/dist/core/session-execution-hub.js +81 -1
  74. package/dist/core/session-execution-hub.js.map +1 -1
  75. package/dist/core/sse-response.d.ts +37 -0
  76. package/dist/core/sse-response.d.ts.map +1 -0
  77. package/dist/core/sse-response.js +121 -0
  78. package/dist/core/sse-response.js.map +1 -0
  79. package/dist/core/system-prompt.d.ts +7 -0
  80. package/dist/core/system-prompt.d.ts.map +1 -1
  81. package/dist/core/system-prompt.js +18 -0
  82. package/dist/core/system-prompt.js.map +1 -1
  83. package/dist/core/tool-step-executor.d.ts +19 -0
  84. package/dist/core/tool-step-executor.d.ts.map +1 -1
  85. package/dist/core/tool-step-executor.js +430 -112
  86. package/dist/core/tool-step-executor.js.map +1 -1
  87. package/dist/core/trace-context.d.ts +23 -0
  88. package/dist/core/trace-context.d.ts.map +1 -0
  89. package/dist/core/trace-context.js +57 -0
  90. package/dist/core/trace-context.js.map +1 -0
  91. package/dist/core/turn-persistence.d.ts +21 -4
  92. package/dist/core/turn-persistence.d.ts.map +1 -1
  93. package/dist/core/turn-persistence.js +49 -5
  94. package/dist/core/turn-persistence.js.map +1 -1
  95. package/dist/core/types.d.ts +13 -0
  96. package/dist/core/types.d.ts.map +1 -1
  97. package/dist/core/ui-registry.d.ts +2 -0
  98. package/dist/core/ui-registry.d.ts.map +1 -1
  99. package/dist/core/ui-registry.js +9 -0
  100. package/dist/core/ui-registry.js.map +1 -1
  101. package/dist/index.d.ts.map +1 -1
  102. package/dist/index.js +43 -4
  103. package/dist/index.js.map +1 -1
  104. package/dist/security.d.ts +38 -1
  105. package/dist/security.d.ts.map +1 -1
  106. package/dist/security.js +98 -5
  107. package/dist/security.js.map +1 -1
  108. package/dist/server.d.ts +25 -1
  109. package/dist/server.d.ts.map +1 -1
  110. package/dist/server.js +818 -132
  111. package/dist/server.js.map +1 -1
  112. package/dist/storage/drivers/base.driver.d.ts +38 -0
  113. package/dist/storage/drivers/base.driver.d.ts.map +1 -1
  114. package/dist/storage/drivers/base.driver.js +8 -1
  115. package/dist/storage/drivers/base.driver.js.map +1 -1
  116. package/dist/storage/drivers/memory.driver.d.ts +5 -0
  117. package/dist/storage/drivers/memory.driver.d.ts.map +1 -1
  118. package/dist/storage/drivers/memory.driver.js +14 -0
  119. package/dist/storage/drivers/memory.driver.js.map +1 -1
  120. package/dist/storage/drivers/redis.driver.d.ts +15 -0
  121. package/dist/storage/drivers/redis.driver.d.ts.map +1 -1
  122. package/dist/storage/drivers/redis.driver.js +19 -0
  123. package/dist/storage/drivers/redis.driver.js.map +1 -1
  124. package/dist/storage/drivers/sqlite.driver.d.ts +39 -0
  125. package/dist/storage/drivers/sqlite.driver.d.ts.map +1 -1
  126. package/dist/storage/drivers/sqlite.driver.js +75 -0
  127. package/dist/storage/drivers/sqlite.driver.js.map +1 -1
  128. package/dist/storage/interfaces.d.ts +14 -0
  129. package/dist/storage/interfaces.d.ts.map +1 -1
  130. package/dist/storage/repositories/cost-record.repository.d.ts +10 -2
  131. package/dist/storage/repositories/cost-record.repository.d.ts.map +1 -1
  132. package/dist/storage/repositories/cost-record.repository.js +53 -0
  133. package/dist/storage/repositories/cost-record.repository.js.map +1 -1
  134. package/dist/storage/repositories/session.repository.d.ts +66 -3
  135. package/dist/storage/repositories/session.repository.d.ts.map +1 -1
  136. package/dist/storage/repositories/session.repository.js +253 -39
  137. package/dist/storage/repositories/session.repository.js.map +1 -1
  138. package/dist/storage/sqlite-action-persist.d.ts +30 -0
  139. package/dist/storage/sqlite-action-persist.d.ts.map +1 -0
  140. package/dist/storage/sqlite-action-persist.js +57 -0
  141. package/dist/storage/sqlite-action-persist.js.map +1 -0
  142. package/dist/tools/system/bash-tool.d.ts +21 -0
  143. package/dist/tools/system/bash-tool.d.ts.map +1 -1
  144. package/dist/tools/system/bash-tool.js +138 -49
  145. package/dist/tools/system/bash-tool.js.map +1 -1
  146. package/dist/tools/ui/protocol-tools.d.ts +17 -0
  147. package/dist/tools/ui/protocol-tools.d.ts.map +1 -1
  148. package/dist/tools/ui/protocol-tools.js +54 -1
  149. package/dist/tools/ui/protocol-tools.js.map +1 -1
  150. package/dist/tools/web/web-tools.d.ts +8 -0
  151. package/dist/tools/web/web-tools.d.ts.map +1 -1
  152. package/dist/tools/web/web-tools.js +60 -10
  153. package/dist/tools/web/web-tools.js.map +1 -1
  154. package/package.json +3 -2
@@ -1,10 +1,46 @@
1
1
  import { resolveLivePermissionMode } from "./permissions.js";
2
+ import { sanitizeForLog } from "../security.js";
2
3
  import { parsePartialJson } from "./stream-orchestrator.js";
3
4
  import { clipTrajectoryEvent } from "./telemetry.js";
4
5
  import { createToolGuardState, runToolGuards, } from "./tool-guards.js";
6
+ import { buildDualLayerContent, buildInteractionResultContent, buildResultAppendix, digestApprovalDecision, digestApprovalGranted, digestCancel, digestTimeout, } from "./result-digest.js";
7
+ import { resolveInteractionResultSchema } from "./action-envelope.js";
8
+ /** 执行段事件队列:结果事件按完成时序即时流出,不阻塞等待整批 */
9
+ class AsyncEventQueue {
10
+ items = [];
11
+ waiting = [];
12
+ closed = false;
13
+ push(item) {
14
+ this.items.push(item);
15
+ this.notify();
16
+ }
17
+ /** 生产端收尾:唤醒等待中的消费端让 drain 退出 */
18
+ close() {
19
+ this.closed = true;
20
+ this.notify();
21
+ }
22
+ notify() {
23
+ const waiters = this.waiting.splice(0);
24
+ for (const resolve of waiters)
25
+ resolve();
26
+ }
27
+ /** 生成器式排空:有事件即流出;close 且队空后结束 */
28
+ async *drain() {
29
+ for (;;) {
30
+ while (this.items.length > 0) {
31
+ yield this.items.shift();
32
+ }
33
+ if (this.closed)
34
+ return;
35
+ await new Promise((resolve) => this.waiting.push(resolve));
36
+ }
37
+ }
38
+ }
5
39
  export async function* executeToolCallStep(deps, input) {
6
- const { calls, runSignal, workspace, sessionId, effectiveMode, sessionPermissionAtStart, approvalTimeoutMs, bashTimeoutCeilingMs, getContentLength, accumulatedCards, messages, telemetry, } = input;
7
- // 逐个执行工具调用
40
+ const { calls, runSignal, workspace, sessionId, effectiveMode, sessionPermissionAtStart, approvalTimeoutMs, bashTimeoutCeilingMs, getContentLength, accumulatedCards, messages, } = input;
41
+ const decisions = [];
42
+ const toExecute = [];
43
+ /* ================= Phase A:决策段(串行,事件实时) ================= */
8
44
  for (const call of calls) {
9
45
  if (runSignal.aborted)
10
46
  break;
@@ -13,9 +49,12 @@ export async function* executeToolCallStep(deps, input) {
13
49
  parsedArgs = JSON.parse(call.argumentsStr || "{}");
14
50
  }
15
51
  catch {
52
+ // TASK-101:partial JSON 静默修复可观测化——修复即发 ops 事件(不再无声吞掉格式错误)
16
53
  parsedArgs = parsePartialJson(call.argumentsStr) || {};
54
+ deps.ops.partialRepair(call.name);
17
55
  }
18
- console.log(`[Vuagent Tool] Executing tool [${call.name}] args:`, parsedArgs);
56
+ // TASK-089:args 日志经脱敏——密钥样键名掩码、长字符串(文件内容/base64)截断
57
+ console.log(`[Vuagent Tool] Executing tool [${call.name}] args: ${sanitizeForLog(parsedArgs)}`);
19
58
  yield {
20
59
  type: "tool_call_executing",
21
60
  toolCallId: call.id,
@@ -36,6 +75,15 @@ export async function* executeToolCallStep(deps, input) {
36
75
  },
37
76
  };
38
77
  accumulatedCards.push(callCard);
78
+ const decision = {
79
+ call,
80
+ parsedArgs,
81
+ isError: false,
82
+ effectiveParsedArgs: {},
83
+ callCard,
84
+ events: [],
85
+ };
86
+ decisions.push(decision);
39
87
  const toolDef = deps.toolRegistry.get(call.name);
40
88
  const toolCfg = await deps.toolConfigRepo.get(call.name);
41
89
  // TASK-012 权限仲裁(评审 P0-2 修复):
@@ -66,17 +114,17 @@ export async function* executeToolCallStep(deps, input) {
66
114
  workspacePermission: workspace.permission,
67
115
  mode,
68
116
  parsedArgs,
69
- validateParams: (name, args) => deps.toolRegistry.validateParams(name, args),
117
+ validateParams: deps.toolRegistry.validateParams.bind(deps.toolRegistry),
70
118
  bashTimeoutCeilingMs,
71
119
  };
72
120
  const guardState = createToolGuardState();
73
121
  await runToolGuards(guardCtx, guardState);
74
122
  let executionResult = guardState.executionResult;
75
- let isError = guardState.isError;
76
- let errorMessage = guardState.errorMessage;
123
+ decision.isError = guardState.isError;
124
+ decision.errorMessage = guardState.errorMessage;
77
125
  const requiresApproval = guardState.requiresApproval;
78
126
  // HITL 拦截机制 (仅在需要人工审批且未被只读限制时进入)
79
- if (requiresApproval && !isError) {
127
+ if (requiresApproval && !decision.isError) {
80
128
  // 登记审批卡片进入持久化记录表
81
129
  // contentOffset:审批挂起发生时的正文长度,前端据此把审批卡重建回文本流中的真实位置
82
130
  const approvalCard = {
@@ -115,6 +163,8 @@ export async function* executeToolCallStep(deps, input) {
115
163
  args: parsedArgs,
116
164
  timeoutMs: approvalTimeoutMs,
117
165
  };
166
+ // TASK-091:挂起窗口前强制落盘(挂起可达 approvalTimeoutMs=180s,期间崩溃须留痕)
167
+ await input.beforeSuspend?.();
118
168
  const userAction = await actionPromise;
119
169
  // 审批完成后立即同步卡片决策状态,保证后续持久化与重连完全一致
120
170
  approvalCard.data.status = userAction.approved ? "approved" : "denied";
@@ -126,127 +176,395 @@ export async function* executeToolCallStep(deps, input) {
126
176
  payload: userAction,
127
177
  };
128
178
  if (!userAction.approved) {
129
- isError = true;
130
- errorMessage = `操作被用户驳回: ${userAction.note || userAction.reason || "未批准"}`;
131
- executionResult = { approved: false, reason: errorMessage };
179
+ // TASK-089(契约 TASK-B,预期行为变更):审批驳回从 `Error: 操作被用户驳回...`
180
+ // 迁移为信封摘要——cancel/deny 语义是用户的合法意图而非系统错误
181
+ // (设计文档 §3「cancel 是一等公民」),isError=false、不进入沙箱执行。
182
+ decision.interactionContent = digestApprovalDecision({
183
+ toolName: call.name,
184
+ envelope: userAction.envelope,
185
+ reason: userAction.reason,
186
+ note: userAction.note,
187
+ timeoutMs: approvalTimeoutMs,
188
+ });
189
+ executionResult = {
190
+ approved: false,
191
+ reason: userAction.reason,
192
+ note: userAction.note,
193
+ ...(userAction.envelope ? { envelope: userAction.envelope } : {}),
194
+ };
195
+ decision.earlyResult = executionResult;
196
+ }
197
+ else if (toolDef?.interaction && userAction.envelope) {
198
+ // TASK-089:声明 interaction 的工具(L1 审批卡等)——批准路径的结果消息
199
+ // 走「语义摘要 + JSON 附录」双层 content(信封是用户决策的事实来源):
200
+ // L1 用审批决策摘要;L2/L3 用 §4.1 表单摘要(词汇表 = resultSchema)。
201
+ if (toolDef.interaction.level === "L2" || toolDef.interaction.level === "L3") {
202
+ decision.interactionContent = buildInteractionResultContent({
203
+ title: call.name,
204
+ envelope: userAction.envelope,
205
+ interaction: toolDef.interaction,
206
+ });
207
+ }
208
+ else {
209
+ const granted = digestApprovalGranted({
210
+ toolName: call.name,
211
+ envelope: userAction.envelope,
212
+ note: userAction.note,
213
+ });
214
+ decision.interactionContent =
215
+ userAction.envelope.kind === "submit"
216
+ ? buildDualLayerContent(granted, buildResultAppendix(userAction.envelope.values, toolDef.interaction.resultSchema))
217
+ : granted;
218
+ }
132
219
  }
133
220
  }
134
- // 若未被驳回,在沙箱中执行工具(超时策略已由守卫链裁决:
135
- // executorTimeoutMs 与 bash 钳制后入参见 guardState.effectiveParsedArgs)
136
- let toolDurationMs = 0;
137
- if (!isError) {
138
- parsedArgs = guardState.effectiveParsedArgs;
139
- const ctx = {
140
- toolCallId: call.id,
221
+ // TASK-092(契约 TASK-E):L2/L3 值采集挂起——「无审批挂起」新路径。
222
+ // 挂起由 interaction.level 驱动,与 HITL 审批守卫(requiresApproval)解耦:
223
+ // 「L2 挂起≠审批」——tool-guards 的 approvalDecision 不命中本类工具
224
+ // (ui_form:requiresApproval=false、riskLevel=low),任何权限模式下都直接
225
+ // 挂起等待填写,不产生审批卡、不评估高风险策略;超时的语义归属按
226
+ // interaction.timeoutMeaning(L2 缺省 cancel,设计文档 §6 状态机)。
227
+ // 与审批路径的组合:若某组件同时声明 requiresApproval(当前无此类成员),
228
+ // 审批挂起先于本段串行执行(先过人、再收值),不并行嵌套。
229
+ //
230
+ // Phase 3(L3 patch 运行时):L3 协作组件的挂起由模型入参 collaborative
231
+ // 驱动(interaction 恒声明 L3,但仅在 parsedArgs.collaborative === true 时
232
+ // 挂起等待用户协作修改——patch 增量由路由 PatchStash 暂存,不唤醒本协程;
233
+ // 缺省 false 走纯展示沙箱执行路径,行为逐字节不变)。
234
+ if (!decision.isError &&
235
+ decision.earlyResult === undefined &&
236
+ toolDef?.interaction !== undefined &&
237
+ (toolDef.interaction.level === "L2" ||
238
+ (toolDef.interaction.level === "L3" && parsedArgs.collaborative === true))) {
239
+ const formInteraction = toolDef.interaction;
240
+ const actionPromise = deps.actionHub.waitForAction(call.id, {
241
+ toolName: call.name,
141
242
  args: parsedArgs,
142
- workspace,
143
- actionHub: deps.actionHub,
144
- abortSignal: runSignal,
145
- };
146
- const execRes = await deps.toolRegistry.execute(call.name, ctx, guardState.executorTimeoutMs);
147
- isError = execRes.isError;
148
- executionResult = execRes.result;
149
- errorMessage = execRes.error;
150
- toolDurationMs = execRes.durationMs;
151
- }
152
- {
153
- const ev = telemetry.recordEvent({
154
- at: Date.now(),
155
- lane: "tool",
156
- role: "tool",
157
- title: `工具执行: ${call.name}`,
158
- detail: JSON.stringify(parsedArgs),
159
- result: isError ? errorMessage : JSON.stringify(executionResult),
243
+ timeoutMs: approvalTimeoutMs,
244
+ sessionId,
160
245
  });
161
- yield { type: "traj", event: clipTrajectoryEvent(ev) };
162
- }
163
- // TASK-051:工具结果运维事件(含禁用/驳回/执行失败三类非 ok 路径)
164
- deps.ops.toolResult({
165
- tool: call.name,
166
- ok: !isError,
167
- durationMs: toolDurationMs,
168
- error: isError ? errorMessage : undefined,
169
- });
170
- console.log(`[Vuagent Tool] Tool [${call.name}] result (error=${isError})`);
171
- yield {
172
- type: "tool_call_result",
173
- toolCallId: call.id,
174
- toolName: call.name,
175
- status: isError ? "error" : "done",
176
- data: executionResult,
177
- error: errorMessage,
178
- };
179
- // TASK-006:收敛调用链卡片终态并派生持久化卡片
180
- callCard.data.status = isError ? "error" : "done";
181
- callCard.data.result = executionResult;
182
- callCard.data.error = errorMessage;
183
- callCard.data.duration = callCard.data.startedAt
184
- ? Date.now() - callCard.data.startedAt
185
- : undefined;
186
- // bash_run:终端卡持久化原始输出
187
- if (call.name === "bash_run") {
246
+ console.log(`[Vuagent Tool] Suspended for form interaction: [${call.name}], actionId=${call.id}`);
247
+ yield {
248
+ type: "suspended",
249
+ actionId: call.id,
250
+ toolName: call.name,
251
+ args: parsedArgs,
252
+ timeoutMs: approvalTimeoutMs,
253
+ };
254
+ // 评审 R-2 修复(表单卡历史恢复):与审批路径对称,把表单卡推入持久化
255
+ // 卡片集合——否则表单卡只能靠活流 suspended 事件重建,刷新/事件缓冲裁剪
256
+ // 后从会话里消失(跨会话收件箱还挂着「待填写」但消息流内无卡可填)。
257
+ // 复用 ui 卡通道(type:"ui" + component:"ui_form"),Console 历史映射归一
258
+ // 为 form 卡渲染;status 由 updateSessionCards 在唤醒时回写。
188
259
  accumulatedCards.push({
189
- id: `term-${call.id}`,
190
- type: "terminal",
260
+ id: `ui-${call.id}`,
261
+ type: "ui",
191
262
  data: {
192
- title: `终端执行: ${call.name}`,
193
- lines: [
194
- { text: `$ [状态: ${isError ? "error" : "done"}]`, kind: "cmd" },
195
- {
196
- text: typeof executionResult === "string"
197
- ? executionResult
198
- : JSON.stringify(executionResult || errorMessage || ""),
199
- kind: isError ? "err" : "stdout",
200
- },
201
- ],
263
+ component: "ui_form",
264
+ props: parsedArgs,
265
+ actionId: call.id,
266
+ status: "pending",
202
267
  contentOffset: getContentLength(),
203
268
  },
204
269
  });
270
+ // 挂起窗口前强制落盘(与审批路径同口径:挂起可达 180s,期间崩溃须留痕)
271
+ await input.beforeSuspend?.();
272
+ const userAction = await actionPromise;
273
+ yield {
274
+ type: "resumed",
275
+ actionId: call.id,
276
+ payload: userAction,
277
+ };
278
+ // resultSchema 由 fields 派生(设计文档 §7:不允许模型声明)——
279
+ // 与路由边界校验同源(resolveInteractionResultSchema 共享解析口径);
280
+ // 摘要/附录据此驱动词汇表、enum label 回映与 secret 打码。
281
+ // 此时 envelope.values 的 secret 字段已在路由边界剥离为 { ref, masked } 占位
282
+ // (core/secret-store.ts),摘要/附录/台账/落库只见占位。
283
+ const formResultSchema = resolveInteractionResultSchema(formInteraction, parsedArgs);
284
+ const formTitle = typeof parsedArgs.title === "string" && parsedArgs.title.trim()
285
+ ? parsedArgs.title
286
+ : call.name;
287
+ const formInteractionWithSchema = {
288
+ ...formInteraction,
289
+ resultSchema: formResultSchema,
290
+ };
291
+ if (userAction.envelope?.kind === "submit") {
292
+ decision.interactionContent = buildInteractionResultContent({
293
+ title: formTitle,
294
+ envelope: userAction.envelope,
295
+ interaction: formInteractionWithSchema,
296
+ });
297
+ executionResult = {
298
+ rendered: true,
299
+ component: call.name,
300
+ props: {
301
+ ...parsedArgs,
302
+ values: userAction.envelope.values,
303
+ status: "submitted",
304
+ },
305
+ };
306
+ }
307
+ else if (userAction.envelope?.kind === "cancel" || userAction.reason === "aborted") {
308
+ // cancel 是一等公民而非错误(设计文档 §3):正常结果,isError=false
309
+ decision.interactionContent = digestCancel({
310
+ title: formTitle,
311
+ reason: (userAction.envelope?.kind === "cancel" ? userAction.envelope.reason : undefined) ??
312
+ userAction.note,
313
+ });
314
+ executionResult = {
315
+ rendered: true,
316
+ component: call.name,
317
+ props: { ...parsedArgs, status: "cancelled" },
318
+ };
319
+ }
320
+ else {
321
+ // 超时(服务端裁决,无信封——不允许客户端伪造超时)
322
+ decision.interactionContent = digestTimeout({
323
+ title: formTitle,
324
+ meaning: formInteraction.timeoutMeaning ?? "cancel",
325
+ timeoutMs: approvalTimeoutMs,
326
+ });
327
+ executionResult = {
328
+ rendered: true,
329
+ component: call.name,
330
+ props: { ...parsedArgs, status: "timeout" },
331
+ };
332
+ }
333
+ decision.earlyResult = executionResult;
205
334
  }
206
- // fs_edit 自然投影:成功编辑时派发代码差异卡片 (Diff),免除模型调用伪工具 ui_code_diff 的负担
207
- if (call.name === "fs_edit" && !isError) {
208
- accumulatedCards.push({
209
- id: `diff-${call.id}`,
210
- type: "diff",
211
- data: {
212
- file: String(parsedArgs.filePath || ""),
213
- oldCode: String(parsedArgs.oldString || ""),
214
- newCode: String(parsedArgs.newString || ""),
215
- view: "unified",
216
- contentOffset: getContentLength(),
217
- },
335
+ if (decision.isError) {
336
+ // 早败路径(守卫拦截):结果事件即时实时发出(串行口径与旧行为一致);
337
+ // 结果消息延迟到 Phase C 按 call 序归位
338
+ decision.earlyResult = executionResult;
339
+ decision.resultMessage = {
340
+ role: "tool",
341
+ tool_call_id: call.id,
342
+ name: call.name,
343
+ content: `Error: ${decision.errorMessage}`,
344
+ };
345
+ finalizeAndEmit(deps, input, decision, true, executionResult, decision.errorMessage, 0);
346
+ for (const event of decision.events)
347
+ yield event;
348
+ decision.events.length = 0;
349
+ }
350
+ else if (decision.earlyResult !== undefined) {
351
+ // 审批驳回早收(TASK-089 非错误通道):摘要消息由 finalizeAndEmit 装配
352
+ // (interactionContent 优先),事件即时流出;不进入沙箱执行段
353
+ finalizeAndEmit(deps, input, decision, false, executionResult, undefined, 0);
354
+ for (const event of decision.events)
355
+ yield event;
356
+ decision.events.length = 0;
357
+ }
358
+ else {
359
+ decision.executorTimeoutMs = guardState.executorTimeoutMs;
360
+ decision.effectiveParsedArgs = guardState.effectiveParsedArgs;
361
+ toExecute.push(decision);
362
+ }
363
+ }
364
+ /* ================= Phase B:执行段(并行/串行双形态) ================= */
365
+ if (toExecute.length > 0) {
366
+ if (!input.parallelTools || toExecute.length <= 1) {
367
+ // 串行形态(开关关闭 / 单工具):与旧行为逐字节一致
368
+ for (const decision of toExecute) {
369
+ await runSandboxExec(deps, input, decision);
370
+ for (const event of decision.events)
371
+ yield event;
372
+ decision.events.length = 0;
373
+ }
374
+ }
375
+ else {
376
+ // 并行形态分组(评审 C3/#3):
377
+ // - 读类工具按名字互斥并行(同名串行,保守口径不变);
378
+ // - 写类工具(writesWorkspace=true,见 HarnessTool 声明)统一并入单一串行写组,
379
+ // 且与「所有其他组」互斥(先写后读屏障序)——跨名写并行(如 fs_write + bash_run)
380
+ // 会竞态写坏工作区,写与读并行则读到撕裂状态;
381
+ // 未声明 writesWorkspace 的工具按读类处理(写副作用必须显式声明 true)。
382
+ const groups = new Map();
383
+ let writesGroup;
384
+ for (const decision of toExecute) {
385
+ const isWrite = deps.toolRegistry.get(decision.call.name)?.writesWorkspace === true;
386
+ if (isWrite) {
387
+ writesGroup ??= [];
388
+ writesGroup.push(decision);
389
+ continue;
390
+ }
391
+ const group = groups.get(decision.call.name) ?? [];
392
+ group.push(decision);
393
+ groups.set(decision.call.name, group);
394
+ }
395
+ const queue = new AsyncEventQueue();
396
+ const runGroup = async (group) => {
397
+ for (const decision of group) {
398
+ await runSandboxExec(deps, input, decision);
399
+ for (const event of decision.events)
400
+ queue.push(event);
401
+ decision.events.length = 0;
402
+ }
403
+ };
404
+ // C3 修复:收尾用 finally——任一分支失败时队列也要关闭,让 drain 正常结束、
405
+ // 生成器走到 `await work` 把原始错误重抛给上层(对齐串行路径轮次落 error 语义)。
406
+ // 此前 `.then(() => queue.close())` 在失败路径不关闭队列,drain 永久挂起。
407
+ const work = (async () => {
408
+ if (writesGroup) {
409
+ // 屏障序:写组独占先执行(执行期并发=1),结束后读组再按名字互斥并行
410
+ await runGroup(writesGroup);
411
+ }
412
+ await Promise.all([...groups.values()].map(runGroup));
413
+ })().finally(() => {
414
+ queue.close();
218
415
  });
416
+ yield* queue.drain();
417
+ await work;
219
418
  }
220
- // ui_* 契约工具:持久化通用 {component, props} 载荷,前端 CardRenderer 动态分发
221
- // (审批卡由 HITL 流负责、agent_plan 由 turn.plan 负责此处不重复落卡)
222
- const renderResult = !isError && executionResult && typeof executionResult === "object"
223
- ? executionResult
224
- : null;
225
- if (renderResult?.rendered &&
226
- typeof renderResult.component === "string" &&
227
- renderResult.component !== "ui_approval_card" &&
228
- renderResult.component !== "ui_agent_plan") {
229
- accumulatedCards.push({
230
- id: `ui-${call.id}`,
231
- type: "ui",
419
+ }
420
+ /* ================= Phase C:结果消息按 call 序归位 ================= */
421
+ for (const decision of decisions) {
422
+ if (decision.resultMessage) {
423
+ messages.push(decision.resultMessage);
424
+ }
425
+ }
426
+ }
427
+ /**
428
+ * 沙箱执行(Phase B 单工具):registry.execute(超时策略已由守卫链裁决)→
429
+ * 结果归账 → finalizeAndEmit(事件缓冲进 decision.events,由调用方按时机流出)。
430
+ */
431
+ async function runSandboxExec(deps, input, decision) {
432
+ const ctx = {
433
+ toolCallId: decision.call.id,
434
+ args: decision.effectiveParsedArgs,
435
+ workspace: input.workspace,
436
+ actionHub: deps.actionHub,
437
+ abortSignal: input.runSignal,
438
+ };
439
+ const execRes = await deps.toolRegistry.execute(decision.call.name, ctx, decision.executorTimeoutMs);
440
+ finalizeAndEmit(deps, input, decision, execRes.isError, execRes.result, execRes.error, execRes.durationMs ?? 0);
441
+ }
442
+ /**
443
+ * 结果归账与事件装配(双路径共用):
444
+ * traj 遥测事件 → ops 运维事件 → 日志 → tool_call_result 事件 → 卡片终态收敛
445
+ * (调用链卡原地收敛 + bash 终端卡 + fs_edit 差异卡 + ui 契约卡)→ 结果消息。
446
+ * 事件写入 decision.events 缓冲(不直接 yield),时序由生成器按路径决定。
447
+ */
448
+ function finalizeAndEmit(deps, input, decision, isError, executionResult, errorMessage, toolDurationMs) {
449
+ const { call, callCard, parsedArgs } = decision;
450
+ const { telemetry, accumulatedCards, getContentLength } = input;
451
+ {
452
+ const ev = telemetry.recordEvent({
453
+ at: Date.now(),
454
+ lane: "tool",
455
+ role: "tool",
456
+ title: `工具执行: ${call.name}`,
457
+ detail: JSON.stringify(parsedArgs),
458
+ result: isError ? errorMessage : JSON.stringify(executionResult),
459
+ });
460
+ decision.events.push({ type: "traj", event: clipTrajectoryEvent(ev) });
461
+ }
462
+ // TASK-051:工具结果运维事件(含禁用/驳回/执行失败三类非 ok 路径)
463
+ deps.ops.toolResult({
464
+ tool: call.name,
465
+ ok: !isError,
466
+ durationMs: toolDurationMs,
467
+ error: isError ? errorMessage : undefined,
468
+ });
469
+ console.log(`[Vuagent Tool] Tool [${call.name}] result (error=${isError})`);
470
+ decision.events.push({
471
+ type: "tool_call_result",
472
+ toolCallId: call.id,
473
+ toolName: call.name,
474
+ status: isError ? "error" : "done",
475
+ data: executionResult,
476
+ error: errorMessage,
477
+ });
478
+ // TASK-006:收敛调用链卡片终态并派生持久化卡片
479
+ callCard.data.status = isError ? "error" : "done";
480
+ callCard.data.result = executionResult;
481
+ callCard.data.error = errorMessage;
482
+ callCard.data.duration = callCard.data.startedAt
483
+ ? Date.now() - callCard.data.startedAt
484
+ : undefined;
485
+ // bash_run:终端卡持久化原始输出
486
+ if (call.name === "bash_run") {
487
+ accumulatedCards.push({
488
+ id: `term-${call.id}`,
489
+ type: "terminal",
490
+ data: {
491
+ title: `终端执行: ${call.name}`,
492
+ lines: [
493
+ { text: `$ [状态: ${isError ? "error" : "done"}]`, kind: "cmd" },
494
+ {
495
+ text: typeof executionResult === "string"
496
+ ? executionResult
497
+ : JSON.stringify(executionResult || errorMessage || ""),
498
+ kind: isError ? "err" : "stdout",
499
+ },
500
+ ],
501
+ contentOffset: getContentLength(),
502
+ },
503
+ });
504
+ }
505
+ // fs_edit 自然投影:成功编辑时派发代码差异卡片 (Diff),免除模型调用伪工具 ui_code_diff 的负担
506
+ if (call.name === "fs_edit" && !isError) {
507
+ accumulatedCards.push({
508
+ id: `diff-${call.id}`,
509
+ type: "diff",
510
+ data: {
511
+ file: String(parsedArgs.filePath || ""),
512
+ oldCode: String(parsedArgs.oldString || ""),
513
+ newCode: String(parsedArgs.newString || ""),
514
+ view: "unified",
515
+ contentOffset: getContentLength(),
516
+ },
517
+ });
518
+ }
519
+ // ui_* 契约工具:持久化通用 {component, props} 载荷,前端 CardRenderer 动态分发
520
+ // (审批卡由 HITL 流负责、agent_plan 由 turn.plan 负责此处不重复落卡)
521
+ const renderResult = !isError && executionResult && typeof executionResult === "object"
522
+ ? executionResult
523
+ : null;
524
+ if (renderResult?.rendered &&
525
+ typeof renderResult.component === "string" &&
526
+ renderResult.component !== "ui_approval_card" &&
527
+ renderResult.component !== "ui_agent_plan") {
528
+ const payloadCard = {
529
+ id: `ui-${call.id}`,
530
+ type: "ui",
531
+ data: {
532
+ component: renderResult.component,
533
+ props: renderResult.props || {},
534
+ contentOffset: getContentLength(),
535
+ },
536
+ };
537
+ // ui_form(评审 R-2):挂起阶段已落 pending 卡(表单卡历史恢复)——完成后
538
+ // **原位更新**为已提交形态(values/status/actionId 供回写与归一),不追加重复卡
539
+ const pendingIdx = accumulatedCards.findIndex((c) => c.id === payloadCard.id && c.data?.component === "ui_form");
540
+ if (pendingIdx >= 0) {
541
+ accumulatedCards[pendingIdx] = {
542
+ ...payloadCard,
232
543
  data: {
233
- component: renderResult.component,
544
+ ...payloadCard.data,
234
545
  props: renderResult.props || {},
235
- contentOffset: getContentLength(),
546
+ status: "submitted",
547
+ actionId: call.id,
236
548
  },
237
- });
549
+ };
550
+ }
551
+ else {
552
+ accumulatedCards.push(payloadCard);
238
553
  }
239
- // 结果喂回上下文
240
- messages.push({
241
- role: "tool",
242
- tool_call_id: call.id,
243
- name: call.name,
244
- content: isError
245
- ? `Error: ${errorMessage}`
246
- : typeof executionResult === "string"
247
- ? executionResult
248
- : JSON.stringify(executionResult),
249
- });
250
554
  }
555
+ // 结果消息(Phase C 按 call 序归位)
556
+ // TASK-089:声明 interaction 的工具/审批驳回路径优先使用双层 content
557
+ // (语义摘要 + JSON 附录);其余工具按旧规则构造,逐字节不变
558
+ decision.resultMessage = {
559
+ role: "tool",
560
+ tool_call_id: call.id,
561
+ name: call.name,
562
+ content: isError
563
+ ? `Error: ${errorMessage}`
564
+ : decision.interactionContent ??
565
+ (typeof executionResult === "string"
566
+ ? executionResult
567
+ : JSON.stringify(executionResult)),
568
+ };
251
569
  }
252
570
  //# sourceMappingURL=tool-step-executor.js.map