minimal-agent 0.18.10 → 0.18.12

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/advisor/advisorCoordinator.js +30 -6
  3. package/src/advisor/advisorCoordinator.ts +23 -6
  4. package/src/advisor/deliveryReview.js +23 -0
  5. package/src/advisor/deliveryReview.ts +22 -0
  6. package/src/advisor/presentation.js +3 -1
  7. package/src/advisor/presentation.ts +4 -1
  8. package/src/loop/README.md +44 -0
  9. package/src/loop/deliveryIntent.js +22 -0
  10. package/src/loop/deliveryIntent.ts +39 -0
  11. package/src/loop/messages.js +146 -0
  12. package/src/loop/messages.ts +166 -0
  13. package/src/loop/options.js +1 -0
  14. package/src/loop/options.ts +155 -0
  15. package/src/loop/progressStream.js +40 -0
  16. package/src/loop/progressStream.ts +44 -0
  17. package/src/loop/publication.js +94 -0
  18. package/src/loop/publication.ts +124 -0
  19. package/src/loop/requestPreparation.js +180 -0
  20. package/src/loop/requestPreparation.ts +226 -0
  21. package/src/loop/toolBatch.js +99 -0
  22. package/src/loop/toolBatch.ts +123 -0
  23. package/src/loop/toolExecutor.js +304 -0
  24. package/src/loop/toolExecutor.ts +363 -0
  25. package/src/loop/toolPresentation.js +135 -0
  26. package/src/loop/toolPresentation.ts +134 -0
  27. package/src/loop/toolSemantics.js +45 -0
  28. package/src/loop/toolSemantics.ts +51 -0
  29. package/src/loop.js +369 -1114
  30. package/src/loop.ts +480 -1380
  31. package/src/tools/advisor/advisor.js +5 -2
  32. package/src/tools/advisor/advisor.ts +6 -2
  33. package/src/tools/bash/semantics.js +33 -1
  34. package/src/tools/bash/semantics.ts +27 -1
  35. package/src/tools/toolPromptGuides.js +1 -1
  36. package/src/tools/toolPromptGuides.ts +1 -1
  37. package/src/tools/webfetch/pageSnapshot.js +56 -0
  38. package/src/tools/webfetch/pageSnapshot.ts +51 -0
  39. package/src/tools/webfetch/webfetch.js +77 -116
  40. package/src/tools/webfetch/webfetch.ts +70 -136
  41. package/src/types.ts +8 -0
package/src/loop.ts CHANGED
@@ -1,419 +1,122 @@
1
+ import { DELIVERY_CORRECTION_REMINDER, expectsFormalDelivery } from './loop/deliveryIntent.js';
2
+ import {
3
+ buildModelMessages,
4
+ evictPriorVisionShots,
5
+ injectVisionFollowups,
6
+ mergeToolCallDelta,
7
+ pushManualInterruptMarker,
8
+ pushQueuedInputMarker,
9
+ } from './loop/messages.js';
10
+ import type { RunQueryOptions } from './loop/options.js';
11
+ import { publishFinalAnswer } from './loop/publication.js';
12
+ import { prepareModelRequest } from './loop/requestPreparation.js';
13
+ import { executeToolBatch } from './loop/toolBatch.js';
14
+ import { createToolExecutor, type WorkerOutcome } from './loop/toolExecutor.js';
15
+ import { advisorSemanticsFor } from './loop/toolSemantics.js';
16
+ export { expectsFormalDelivery } from './loop/deliveryIntent.js';
17
+ export {
18
+ buildModelMessages,
19
+ SYSTEM_REMINDER_CLOSE,
20
+ SYSTEM_REMINDER_OPEN,
21
+ VISION_SHOT_MARKER,
22
+ } from './loop/messages.js';
23
+ export type { RunQueryOptions } from './loop/options.js';
24
+ export { friendlyToolDescription } from './loop/toolPresentation.js';
25
+ export { advisorSemanticsFor } from './loop/toolSemantics.js';
1
26
  /**
2
- * ============================================================
3
- * src/loop.ts —— Agent 主循环(query loop)
4
- * ------------------------------------------------------------
5
- * 这是整个 agent 的"心脏"。一句话描述:
6
- *
7
- * 用户说话 → 调 LLM → LLM 想调工具就执行工具 → 把结果喂回去 → 继续调 LLM →
8
- * 直到 LLM 不再调工具,输出最终回答。
9
- *
10
- * 和 kakadeai 主仓库 query.ts 用同样的 AsyncGenerator 模式:
11
- * - 函数是 async function*,可以 yield 各种事件给 UI
12
- * - UI 通过 for await 拿到事件,把它们映射到 React state
13
- *
14
- * 循环每轮(turn)做的事:
15
- * a. 自动压缩检查(防止 context 撑爆)
16
- * b. 调 LLM,把流式响应组装成完整的 assistant message
17
- * c. 如果 assistant 不调工具 → 结束,return
18
- * d. 否则并行执行所有工具调用(OpenAI 协议要求 tool 消息按 tool_calls 顺序回填)
19
- * e. 进入下一轮(让模型看到 tool_result 后继续推理)
20
- *
21
- * 失控保护:maxTurns(默认 200)。
22
- * 中断支持:AbortSignal 透传到 chat() 和 tool.call()。
23
- *
24
- * "工作过程显示"事件:
25
- * - stage_change:thinking / streaming / tool_executing / compacting
26
- * - reasoning:思维链流式增量(仅字符串型 field)
27
- * ============================================================
27
+ * Agent turn orchestrator. Owns conversation state and continuation decisions.
28
+ * Request preparation, tool execution/scheduling and final publication live in
29
+ * ./loop/. Host options and LoopEvent remain the public compatibility boundary.
30
+ * See ./loop/README.md for phase ownership and invariants.
28
31
  */
29
32
 
30
33
  import crypto from 'node:crypto';
31
- import { answerPreparationNotice } from './runtime/answerPreparation.js';
32
- import { finalAnswerMessages } from './runtime/finalAnswer.js';
33
- import { resolveOutputContract, toolsForResponsePhase } from './runtime/outputContract.js';
34
- import { needsDiagramPreparation, visualPresentation } from './prompts/visualPresentation.js';
35
- import { createLifecycleTrace } from './runtime/lifecycleTrace.js';
36
- import { conciseToolPath } from './runtime/toolDisplay.js';
37
- import { dirname, resolve } from 'node:path';
38
- import { loadProjectPromptInstructions } from './prompts/projectInstructions.js';
39
- import { resolveToolPath } from './tools/shared/fileUtils.js';
40
- import { invocationInstructions, invocationToolAllowed, type InvocationPolicy } from './runtime/invocationPolicy.js';
41
- import { needsInteractiveQuestion } from './tools/ask/routing.js';
42
- import { autoCompactIfNeeded, getCompactThreshold, shouldAutoCompact } from './context/compact.js';
43
- import { createConversationOptimizer } from './context/optimizeConversation.js';
34
+ import { resolve } from 'node:path';
35
+ import { AdvisorCoordinator } from './advisor/advisorCoordinator.js';
36
+ import { collectReviewContext } from './advisor/reviewContext.js';
37
+ import { configService } from './config/configService.js';
38
+ import { buildContextBudgetPlan } from './context/budgetPlan.js';
39
+ import { getCompactThreshold } from './context/compact.js';
40
+ import { assembleContextBundle, contextFragment, resizeContextBundle } from './context/contextBundle.js';
44
41
  import {
45
- microCompact,
46
- incrementTurn,
47
42
  expireOldEntries,
43
+ getToolResultPolicy,
44
+ incrementTurn,
45
+ microCompact,
48
46
  reclaimOldToolResults,
49
47
  resetCacheEdits,
50
- getToolResultPolicy,
51
48
  } from './context/microCompactLite.js';
52
- import {
53
- isPromptTooLongError,
54
- reactiveCompactIfApplicable,
55
- } from './context/reactiveCompact.js';
56
- import { snipCompactIfNeeded } from './context/snipCompact.js';
49
+ import { createConversationOptimizer } from './context/optimizeConversation.js';
50
+ import { isPromptTooLongError, reactiveCompactIfApplicable } from './context/reactiveCompact.js';
51
+ import { countMessagesTokens, estimateToolsTokens } from './context/tokenCounter.js';
57
52
  import { archiveToolResult } from './context/toolResultArchive.js';
58
- import {
59
- countMessagesTokens,
60
- countTextTokens,
61
- estimateToolsTokens,
62
- } from './context/tokenCounter.js';
63
- import { buildContextBudgetPlan, fitToolsForEmergency } from './context/budgetPlan.js';
64
- import { assembleContextBundle, contextFragment, resizeContextBundle, type ContextBundle } from './context/contextBundle.js';
53
+ import { validateFinalClaims } from './harness/claimValidation.js';
54
+ import { EvidenceLedger } from './harness/evidenceLedger.js';
55
+ import { StallGuard } from './harness/stallGuard.js';
65
56
  import { chat as defaultChat } from './llm/client.js';
66
57
  import { buildUserContent } from './multimodal.js';
67
- import type { SessionState } from './session/sessionState.js';
68
- import {
69
- ALL_TOOLS,
70
- executeTool as defaultExecuteTool,
71
- getToolByName,
72
- getToolGateDetails,
73
- } from './tools/index.js';
74
- import type { ToolGate } from './toolGate.js';
75
- import { createReadBudget } from './tools/shared/readBudget.js';
76
- import type {
77
- DeliverableManifest,
78
- ImageDetail,
79
- ImageInputSpec,
80
- LoopEvent,
81
- Message,
82
- Provider,
83
- Tool,
84
- ToolCall,
85
- ToolCallContext,
86
- ToolResult,
87
- TurnResourceUsage,
88
- } from './types.js';
89
- import { configService } from './config/configService.js';
58
+ import { delegationRuntimeGuidance } from './prompts/delegation.js';
59
+ import { capabilitiesForTools, enabledPolicyIds } from './prompts/policyRegistry.js';
60
+ import { loadProjectPromptInstructions } from './prompts/projectInstructions.js';
61
+ import { needsDiagramPreparation, visualPresentation } from './prompts/visualPresentation.js';
62
+ import { createAgentRuntimeContext } from './runtime/agentRuntimeContext.js';
63
+ import { answerPreparationNotice } from './runtime/answerPreparation.js';
64
+ import { invocationInstructions, invocationToolAllowed } from './runtime/invocationPolicy.js';
65
+ import { createLifecycleTrace } from './runtime/lifecycleTrace.js';
66
+ import { resolveOutputContract, toolsForResponsePhase } from './runtime/outputContract.js';
67
+ import { filterToolsForProvider } from './team/toolPolicy.js';
68
+ import { agentCoordinationContext, takeAgentNotifications } from './tools/agent/agentTaskService.js';
69
+ import { needsInteractiveQuestion } from './tools/ask/routing.js';
90
70
  import { capabilityForToolName } from './tools/capabilities.js';
91
- import { createEffectiveToolSet } from './tools/effectiveToolSet.js';
92
71
  import { classifyComputerAutomationIntent } from './tools/computeruse/computerIntent.js';
93
72
  import { recordComputerUseExposure } from './tools/computeruse/telemetryLog.js';
94
- import { filterToolsForProvider } from './team/toolPolicy.js';
73
+ import { createEffectiveToolSet } from './tools/effectiveToolSet.js';
74
+ import { ALL_TOOLS, executeTool as defaultExecuteTool } from './tools/index.js';
75
+ import { createReadBudget } from './tools/shared/readBudget.js';
95
76
  import { hydrateSessionWorktree } from './tools/worktree/sessionWorktree.js';
96
- import {
97
- capabilitiesForTools,
98
- enabledPolicyIds,
99
- } from './prompts/policyRegistry.js';
100
- import { EvidenceLedger } from './harness/evidenceLedger.js';
101
- import { StallGuard, type StallObservation } from './harness/stallGuard.js';
102
- import { validateFinalClaims } from './harness/claimValidation.js';
103
- import {
104
- AdvisorCoordinator,
105
- type AdvisorToolSemantics,
106
- } from './advisor/advisorCoordinator.js';
107
- import { toolEffectFor } from './tools/capabilities.js';
108
- import { isReadOnlyShellCommand, isVerificationShellCommand } from './tools/bash/semantics.js';
109
- import { collectReviewContext } from './advisor/reviewContext.js';
110
- import {
111
- createAgentRuntimeContext,
112
- type AgentRuntimeContext,
113
- } from './runtime/agentRuntimeContext.js';
77
+ import type { LoopEvent, Message, Tool, ToolCall, ToolCallContext, TurnResourceUsage } from './types.js';
114
78
  import { stripThinkBlocks } from './utils/stripThink.js';
115
- import { orderedPool } from './runtime/orderedPool.js';
116
- import { takeAgentNotifications, agentCoordinationContext } from './tools/agent/agentTaskService.js';
117
- import { delegationRuntimeGuidance } from './prompts/delegation.js';
118
- import { executionSegments } from './tools/executionSegments.js';
119
- import { acquireSubagentLease, normalizeWriteScopes } from './tools/agent/coordinator.js';
120
-
121
- const DELIVERY_ARTIFACT = '(?:文件|合同|协议|方案|文档|表格|报告|图片|图像|海报|幻灯片|PPT|PDF|代码|脚本|压缩包|网页|页面|HTML|DOCX|XLSX|CSV|ZIP)';
122
- const DELIVERY_ACTION = '(?:发送|(?<![开研])发|交付|提交|(?<!宣)传(?!统)|制作|生成|创建|导出|输出|修改|更新|完成|写|起草|做|设计|整理)';
123
- const ENGLISH_DELIVERY_ARTIFACT = '(?:file|contract|document|report|spreadsheet|workbook|slides?|presentation|pdf|image|code|script|archive|zip|html|webpage|website)';
124
- const ENGLISH_DELIVERY_ACTION = '(?:send|deliver|submit|provide|create|generate|export|update|modify|finish|produce|draft|write|make|build)';
125
-
126
- /** Whether this turn explicitly asks for a concrete artifact that should be formally delivered. */
127
- export function expectsFormalDelivery(input: string): boolean {
128
- // Questions about producing artifacts are not instructions to produce them.
129
- // Evaluate clauses independently so “解释原因,然后生成报告” still delivers.
130
- const clauses = input.split(/[。!?!?;;\n]|然后|随后|并且/).filter(Boolean);
131
- return clauses.some(expectsDeliveryClause);
132
- }
133
-
134
- function expectsDeliveryClause(input: string): boolean {
135
- if (/为什么|为何|如何|怎么|怎样|是否|能否|能不能|不要|不必|无需|只(?:需|要)?(?:解释|分析|评估|讨论)|\b(?:why|how|whether|explain|analy[sz]e|discuss|do not|don't)\b/i.test(input)) return false;
136
- const compact = input.replace(/\s+/g, '');
137
- const chinese = new RegExp(
138
- `${DELIVERY_ACTION}(?:给)?我?.{0,24}${DELIVERY_ARTIFACT}|${DELIVERY_ARTIFACT}.{0,24}${DELIVERY_ACTION}(?:给)?我?|给我.{0,24}${DELIVERY_ARTIFACT}|${DELIVERY_ARTIFACT}.{0,24}给我`,
139
- 'i',
140
- );
141
- const english = new RegExp(
142
- `\\b${ENGLISH_DELIVERY_ACTION}\\b.{0,80}\\b${ENGLISH_DELIVERY_ARTIFACT}\\b|\\b${ENGLISH_DELIVERY_ARTIFACT}\\b.{0,80}\\b${ENGLISH_DELIVERY_ACTION}\\b`,
143
- 'i',
144
- );
145
- return chinese.test(compact) || english.test(input);
146
- }
147
-
148
- const DELIVERY_CORRECTION_REMINDER = `The user requested a concrete final deliverable, but no successful PresentResult call has been made.
149
- Do not repeat the answer or mention a path only. Call PresentResult now with the actual final files and/or final http(s) links.
150
- Submit only final outputs, never temporary scripts, unpacked assets, caches, or reference sources. If no valid result exists, explain that honestly without inventing one.`;
151
-
152
- /**
153
- * 每轮 LLM 请求都会带上工具 schema,但 countMessagesTokens 只数历史消息、
154
- * 漏了这部分 → 系统性低估。autoCompact 判定阈值时加上它才准。
155
- *
156
- * ⚠️ 必须懒求值而非模块顶层求值:Agent 工具引入了 tools/index → agent → loop →
157
- * tools/index 的模块环,若从 tools/index 一侧先进入,顶层求值 ALL_TOOLS 时它还在
158
- * TDZ(临时死区),启动即 ReferenceError。函数体内访问时模块图早已初始化完毕。
159
- */
160
- /**
161
- * 本轮**真正发出去的**工具 schema 估算 token 数。
162
- *
163
- * 曾经这里数的是 `ALL_TOOLS`,那是错的:每回合发给模型的是 `activeTools`,
164
- * 会被 `allowedTools`(工作流步骤 / 子 agent 收窄)、`subagents.enabled`、
165
- * `computerRun` 是否注入等条件过滤掉一部分。ComputerUse 单个工具的 schema
166
- * 实测就有 ~5800 token(全量 ~18000 的三分之一),在没暴露它的会话里照样
167
- * 被计入压缩阈值 → **压缩提前触发**;被 `allowed_tools` 收窄到两三个工具的
168
- * 子 agent 偏差更大。
169
- *
170
- * 缓存必须按工具集**键控**:模块级单值缓存配上按回合变化的工具集,会让所有
171
- * 后续回合都拿到第一回合那个数字 —— 比不缓存更糟,因为它错得很稳定。
172
- */
173
- const toolsSchemaTokensCache = new Map<string, number>();
174
- function getToolsSchemaTokens(tools: readonly Tool[], signature?: string): number {
175
- const key = signature ?? tools.map((t) => t.name).join(',');
176
- let cached = toolsSchemaTokensCache.get(key);
177
- if (cached === undefined) {
178
- cached = estimateToolsTokens(tools as Tool[]);
179
- toolsSchemaTokensCache.set(key, cached);
180
- }
181
- return cached;
182
- }
183
79
 
184
80
  /** 主工具循环的默认轮数上限。 */
185
81
  export const DEFAULT_MAX_TURNS = 200;
186
82
 
187
- export function advisorSemanticsFor(
188
- call: ToolCall,
189
- context?: ToolCallContext,
190
- tool?: Tool,
191
- // 默认 false:只有 advisor 检查点/记账(beforeTool、observeToolResult、
192
- // 持久化的 advisorMutatesWorkspace 标注)才传 true。工作区租约判定
193
- // (needsWorkspaceLease)必须保持严格定义不受影响——验证类命令仍可能写
194
- // 构建产物/缓存,并发场景下让它绕开租约会重新引入竞态。
195
- opts?: { treatVerificationAsReadOnly?: boolean },
196
- ): AdvisorToolSemantics {
197
- const definition = tool ?? getToolByName(call.function.name);
198
- const gate = context ? getToolGateDetails(call.function.name, call.function.arguments, context) : undefined;
199
- // Reuse the tool's side-effect contract, including shell/scripts, Trash and
200
- // generation tools. Shell tools refine their generic writable declaration
201
- // using the actual command; the same result is also used by the host gate.
202
- let isReadOnly = gate?.isReadOnly ?? definition?.isReadOnly ?? false;
203
- if (call.function.name === 'Agent') {
204
- try {
205
- const args = JSON.parse(call.function.arguments || '{}');
206
- isReadOnly = !args.resume_agent_id && (args.agent_type ?? 'explore') === 'explore';
207
- } catch { isReadOnly = false; }
208
- }
209
- if (call.function.name === 'Bash' || call.function.name === 'PowerShell') {
210
- try {
211
- const input = JSON.parse(call.function.arguments || '{}') as { command?: unknown };
212
- if (typeof input.command === 'string') {
213
- // 跑测试/构建/lint 只是核对现状,不该被当成"开始实施改动"而白白烧掉
214
- // pre-execution 检查点——即使它们可能写构建产物/缓存,不满足
215
- // isReadOnlyShellCommand 的并发安全定义(见 opts 注释,那个场景仍要严格)。
216
- isReadOnly =
217
- isReadOnlyShellCommand(input.command) ||
218
- (opts?.treatVerificationAsReadOnly === true &&
219
- isVerificationShellCommand(input.command));
220
- }
221
- } catch {
222
- // Malformed input is left writable; normal tool validation reports it.
223
- isReadOnly = false;
224
- }
225
- }
226
- const mutatesWorkspace = toolEffectFor(call.function.name, isReadOnly) === 'execution';
227
- return { mutatesWorkspace };
228
- }
229
-
230
- export interface RunQueryOptions {
231
- agentHandoff?: ToolCallContext['agentHandoff'];
232
- /** Generic embedded-task policy; omitted for ordinary conversation turns. */
233
- invocationPolicy?: InvocationPolicy;
234
- executionServices?: ToolCallContext['executionServices'];
235
- provider: Provider;
236
- /** Canonical host-issued trust context. Legacy fields below remain adapters. */
237
- runtimeContext?: AgentRuntimeContext;
238
- /** 历史会被 mutate(追加新消息、压缩时整体替换内容);调用方持同一引用 */
239
- history: Message[];
240
- /** Host mailbox: consume at model boundaries, never mutate an in-flight request. */
241
- takePendingMessages?: () => Message[];
242
- /** 最多多少轮(防止失控调工具) */
243
- maxTurns?: number;
244
- /**
245
- * 工作流 agent/llm 步的工具白名单:只把这些工具下发给模型并允许执行。
246
- * 缺省 = 当前宿主工具全集;空数组 = 无工具。
247
- */
248
- allowedTools?: string[];
249
- /** 调用方工具边界名称,仅用于准确解释越界调用;缺省表示宿主能力边界。 */
250
- toolBoundaryLabel?: string;
251
- /** Disable Advisor checkpoints for an explicitly read-only embedded node. */
252
- advisorCheckpoints?: boolean;
253
- /** Tools the host/workflow explicitly requires; emergency schema reduction preserves them. */
254
- requiredTools?: string[];
255
- /**
256
- * provider 原生结构化输出(`response_format.json_schema`),原样透传给 `chat()`。
257
- *
258
- * ⚠️ **只在本轮没有工具时才该传**:response_format 会强制**每一条** assistant
259
- * 消息都是 JSON,而工具调用轮的 assistant 消息带的是 tool_calls —— 两者互斥,
260
- * 同时给会让带工具的循环直接崩。工作流引擎因此只在 `llm()`(零工具)和
261
- * schema 修复轮(零工具)上传它;`agent()` 的结构化输出走「跑完再修复」那条路。
262
- *
263
- * Anthropic 格式的 provider 不支持,`chat()` 会在发请求前抛错 —— 所以它是
264
- * **加成**而不是地基,地基是引擎侧的「校验 + 有界修复」。
265
- */
266
- responseFormat?: {
267
- type: 'json_schema';
268
- json_schema: {
269
- name: string;
270
- schema: Record<string, unknown>;
271
- strict?: boolean;
272
- };
273
- };
274
- /**
275
- * Host-provided tool catalog. Production hosts normally omit this and use ALL_TOOLS;
276
- * tests and embedders with custom executors must provide matching schemas so the
277
- * model-visible catalog and execution boundary remain identical.
278
- */
279
- availableTools?: readonly Tool[];
280
- /** 用户取消 */
281
- signal?: AbortSignal;
282
- /**
283
- * 回调:宿主检查是否有排队输入需要在安全点处理。
284
- * loop只在安全检查点调用:每轮while开始时、工具全部执行完成后。
285
- * 返回true表示应该结束当前turn(自然return,不抛异常)。
286
- */
287
- hasQueuedInput?: () => boolean;
288
- /** Concurrent-safe tool throughput; defaults to 8, host may tune upward. */
289
- toolConcurrency?: number;
290
- /**
291
- * 回调:工具开始/结束执行,用于宿主跟踪运行中工具状态。
292
- */
293
- onToolStart?: (toolName: string, toolCallId: string) => void;
294
- onToolEnd?: (toolCallId: string, wasAborted: boolean) => void;
295
- /**
296
- * 多租户场景下注入隔离的 session 级状态;缺省走模块单例。
297
- * TUI / print(单进程单 session)不传即可;HTTP server per-request 必须传。
298
- */
299
- sessionState?: SessionState;
300
- /**
301
- * 注入 chat 实现(仅测试用)。
302
- *
303
- * 之前用 bun:test 的 mock.module 替换 llm/client.js 会进程全局污染所有跨文件
304
- * import;改用显式 DI 后,测试传 stub 进来即可,零污染。生产代码不需要传。
305
- */
306
- chat?: typeof defaultChat;
307
- /**
308
- * 注入 executeTool 实现(仅测试用)。同上,DI 而非 mock.module,零污染。
309
- */
310
- executeTool?: (
311
- name: string,
312
- rawArgsJson: string,
313
- signal?: AbortSignal,
314
- ctx?: ToolCallContext,
315
- ) => Promise<ToolResult>;
316
- /**
317
- * Trusted host persistence boundary for formal results. It runs after
318
- * PresentResult validates the files but before tool_end is published or the
319
- * result is appended to history. Throwing turns the tool call into a failure,
320
- * so a UI can never display an uncommitted delivery as durable.
321
- */
322
- commitFormalDelivery?: (input: {
323
- toolCallId: string;
324
- turnId: string;
325
- manifest: DeliverableManifest;
326
- }) => Promise<void>;
327
- /**
328
- * 工具执行闸门(通用机制,见 src/toolGate.ts):loop 在执行每个工具前
329
- * await 它拿放行/拒绝;拒绝时把 reason 当 tool_result 回填。内核零策略——审批语义
330
- * 全在宿主(如 gateway 跨机指令同意闸门)。缺省不传 = 全放行,行为不变。
331
- */
332
- toolGate?: ToolGate;
333
- /**
334
- * 仅对本次回合可见的系统上下文。它会随每次模型调用注入,但不会写入 history、
335
- * 会话文件或压缩摘要,适合项目事实、远程委托和附件概要等外部上下文。
336
- *
337
- * 注入到本轮用户消息的模型副本,不改变 UI 或持久化历史。
338
- */
339
- transientContext?: string;
340
- /** Structured transient fragments allow deterministic request-time degradation. */
341
- transientBundle?: ContextBundle;
342
- /** Provider cache routing for this conversation; never persisted. */
343
- promptCache?: import('./types.js').PromptCacheContext;
344
- /** 仅供宿主 UI 恢复附件卡片;不会发送给 LLM。 */
345
- userAttachments?: import('./types.js').MessageAttachmentRef[];
346
- /** Host-authorized files for typed workflow inputs; runtime-only paths. */
347
- inputResources?: readonly import('./types.js').InvocationResource[];
348
- /** Stable host-provided identity for the user message of this turn. */
349
- userMessageId?: string;
350
- /** Trusted local origin for every message created by this run. */
351
- messageProvenance?: import('./types.js').ConversationProvenance;
352
- /** Browser element chips are persisted for UI but stripped before provider calls. */
353
- userBrowserReferences?: import('./types.js').MessageBrowserReference[];
354
- /** 显式传入的图片附件(-p --image / stream-json images)。 */
355
- imageInputs?: ImageInputSpec[];
356
- /** 是否解析用户文本里的 @./image.png / 图片 URL。TUI 默认开启。 */
357
- parseInlineImages?: boolean;
358
- /** 图片 detail 默认值:low/default/high。 */
359
- imageDetail?: ImageDetail;
360
- /** OpenAI 兼容扩展:图片最长边像素。 */
361
- imageMaxLongSidePixel?: number;
362
- /** Host-provided browser ownership scope; never exposed to the model. */
363
- browserRun?: ToolCallContext['browserRun'];
364
- /** Host-provided native desktop-control scope; absent means ComputerUse is not exposed. */
365
- computerRun?: ToolCallContext['computerRun'];
366
- /** Trusted host-only human handoff bridge for native Computer Use. */
367
- computerIntervention?: ToolCallContext['computerIntervention'];
368
- memoryContext?: {
369
- access: import('./runtime/agentRuntimeContext.js').MemoryAccessInput;
370
- workspaceId?: string;
371
- sessionId?: string;
372
- };
373
- }
374
-
375
83
  /**
376
84
  * 执行一次"用户输入 → 模型回答完成"的完整流程。
377
85
  *
378
86
  * yield 出来的 LoopEvent 会被 UI 用来更新界面。
379
87
  */
380
- export async function* runQuery(
381
- userInput: string,
382
- options: RunQueryOptions,
383
- ): AsyncGenerator<LoopEvent, void, void> {
88
+ export async function* runQuery(userInput: string, options: RunQueryOptions): AsyncGenerator<LoopEvent, void, void> {
384
89
  const { provider, history, signal, sessionState } = options;
385
90
  // Tool screenshots are transient evidence for the tool continuation that produced them.
386
91
  // Never carry a prior turn's base64 image into a new user request.
387
92
  evictPriorVisionShots(history);
388
93
  const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
389
- const inferredDesktop = options.browserRun?.supervised === true ||
390
- options.browserRun?.viewer === 'desktop';
391
- const baseRuntimeContext = options.runtimeContext ?? createAgentRuntimeContext({
392
- surface: inferredDesktop ? 'desktop' : 'headless',
393
- ...(inferredDesktop ? { host: 'desktop' as const } : {}),
394
- profile: 'main',
395
- cwd: process.cwd(),
396
- workspaceId: options.memoryContext?.workspaceId,
397
- sessionId: options.memoryContext?.sessionId,
398
- owner: options.memoryContext?.access !== 'denied' ? 'local-owner' : 'untrusted',
399
- memoryAccess: options.memoryContext?.access ?? 'denied',
400
- interactiveAsk: false,
401
- browser: options.browserRun,
402
- computer: options.computerRun,
403
- computerIntervention: options.computerIntervention,
404
- toolGate: options.toolGate,
405
- });
406
- const computerIntent = baseRuntimeContext.computerIntent
407
- ?? classifyComputerAutomationIntent(userInput, sessionState?.computerAutomation);
94
+ const inferredDesktop = options.browserRun?.supervised === true || options.browserRun?.viewer === 'desktop';
95
+ const baseRuntimeContext =
96
+ options.runtimeContext ??
97
+ createAgentRuntimeContext({
98
+ surface: inferredDesktop ? 'desktop' : 'headless',
99
+ ...(inferredDesktop ? { host: 'desktop' as const } : {}),
100
+ profile: 'main',
101
+ cwd: process.cwd(),
102
+ workspaceId: options.memoryContext?.workspaceId,
103
+ sessionId: options.memoryContext?.sessionId,
104
+ owner: options.memoryContext?.access !== 'denied' ? 'local-owner' : 'untrusted',
105
+ memoryAccess: options.memoryContext?.access ?? 'denied',
106
+ interactiveAsk: false,
107
+ browser: options.browserRun,
108
+ computer: options.computerRun,
109
+ computerIntervention: options.computerIntervention,
110
+ toolGate: options.toolGate,
111
+ });
112
+ const computerIntent =
113
+ baseRuntimeContext.computerIntent ?? classifyComputerAutomationIntent(userInput, sessionState?.computerAutomation);
408
114
  const runtimeContext = createAgentRuntimeContext({
409
115
  ...baseRuntimeContext,
410
116
  computerIntent,
411
117
  });
412
118
  if (runtimeContext.computer) {
413
- void recordComputerUseExposure(
414
- computerIntent.needed,
415
- computerIntent.source,
416
- );
119
+ void recordComputerUseExposure(computerIntent.needed, computerIntent.source);
417
120
  }
418
121
  if (!computerIntent.needed && sessionState) delete sessionState.computerAutomation;
419
122
  // DI fallback:测试可传 stub,生产走真实模块单例
@@ -429,7 +132,9 @@ export async function* runQuery(
429
132
  const observedRuleScopes = new Map<string, string>();
430
133
  const pendingRuleScopes = new Set<string>();
431
134
  const transientFor = (tools: readonly Tool[]): string => {
432
- const opaque = [options.transientContext?.trim(), invocationInstructions(options.invocationPolicy)].filter(Boolean).join('\n\n');
135
+ const opaque = [options.transientContext?.trim(), invocationInstructions(options.invocationPolicy)]
136
+ .filter(Boolean)
137
+ .join('\n\n');
433
138
  const bundle = currentTransientBundle;
434
139
  if (!bundle) return opaque;
435
140
  const basePlan = buildContextBudgetPlan({
@@ -442,9 +147,8 @@ export async function* runQuery(
442
147
  0,
443
148
  basePlan.inputLimit - basePlan.historyTokens - basePlan.toolTokens - basePlan.transientTokens,
444
149
  );
445
- const selected = availableForBundle >= bundle.diagnostics.usedTokens
446
- ? bundle
447
- : resizeContextBundle(bundle, availableForBundle);
150
+ const selected =
151
+ availableForBundle >= bundle.diagnostics.usedTokens ? bundle : resizeContextBundle(bundle, availableForBundle);
448
152
  advisorContextBundle = selected;
449
153
  return [selected.text, opaque].filter(Boolean).join('\n\n');
450
154
  };
@@ -466,18 +170,43 @@ export async function* runQuery(
466
170
  const toolCallContext: ToolCallContext = {
467
171
  output,
468
172
  availableToolNames: () => currentEffectiveToolSet.names,
469
- executionServices: { ...options.executionServices, executeTool: executeToolFn, chat: chatFn, invocationPolicy: options.invocationPolicy },
173
+ executionServices: {
174
+ ...options.executionServices,
175
+ executeTool: executeToolFn,
176
+ chat: chatFn,
177
+ invocationPolicy: options.invocationPolicy,
178
+ },
470
179
  history,
471
180
  sessionState,
472
181
  advisorReviewContext: () => ({
473
182
  ...collectReviewContext(advisorContextBundle),
474
- constraints: [...collectReviewContext(advisorContextBundle).constraints,
475
- { id: 'execution.boundary', authority: 'host', content: JSON.stringify({ cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
476
- conversationMode: toolCallContext.conversationMode, profile: runtimeContext.profile,
477
- availableTools: [...currentEffectiveToolSet.names], invocation: invocationInstructions(options.invocationPolicy) }) }],
478
- omittedIds: [...new Set([...(currentTransientBundle?.diagnostics.omittedIds ?? []), ...(advisorContextBundle?.diagnostics.omittedIds ?? [])]),
479
- ...(options.transientContext ? ['legacy.transient-context:not-forwarded'] : [])],
480
- clippedIds: [...new Set([...(currentTransientBundle?.diagnostics.clippedIds ?? []), ...(advisorContextBundle?.diagnostics.clippedIds ?? [])])],
183
+ constraints: [
184
+ ...collectReviewContext(advisorContextBundle).constraints,
185
+ {
186
+ id: 'execution.boundary',
187
+ authority: 'host',
188
+ content: JSON.stringify({
189
+ cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
190
+ conversationMode: toolCallContext.conversationMode,
191
+ profile: runtimeContext.profile,
192
+ availableTools: [...currentEffectiveToolSet.names],
193
+ invocation: invocationInstructions(options.invocationPolicy),
194
+ }),
195
+ },
196
+ ],
197
+ omittedIds: [
198
+ ...new Set([
199
+ ...(currentTransientBundle?.diagnostics.omittedIds ?? []),
200
+ ...(advisorContextBundle?.diagnostics.omittedIds ?? []),
201
+ ]),
202
+ ...(options.transientContext ? ['legacy.transient-context:not-forwarded'] : []),
203
+ ],
204
+ clippedIds: [
205
+ ...new Set([
206
+ ...(currentTransientBundle?.diagnostics.clippedIds ?? []),
207
+ ...(advisorContextBundle?.diagnostics.clippedIds ?? []),
208
+ ]),
209
+ ],
481
210
  }),
482
211
  // Statistics only; consultations have no per-turn quota.
483
212
  advisorCalls: { used: 0 },
@@ -504,16 +233,17 @@ export async function* runQuery(
504
233
  promptCache: options.promptCache,
505
234
  };
506
235
 
507
-
508
236
  // 实际下发给模型的工具集:allowedTools 未传时给全量;
509
237
  // 传入数组时严格按数组过滤,[] 表示本轮不下发任何工具。
510
238
  // 同时约束模型可见工具和本循环实际执行的工具。
511
239
  const hostTools = filterToolsForProvider(options.availableTools ?? ALL_TOOLS, provider);
512
- const availableTools = hostTools.filter((tool) =>
513
- invocationToolAllowed(tool.name, options.invocationPolicy)
514
- && (tool.name !== 'Agent' || subagents.enabled)
515
- && (tool.name !== 'ComputerUse'
516
- || (runtimeContext.computer !== undefined && runtimeContext.computerIntent?.needed === true)));
240
+ const availableTools = hostTools.filter(
241
+ (tool) =>
242
+ invocationToolAllowed(tool.name, options.invocationPolicy) &&
243
+ (tool.name !== 'Agent' || subagents.enabled) &&
244
+ (tool.name !== 'ComputerUse' ||
245
+ (runtimeContext.computer !== undefined && runtimeContext.computerIntent?.needed === true)),
246
+ );
517
247
  const effectiveToolSet = createEffectiveToolSet({
518
248
  availableTools,
519
249
  runtime: runtimeContext,
@@ -521,10 +251,11 @@ export async function* runQuery(
521
251
  requiredNames: options.requiredTools,
522
252
  });
523
253
  const activeTools = effectiveToolSet.tools;
524
- const formalDeliveryRequired = explicitFileDeliveryRequested
525
- && runtimeContext.profile === 'main'
526
- && options.invocationPolicy?.delivery !== 'caller'
527
- && effectiveToolSet.names.has('PresentResult');
254
+ const formalDeliveryRequired =
255
+ explicitFileDeliveryRequested &&
256
+ runtimeContext.profile === 'main' &&
257
+ options.invocationPolicy?.delivery !== 'caller' &&
258
+ effectiveToolSet.names.has('PresentResult');
528
259
  let currentEffectiveToolSet = effectiveToolSet;
529
260
  const advisorCoordinator = new AdvisorCoordinator({
530
261
  history,
@@ -543,30 +274,39 @@ export async function* runQuery(
543
274
  const parts = [
544
275
  transientFor(activeTools),
545
276
  coordinationText,
546
- delegationRuntimeGuidance({ available: runtimeContext.profile === 'main' && currentEffectiveToolSet.names.has('Agent'),
547
- maxConcurrent: subagents.maxConcurrent, callsUsed: toolCallContext.agentCalls?.used ?? 0,
548
- maxCalls: toolCallContext.agentCalls?.max ?? 0 }),
277
+ delegationRuntimeGuidance({
278
+ available: runtimeContext.profile === 'main' && currentEffectiveToolSet.names.has('Agent'),
279
+ maxConcurrent: subagents.maxConcurrent,
280
+ callsUsed: toolCallContext.agentCalls?.used ?? 0,
281
+ maxCalls: toolCallContext.agentCalls?.max ?? 0,
282
+ }),
549
283
  diagramPreparationAttempted ? visualPresentation(output) : '',
550
- delegationCorrectionAttempted ? '本轮必要子任务尚未验收或接管完成。先读取结果、等待运行任务或完成接力,使用 AgentResolve 记录判断;若确实无法完成,明确报告缺口,不声称全部完成。' : '',
551
- askCorrectionAttempted ? '当前交互宿主支持 AskUserQuestion。若仍需用户选择或补充,请调用该工具一次只问一个问题,等待答案后继续;不要仅在正文列问后停止。若没有待决事项则正常回答,不必提问。' : '',
552
- emptyResponseRecoveryAttempted ? `上一次模型响应没有可交付正文(${emptyResponseRecoveryReason})。请基于已有历史和工具结果继续完成任务:信息充分则给出实质结论,不充分则继续必要操作或明确缺口。不要重复已经完成的调查或有副作用的操作;不要把未完成的任务说成完成。已有顾问意见继续有效,无需仅因恢复而再次咨询。` : '',
284
+ delegationCorrectionAttempted
285
+ ? '本轮必要子任务尚未验收或接管完成。先读取结果、等待运行任务或完成接力,使用 AgentResolve 记录判断;若确实无法完成,明确报告缺口,不声称全部完成。'
286
+ : '',
287
+ askCorrectionAttempted
288
+ ? '当前交互宿主支持 AskUserQuestion。若仍需用户选择或补充,请调用该工具一次只问一个问题,等待答案后继续;不要仅在正文列问后停止。若没有待决事项则正常回答,不必提问。'
289
+ : '',
290
+ emptyResponseRecoveryAttempted
291
+ ? `上一次模型响应没有可交付正文(${emptyResponseRecoveryReason})。请基于已有历史和工具结果继续完成任务:信息充分则给出实质结论,不充分则继续必要操作或明确缺口。不要重复已经完成的调查或有副作用的操作;不要把未完成的任务说成完成。已有顾问意见继续有效,无需仅因恢复而再次咨询。`
292
+ : '',
553
293
  deliveryCorrectionAttempted && !resultPresented ? DELIVERY_CORRECTION_REMINDER : '',
554
294
  advisorAvailable ? advisorCoordinator.transientReminder() : '',
555
- advisorAvailable
556
- ? advisorCoordinator.usageLine(toolCallContext.advisorCalls!.used)
557
- : '',
295
+ advisorAvailable ? advisorCoordinator.usageLine(toolCallContext.advisorCalls!.used) : '',
558
296
  ];
559
297
  return parts.filter(Boolean).join('\n\n');
560
298
  };
561
299
  let lastRequestTransientContext = [options.transientBundle?.text, options.transientContext]
562
- .filter(Boolean).join('\n\n');
300
+ .filter(Boolean)
301
+ .join('\n\n');
563
302
  const evidenceLedger = new EvidenceLedger();
564
303
  const stallGuard = new StallGuard();
565
304
  const harnessDiagnostics = (
566
305
  stopReason: import('./types.js').HarnessDiagnostics['stopReason'],
567
306
  ): import('./types.js').HarnessDiagnostics => ({
568
307
  promptVersion: 'minimal-agent:prompt:v2',
569
- basePromptHash: crypto.createHash('sha256')
308
+ basePromptHash: crypto
309
+ .createHash('sha256')
570
310
  .update(history[0]?.role === 'system' ? history[0].content : '')
571
311
  .digest('hex'),
572
312
  enabledPolicyIds: enabledPolicyIds({
@@ -576,9 +316,13 @@ export async function* runQuery(
576
316
  capabilities: capabilitiesForTools(currentEffectiveToolSet.tools),
577
317
  toolNames: currentEffectiveToolSet.names,
578
318
  }),
579
- enabledCapabilities: [...new Set(currentEffectiveToolSet.tools
580
- .map((tool) => capabilityForToolName(tool.name))
581
- .filter((capability): capability is NonNullable<typeof capability> => Boolean(capability)))],
319
+ enabledCapabilities: [
320
+ ...new Set(
321
+ currentEffectiveToolSet.tools
322
+ .map((tool) => capabilityForToolName(tool.name))
323
+ .filter((capability): capability is NonNullable<typeof capability> => Boolean(capability)),
324
+ ),
325
+ ],
582
326
  effectiveToolSetSignature: currentEffectiveToolSet.signature,
583
327
  tokenBudget: buildContextBudgetPlan({
584
328
  provider,
@@ -619,8 +363,8 @@ export async function* runQuery(
619
363
  message: `未作为图片附加:${skipped.source}(${skipped.reason}),已按普通文本处理。`,
620
364
  };
621
365
  }
622
- let visionRequiredThisTurn = Array.isArray(userContent)
623
- && userContent.some((part) => part.type === 'image_url' || part.type === 'video_url');
366
+ let visionRequiredThisTurn =
367
+ Array.isArray(userContent) && userContent.some((part) => part.type === 'image_url' || part.type === 'video_url');
624
368
  if (visionRequiredThisTurn && provider.supportsVision === false) {
625
369
  yield {
626
370
  type: 'error',
@@ -683,14 +427,17 @@ export async function* runQuery(
683
427
  };
684
428
  const optimizationEvents: LoopEvent[] = [];
685
429
  toolCallContext.optimizeConversation = createConversationOptimizer({
686
- history, provider,
430
+ history,
431
+ provider,
687
432
  // This additional model call must contribute to the turn's resource ledger,
688
433
  // without replacing the main model's context/cache usage measurements.
689
434
  chat: async function* (args) {
690
435
  turnUsage.totalCalls += 1;
691
436
  for await (const event of chatFn(args)) {
692
- if (event.type === 'done'
693
- && (typeof event.promptTokens === 'number' || typeof event.outputTokens === 'number')) {
437
+ if (
438
+ event.type === 'done' &&
439
+ (typeof event.promptTokens === 'number' || typeof event.outputTokens === 'number')
440
+ ) {
694
441
  turnUsage.reportedCalls += 1;
695
442
  turnUsage.inputTokens += event.promptTokens ?? 0;
696
443
  turnUsage.outputTokens += event.outputTokens ?? 0;
@@ -699,8 +446,9 @@ export async function* runQuery(
699
446
  }
700
447
  },
701
448
  promptCache: options.promptCache,
702
- replaceHistory, hasQueuedInput: options.hasQueuedInput,
703
- onCompacted: event => optimizationEvents.push(event),
449
+ replaceHistory,
450
+ hasQueuedInput: options.hasQueuedInput,
451
+ onCompacted: (event) => optimizationEvents.push(event),
704
452
  });
705
453
  const interruption = (): Extract<LoopEvent, { type: 'interrupted' }> => {
706
454
  if (options.hasQueuedInput?.()) {
@@ -723,19 +471,45 @@ export async function* runQuery(
723
471
  }
724
472
  modelEnvironmentCwd = nextEnvironmentCwd;
725
473
  try {
726
- const rules = await loadProjectPromptInstructions(modelEnvironmentCwd) ?? '';
474
+ const rules = (await loadProjectPromptInstructions(modelEnvironmentCwd)) ?? '';
727
475
  observedRuleScopes.set(resolve(modelEnvironmentCwd), rules);
728
476
  for (const scope of new Set([...observedRuleScopes.keys(), ...pendingRuleScopes])) {
729
- if (scope !== resolve(modelEnvironmentCwd)) observedRuleScopes.set(scope, await loadProjectPromptInstructions(scope) ?? '');
477
+ if (scope !== resolve(modelEnvironmentCwd))
478
+ observedRuleScopes.set(scope, (await loadProjectPromptInstructions(scope)) ?? '');
730
479
  }
731
480
  pendingRuleScopes.clear();
732
- const mergedRules = await loadProjectPromptInstructions(modelEnvironmentCwd, [...observedRuleScopes.keys()]) ?? '';
733
- currentTransientBundle = assembleContextBundle([
734
- ...(options.transientBundle?.fragments ?? []).filter(f => f.id !== 'project.instructions' && f.id !== 'runtime.execution-environment'),
735
- contextFragment({ id: 'runtime.execution-environment', kind: 'runtime', authority: 'host', priority: 100, required: true, atomic: true,
736
- content: `当前有效执行目录:${modelEnvironmentCwd}。此宿主快照替换旧执行目录;项目规则以本次快照为准,旧历史中的版本不再生效。${rules ? '' : '当前目录及父目录没有适用的项目规则文件,旧规则不得恢复。'}工具权限仍以本次有效工具集和宿主闸门为准。` }),
737
- ...(mergedRules ? [contextFragment({ id: 'project.instructions', kind: 'project', authority: 'constraint', priority: 90, required: true, atomic: true, content: mergedRules })] : []),
738
- ], options.transientBundle?.diagnostics.budgetTokens);
481
+ const mergedRules =
482
+ (await loadProjectPromptInstructions(modelEnvironmentCwd, [...observedRuleScopes.keys()])) ?? '';
483
+ currentTransientBundle = assembleContextBundle(
484
+ [
485
+ ...(options.transientBundle?.fragments ?? []).filter(
486
+ (f) => f.id !== 'project.instructions' && f.id !== 'runtime.execution-environment',
487
+ ),
488
+ contextFragment({
489
+ id: 'runtime.execution-environment',
490
+ kind: 'runtime',
491
+ authority: 'host',
492
+ priority: 100,
493
+ required: true,
494
+ atomic: true,
495
+ content: `当前有效执行目录:${modelEnvironmentCwd}。此宿主快照替换旧执行目录;项目规则以本次快照为准,旧历史中的版本不再生效。${rules ? '' : '当前目录及父目录没有适用的项目规则文件,旧规则不得恢复。'}工具权限仍以本次有效工具集和宿主闸门为准。`,
496
+ }),
497
+ ...(mergedRules
498
+ ? [
499
+ contextFragment({
500
+ id: 'project.instructions',
501
+ kind: 'project',
502
+ authority: 'constraint',
503
+ priority: 90,
504
+ required: true,
505
+ atomic: true,
506
+ content: mergedRules,
507
+ }),
508
+ ]
509
+ : []),
510
+ ],
511
+ options.transientBundle?.diagnostics.budgetTokens,
512
+ );
739
513
  } catch (error) {
740
514
  yield { type: 'error', error: `无法加载完整项目规则,停止本轮:${(error as Error).message}` };
741
515
  yield { type: 'turn_done', completionStatus: 'delivery_incomplete' };
@@ -743,12 +517,18 @@ export async function* runQuery(
743
517
  }
744
518
  const handoff = options.agentHandoff?.current();
745
519
  if (handoff && handoff.kind !== 'help') {
746
- yield { type: 'turn_done', completionStatus: handoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
520
+ yield {
521
+ type: 'turn_done',
522
+ completionStatus: handoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
747
523
  warning: handoff.kind === 'blocked' ? '子任务已交回主 Agent 接力' : undefined,
748
- usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
524
+ usage: {
525
+ ...turnUsage,
526
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
527
+ },
528
+ };
749
529
  return;
750
530
  }
751
- history.push(...(options.takePendingMessages?.() ?? []), ...await takeAgentNotifications(toolCallContext));
531
+ history.push(...(options.takePendingMessages?.() ?? []), ...(await takeAgentNotifications(toolCallContext)));
752
532
  if (runtimeContext.profile === 'main') coordinationText = (await agentCoordinationContext(toolCallContext)).text;
753
533
  incrementTurn(sessionState?.microCompact);
754
534
  expireOldEntries(sessionState?.microCompact);
@@ -760,11 +540,7 @@ export async function* runQuery(
760
540
  // 本地估算的虚高部分(服务端已删内容)由 autoCompactIfNeeded 的 serverDeletedTokens
761
541
  // 校正,判据不会因此过早触发压缩。
762
542
  const cacheEditsMode = provider.apiFormat === 'anthropic' && provider.cacheEdits === true;
763
- reclaimOldToolResults(
764
- history,
765
- sessionState?.microCompact,
766
- cacheEditsMode ? 'cacheEdits' : 'inline',
767
- );
543
+ reclaimOldToolResults(history, sessionState?.microCompact, cacheEditsMode ? 'cacheEdits' : 'inline');
768
544
 
769
545
  if (signal?.aborted) {
770
546
  pushManualInterruptMarker(history);
@@ -786,178 +562,54 @@ export async function* runQuery(
786
562
  return;
787
563
  }
788
564
 
789
- // 2. 自动压缩(判据 = max(上一轮真实 usage, 历史估算 + 工具 schema),
790
- // 阈值 provider 无关、按 contextWindow × compactRatio 比例触发)
791
- let requestTransientContext = buildRequestTransientContext();
792
- lastRequestTransientContext = requestTransientContext;
793
- const preCompactBudget = buildContextBudgetPlan({
794
- provider,
795
- history,
796
- tools: activeTools,
797
- transientContext: requestTransientContext,
798
- });
799
- if (preCompactBudget.overBudget || lastPromptTokens !== undefined) {
800
- try {
801
- const compactOptions = {
802
- actualPromptTokens: lastPromptTokens,
803
- toolsTokens: getToolsSchemaTokens(activeTools, effectiveToolSet.signature),
804
- transientTokens: countTextTokens(requestTransientContext),
805
- // cacheEdits 判据校正:本地 history 未瘦身,扣掉服务端已删部分的估算,
806
- // 防止虚高估算劫持 Math.max 导致压缩过早触发(压缩会重建整个前缀缓存)。
807
- ...(cacheEditsMode && sessionState?.microCompact
808
- ? { serverDeletedTokens: sessionState.microCompact.cacheEdits.activeDeletedTokens }
809
- : {}),
810
- signal,
811
- promptCache: options.promptCache,
812
- chat: chatFn,
813
- };
814
- if (shouldAutoCompact(history, provider, compactOptions)) {
815
- yield { type: 'compact_start' };
816
- yield { type: 'stage_change', stage: 'compacting' };
817
- }
818
- const compact = await autoCompactIfNeeded(history, provider, compactOptions);
819
- if (compact.compacted) {
820
- replaceHistory(compact.messages);
821
- yield {
822
- type: 'compact_done',
823
- before: compact.before,
824
- after: compact.after,
825
- trigger: 'threshold',
826
- mode: compact.mode,
827
- degraded: compact.degraded,
828
- ...(compact.fallbackReason ? { fallbackReason: compact.fallbackReason } : {}),
829
- ...(compact.messagesRemoved !== undefined ? { messagesRemoved: compact.messagesRemoved } : {}),
830
- ...(compact.tokensFreed !== undefined ? { tokensFreed: compact.tokensFreed } : {}),
831
- };
832
- yield { type: 'stage_change', stage: 'thinking' };
833
- }
834
- } catch (e) {
835
- if (signal?.aborted || (e as Error).name === 'AbortError') {
836
- yield interruption();
837
- return;
838
- }
839
- // 压缩失败不要让整个对话挂掉:先 snip 砍最老消息释放空间再继续。
840
- let recovered = false;
841
- try {
842
- const before = countMessagesTokens(history);
843
- const snipped = snipCompactIfNeeded(history, { force: true, snipPercent: 0.3 });
844
- if (snipped.messagesRemoved > 0) {
845
- replaceHistory(snipped.messages);
846
- recovered = true;
847
- yield {
848
- type: 'compact_done',
849
- before,
850
- after: countMessagesTokens(history),
851
- trigger: 'threshold',
852
- mode: 'snip-fallback',
853
- degraded: true,
854
- fallbackReason: 'llm-error',
855
- messagesRemoved: snipped.messagesRemoved,
856
- tokensFreed: snipped.tokensFreed,
857
- };
858
- }
859
- } catch {
860
- /* snip 也失败 → 真的只能硬上 */
861
- }
862
- if (!recovered) {
863
- // 事件是 provider 原始报错唯一该去的地方:只到 stderr / UI,不进 history、
864
- // 不落盘、不会在后续轮次重新发给模型(compact.ts 里那条降级消息因此保持无错误体)。
865
- yield {
866
- type: 'error',
867
- error: `自动压缩失败,规则式截断也未能释放空间;已继续尝试回答:${(e as Error).message}`,
868
- code: 'compact_failed',
869
- };
870
- }
871
- }
872
- }
873
-
874
- // Re-open transient capacity after compaction. If the compacted tail is still
875
- // too large, trim old history before sacrificing any model-visible ability.
876
- requestTransientContext = buildRequestTransientContext();
877
- lastRequestTransientContext = requestTransientContext;
878
- let postCompactBudget = buildContextBudgetPlan({
879
- provider,
565
+ const prepared = yield* prepareModelRequest({
880
566
  history,
881
- tools: activeTools,
882
- transientContext: requestTransientContext,
883
- });
884
- if (postCompactBudget.overBudget) {
885
- const before = countMessagesTokens(history);
886
- const snipped = snipCompactIfNeeded(history, { force: true, snipPercent: 0.3 });
887
- if (snipped.messagesRemoved > 0) {
888
- replaceHistory(snipped.messages);
889
- yield {
890
- type: 'compact_done',
891
- before,
892
- after: countMessagesTokens(history),
893
- trigger: 'post-budget',
894
- mode: 'snip-fallback',
895
- degraded: true,
896
- fallbackReason: 'still-over-budget',
897
- messagesRemoved: snipped.messagesRemoved,
898
- tokensFreed: snipped.tokensFreed,
899
- };
900
- requestTransientContext = buildRequestTransientContext();
901
- lastRequestTransientContext = requestTransientContext;
902
- postCompactBudget = buildContextBudgetPlan({
903
- provider,
904
- history,
905
- tools: activeTools,
906
- transientContext: requestTransientContext,
907
- });
908
- }
909
- }
910
-
911
- const emergencyFit = fitToolsForEmergency({
912
567
  provider,
913
- history,
914
- tools: activeTools,
915
- transientContext: requestTransientContext,
916
- requiredNames: effectiveToolSet.requiredNames,
917
- });
918
- currentEffectiveToolSet = emergencyFit.removedNames.length === 0
919
- ? effectiveToolSet
920
- : createEffectiveToolSet({
921
- availableTools: emergencyFit.tools,
922
- runtime: runtimeContext,
923
- requiredNames: [...effectiveToolSet.requiredNames],
924
- });
925
- advisorCoordinator.setAvailable(
926
- currentEffectiveToolSet.names.has('Advisor'),
927
- );
928
- // Tool availability may change during emergency fitting. Rebuild dynamic
929
- // guidance against the actual request boundary, then account for its size.
930
- requestTransientContext = buildRequestTransientContext();
931
- lastRequestTransientContext = requestTransientContext;
932
- const finalRequestBudget = buildContextBudgetPlan({
933
- provider, history, tools: currentEffectiveToolSet.tools,
934
- transientContext: requestTransientContext,
568
+ activeTools,
569
+ effectiveToolSet,
570
+ runtimeContext,
571
+ sessionState,
572
+ signal,
573
+ lastPromptTokens,
574
+ cacheEditsMode,
575
+ options,
576
+ chatFn,
577
+ replaceHistory,
578
+ buildRequestTransientContext: (tools) => {
579
+ currentEffectiveToolSet = tools;
580
+ advisorCoordinator.setAvailable(tools.names.has('Advisor'));
581
+ lastRequestTransientContext = buildRequestTransientContext();
582
+ return lastRequestTransientContext;
583
+ },
935
584
  });
936
- if (emergencyFit.removedNames.length > 0) {
937
- yield {
938
- type: 'warning',
939
- message: `当前模型窗口压力过高,本次请求临时省略工具 Schema:${emergencyFit.removedNames.join(', ')};下一轮会重新评估并恢复。`,
940
- };
585
+ if (prepared.kind === 'interrupted') {
586
+ yield interruption();
587
+ return;
941
588
  }
942
- toolCallContext.reserveReadChars = createReadBudget(finalRequestBudget.inputLimit - finalRequestBudget.totalInputTokens);
943
- if (finalRequestBudget.overBudget) {
944
- yield {
945
- type: 'error',
946
- error: `当前请求即使经过上下文降级仍需要约 ${finalRequestBudget.totalInputTokens} tokens,超过模型输入上限 ${finalRequestBudget.inputLimit}。已停止发送,避免 Provider 接收必然失败的超限请求。`,
947
- code: 'context_overflow',
948
- };
589
+ if (prepared.kind === 'overflow') {
949
590
  yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('error') };
950
591
  return;
951
592
  }
593
+ const requestTransientContext = prepared.requestTransientContext;
594
+ currentEffectiveToolSet = prepared.currentEffectiveToolSet;
595
+ toolCallContext.reserveReadChars = createReadBudget(prepared.remainingTokens);
952
596
 
953
597
  // 3. 调 LLM 并组装 assistant 消息
954
598
  trace('model_start');
955
599
  let assistantText = '';
956
600
  // Candidate text is private until the delivery gates allow publication.
957
601
  // Keep the compatibility event as a phase notice, never as a text retraction.
958
- function* retireDraft(reason: Extract<LoopEvent, { type: 'assistant_draft_discarded' }>['reason'] | 'interrupted'): Generator<LoopEvent> {
959
- const message: Message = { role: 'system', content: answerPreparationNotice(reason), id: crypto.randomUUID(),
960
- timestamp: Date.now(), _ephemeral: true, _uiProgress: true };
602
+ function* retireDraft(
603
+ reason: Extract<LoopEvent, { type: 'assistant_draft_discarded' }>['reason'] | 'interrupted',
604
+ ): Generator<LoopEvent> {
605
+ const message: Message = {
606
+ role: 'system',
607
+ content: answerPreparationNotice(reason),
608
+ id: crypto.randomUUID(),
609
+ timestamp: Date.now(),
610
+ _ephemeral: true,
611
+ _uiProgress: true,
612
+ };
961
613
  history.push(message);
962
614
  yield { type: 'injected_message', message };
963
615
  if (reason !== 'interrupted') yield { type: 'assistant_draft_discarded', reason, textLength: 0 };
@@ -977,8 +629,7 @@ export async function* runQuery(
977
629
  * 'length' = 被 provider 因 max_tokens 截断 —— 收尾时据此给 warning,
978
630
  * 避免「半截答案」被静默当成正常 end_turn。
979
631
  */
980
- let lastFinishReason: 'stop' | 'tool_calls' | 'length' | 'unknown' | 'aborted' =
981
- 'unknown';
632
+ let lastFinishReason: 'stop' | 'tool_calls' | 'length' | 'unknown' | 'aborted' = 'unknown';
982
633
 
983
634
  // 进入 LLM 流前:等首 token / reasoning,本质是 thinking
984
635
  yield { type: 'stage_change', stage: 'thinking' };
@@ -996,12 +647,8 @@ export async function* runQuery(
996
647
  promptCache: options.promptCache,
997
648
  visionPolicy: visionRequiredThisTurn ? 'required' : 'optional-history',
998
649
  // cacheEdits 回收状态(同一会话级对象跨轮复用;compact 后由 resetCacheEdits 清空)
999
- ...(cacheEditsMode && sessionState?.microCompact
1000
- ? { cacheEdits: sessionState.microCompact.cacheEdits }
1001
- : {}),
1002
- ...(options.responseFormat
1003
- ? { responseFormat: options.responseFormat }
1004
- : {}),
650
+ ...(cacheEditsMode && sessionState?.microCompact ? { cacheEdits: sessionState.microCompact.cacheEdits } : {}),
651
+ ...(options.responseFormat ? { responseFormat: options.responseFormat } : {}),
1005
652
  })) {
1006
653
  if (ev.type === 'text_delta') {
1007
654
  assistantText += ev.delta;
@@ -1138,14 +785,29 @@ export async function* runQuery(
1138
785
  // A pending review must run before another solving/publishing attempt.
1139
786
  // Read-only diagnosis and human questions remain available while stalled.
1140
787
  const pendingReview = options.advisorCheckpoints === false ? undefined : advisorCoordinator.pendingReview();
1141
- if (pendingReview && turn < maxTurns && toolCallsByIndex.length > 0
1142
- && !toolCallsByIndex.some(tc => ['Advisor', 'AskUserQuestion'].includes(tc.function.name))
1143
- && toolCallsByIndex.some(tc => tc.function.name === 'PresentResult'
1144
- || advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find(t => t.name === tc.function.name), { treatVerificationAsReadOnly: true }).mutatesWorkspace
1145
- || stallGuard.shouldReject(tc))) {
788
+ if (
789
+ pendingReview &&
790
+ turn < maxTurns &&
791
+ toolCallsByIndex.length > 0 &&
792
+ !toolCallsByIndex.some((tc) => ['Advisor', 'AskUserQuestion'].includes(tc.function.name)) &&
793
+ toolCallsByIndex.some(
794
+ (tc) =>
795
+ tc.function.name === 'PresentResult' ||
796
+ advisorSemanticsFor(
797
+ tc,
798
+ toolCallContext,
799
+ currentEffectiveToolSet.tools.find((t) => t.name === tc.function.name),
800
+ { treatVerificationAsReadOnly: true },
801
+ ).mutatesWorkspace ||
802
+ stallGuard.shouldReject(tc),
803
+ )
804
+ ) {
1146
805
  yield* retireDraft('advisor_checkpoint');
1147
- toolCallsByIndex.splice(0, toolCallsByIndex.length, { id: crypto.randomUUID(), type: 'function',
1148
- function: { name: 'Advisor', arguments: JSON.stringify(pendingReview) } });
806
+ toolCallsByIndex.splice(0, toolCallsByIndex.length, {
807
+ id: crypto.randomUUID(),
808
+ type: 'function',
809
+ function: { name: 'Advisor', arguments: JSON.stringify(pendingReview) },
810
+ });
1149
811
  assistantText = '';
1150
812
  }
1151
813
  // Count the calls that survived review scheduling, including failed loads.
@@ -1153,7 +815,9 @@ export async function* runQuery(
1153
815
  if (call.function.name !== 'Skill') continue;
1154
816
  try {
1155
817
  if (JSON.parse(call.function.arguments).name === 'dynamic-ui') diagramPreparationAttempted = true;
1156
- } catch { /* Ordinary tool validation reports malformed arguments. */ }
818
+ } catch {
819
+ /* Ordinary tool validation reports malformed arguments. */
820
+ }
1157
821
  }
1158
822
  const assistantMsg: Message = {
1159
823
  role: 'assistant',
@@ -1170,35 +834,54 @@ export async function* runQuery(
1170
834
  finalResponse: if (toolCallsByIndex.length === 0) {
1171
835
  // Repair only private preparation, through the ordinary tool pipeline.
1172
836
  // One attempt per turn, including missing/failed skills; never rewind a reply.
1173
- if (!diagramPreparationAttempted && !options.responseFormat
1174
- && runtimeContext.profile === 'main' && output.diagrams.length > 0
1175
- && currentEffectiveToolSet.names.has('Skill') && turn < maxTurns
1176
- && needsDiagramPreparation(assistantText, userInput)) {
837
+ if (
838
+ !diagramPreparationAttempted &&
839
+ !options.responseFormat &&
840
+ runtimeContext.profile === 'main' &&
841
+ output.diagrams.length > 0 &&
842
+ currentEffectiveToolSet.names.has('Skill') &&
843
+ turn < maxTurns &&
844
+ needsDiagramPreparation(assistantText, userInput)
845
+ ) {
1177
846
  diagramPreparationAttempted = true;
1178
- toolCallsByIndex.push({ id: crypto.randomUUID(), type: 'function', function: {
1179
- name: 'Skill', arguments: JSON.stringify({ name: 'dynamic-ui' }),
1180
- } });
847
+ toolCallsByIndex.push({
848
+ id: crypto.randomUUID(),
849
+ type: 'function',
850
+ function: {
851
+ name: 'Skill',
852
+ arguments: JSON.stringify({ name: 'dynamic-ui' }),
853
+ },
854
+ });
1181
855
  assistantMsg.content = null;
1182
856
  assistantMsg.tool_calls = toolCallsByIndex;
1183
857
  break finalResponse;
1184
858
  }
1185
- if (!askCorrectionAttempted && runtimeContext.interactiveAsk
1186
- && currentEffectiveToolSet.names.has('AskUserQuestion')
1187
- && needsInteractiveQuestion(stripThinkBlocks(assistantText)) && turn < maxTurns) {
859
+ if (
860
+ !askCorrectionAttempted &&
861
+ runtimeContext.interactiveAsk &&
862
+ currentEffectiveToolSet.names.has('AskUserQuestion') &&
863
+ needsInteractiveQuestion(stripThinkBlocks(assistantText)) &&
864
+ turn < maxTurns
865
+ ) {
1188
866
  askCorrectionAttempted = true;
1189
867
  yield* retireDraft('interactive_question');
1190
868
  continue;
1191
869
  }
1192
870
  const emptyResponse = stripThinkBlocks(assistantText).length === 0;
1193
- const coordination = runtimeContext.profile === 'main' ? await agentCoordinationContext(toolCallContext) : undefined;
1194
- const pendingDelegations = coordination?.unresolved.filter((record) => record.parentMessageId === currentUserMessageId) ?? [];
871
+ const coordination =
872
+ runtimeContext.profile === 'main' ? await agentCoordinationContext(toolCallContext) : undefined;
873
+ const pendingDelegations =
874
+ coordination?.unresolved.filter((record) => record.parentMessageId === currentUserMessageId) ?? [];
1195
875
  if (pendingDelegations.length && !delegationCorrectionAttempted && turn < maxTurns) {
1196
876
  delegationCorrectionAttempted = true;
1197
877
  coordinationText = coordination!.text;
1198
878
  yield* retireDraft('formal_delivery');
1199
879
  continue;
1200
880
  }
1201
- const pendingMessages = [...(options.takePendingMessages?.() ?? []), ...await takeAgentNotifications(toolCallContext)];
881
+ const pendingMessages = [
882
+ ...(options.takePendingMessages?.() ?? []),
883
+ ...(await takeAgentNotifications(toolCallContext)),
884
+ ];
1202
885
  if (pendingMessages.length) {
1203
886
  history.push(...pendingMessages);
1204
887
  continue;
@@ -1207,27 +890,36 @@ export async function* runQuery(
1207
890
  // presenting it. Give it one model-only corrective pass; the reminder is
1208
891
  // transient and therefore never pollutes persisted conversation history.
1209
892
  if (
1210
- !emptyResponse && formalDeliveryRequired
1211
- && !resultPresented
1212
- && !deliveryCorrectionAttempted
1213
- && turn < maxTurns
893
+ !emptyResponse &&
894
+ formalDeliveryRequired &&
895
+ !resultPresented &&
896
+ !deliveryCorrectionAttempted &&
897
+ turn < maxTurns
1214
898
  ) {
1215
899
  deliveryCorrectionAttempted = true;
1216
900
  yield* retireDraft('formal_delivery');
1217
901
  continue;
1218
902
  }
1219
- const deliveryCheckpoint = emptyResponse || options.advisorCheckpoints === false
1220
- ? { allow: true as const }
1221
- : advisorCoordinator.beforeDelivery(assistantText);
1222
- const fallbackReview = !emptyResponse && options.advisorCheckpoints !== false
1223
- ? advisorCoordinator.pendingReview(assistantText) : undefined;
903
+ const deliveryCheckpoint =
904
+ emptyResponse || options.advisorCheckpoints === false
905
+ ? { allow: true as const }
906
+ : advisorCoordinator.beforeDelivery(assistantText);
907
+ const fallbackReview =
908
+ !emptyResponse && options.advisorCheckpoints !== false
909
+ ? advisorCoordinator.pendingReview(assistantText)
910
+ : undefined;
1224
911
  if (fallbackReview && turn < maxTurns) {
1225
912
  yield* retireDraft('advisor_checkpoint');
1226
913
  // Reuse the effective tool boundary, permissions, cancellation, events and
1227
914
  // persistence. Never call a provider behind the host's tool pipeline.
1228
- toolCallsByIndex.push({ id: crypto.randomUUID(), type: 'function', function: {
1229
- name: 'Advisor', arguments: JSON.stringify(fallbackReview),
1230
- } });
915
+ toolCallsByIndex.push({
916
+ id: crypto.randomUUID(),
917
+ type: 'function',
918
+ function: {
919
+ name: 'Advisor',
920
+ arguments: JSON.stringify(fallbackReview),
921
+ },
922
+ });
1231
923
  assistantMsg.content = null;
1232
924
  assistantMsg.tool_calls = toolCallsByIndex;
1233
925
  break finalResponse;
@@ -1238,18 +930,28 @@ export async function* runQuery(
1238
930
  }
1239
931
  if (!emptyResponse) {
1240
932
  for (const message of advisorCoordinator.deliveryWarnings()) yield { type: 'warning', message };
1241
- if (!deliveryCheckpoint.allow) yield { type: 'warning', message: '已达到本轮执行上限,顾问交付检查尚未完成;不能把此次输出视为已复核。' };
933
+ if (!deliveryCheckpoint.allow)
934
+ yield { type: 'warning', message: '已达到本轮执行上限,顾问交付检查尚未完成;不能把此次输出视为已复核。' };
1242
935
  }
1243
936
  if (emptyResponse) {
1244
937
  // Recover once within the existing turn budget, retaining tool receipts and
1245
938
  // advisor state. Never replay tools or expose an empty candidate as an answer.
1246
939
  if (!resultPresented && !emptyResponseRecoveryAttempted && turn < maxTurns) {
1247
940
  emptyResponseRecoveryAttempted = true;
1248
- emptyResponseRecoveryReason = lastFinishReason === 'length'
1249
- ? '输出额度耗尽' : lastFinishReason === 'unknown'
1250
- ? '响应流缺少正常结束状态' : '响应为空或仅含思考内容';
1251
- const message: Message = { role: 'system', content: '正在恢复回答,已保留调查结果与工作进展。',
1252
- id: crypto.randomUUID(), timestamp: Date.now(), _ephemeral: true, _uiProgress: true };
941
+ emptyResponseRecoveryReason =
942
+ lastFinishReason === 'length'
943
+ ? '输出额度耗尽'
944
+ : lastFinishReason === 'unknown'
945
+ ? '响应流缺少正常结束状态'
946
+ : '响应为空或仅含思考内容';
947
+ const message: Message = {
948
+ role: 'system',
949
+ content: '正在恢复回答,已保留调查结果与工作进展。',
950
+ id: crypto.randomUUID(),
951
+ timestamp: Date.now(),
952
+ _ephemeral: true,
953
+ _uiProgress: true,
954
+ };
1253
955
  history.push(message);
1254
956
  yield { type: 'injected_message', message };
1255
957
  continue;
@@ -1261,81 +963,49 @@ export async function* runQuery(
1261
963
  let publicationError: unknown;
1262
964
  let publicationInterrupted = false;
1263
965
  let streamed = false;
1264
- if (!options.responseFormat && runtimeContext.profile === 'main'
1265
- && output.finalDelivery === 'stream') {
1266
- const candidate = assistantText;
1267
- const candidateFinishReason = lastFinishReason;
1268
- let publishedText = '';
1269
- let publicationDone = false;
1270
- yield { type: 'stage_change', stage: 'streaming' };
1271
- try {
1272
- const publicationMessages = finalAnswerMessages(buildModelMessages(history, requestTransientContext, userMessage.id), assistantText, output);
1273
- const publicationPlan = buildContextBudgetPlan({ provider, history: publicationMessages, tools: [] });
1274
- if (publicationPlan.overBudget) throw new Error('最终表达上下文超过模型输入上限,未发送请求。');
1275
- if (signal?.aborted || options.hasQueuedInput?.()) {
1276
- publicationInterrupted = true;
1277
- throw new Error('最终发布已取消。');
1278
- }
1279
- turnUsage.totalCalls += 1;
1280
- for await (const event of chatFn({
1281
- provider,
1282
- messages: publicationMessages,
1283
- tools: toolsForResponsePhase(currentEffectiveToolSet.tools, 'publication'), signal,
1284
- conversationMode: runtimeContext.conversationMode ?? 'private',
1285
- promptCache: options.promptCache,
1286
- })) {
1287
- if (event.type === 'done' && !publicationDone) {
1288
- publicationDone = true;
1289
- if (typeof event.promptTokens === 'number' || typeof event.outputTokens === 'number') {
1290
- turnUsage.reportedCalls += 1;
1291
- turnUsage.inputTokens += event.promptTokens ?? 0;
1292
- turnUsage.outputTokens += event.outputTokens ?? 0;
1293
- }
1294
- }
1295
- if (signal?.aborted || options.hasQueuedInput?.()) {
1296
- publicationInterrupted = true;
1297
- break;
1298
- }
1299
- if (event.type === 'text_delta') {
1300
- // Final expression is live generation, not an exact-copy replay.
1301
- // Once visible, text is never replaced or joined with a different draft.
1302
- publishedText += event.delta;
1303
- streamed = true;
1304
- yield { type: 'text', delta: event.delta };
1305
- } else if (event.type === 'tool_call_delta') {
1306
- throw new Error('最终表达阶段返回了非预期工具调用,未执行该工具。');
1307
- } else if (event.type === 'done') {
1308
- publicationDone = true;
1309
- lastFinishReason = event.stopReason;
1310
- if (event.stopReason === 'aborted') publicationInterrupted = true;
1311
- }
1312
- }
1313
- if (!publicationDone && !publicationInterrupted) throw new Error('最终答案流未正常结束。');
1314
- if (!publicationInterrupted && lastFinishReason !== 'stop' && lastFinishReason !== 'length') throw new Error('最终答案流缺少有效的结束状态。');
1315
- if (!publishedText.trim() && !publicationInterrupted) throw new Error('最终表达未返回正文。');
1316
- } catch (error) {
1317
- publicationInterrupted ||= signal?.aborted === true || options.hasQueuedInput?.() === true || (error as Error)?.name === 'AbortError';
1318
- publicationError = error;
1319
- }
1320
- if (publicationError && !publicationInterrupted && !publishedText) {
1321
- yield { type: 'warning', message: '最终回答流未能开始,已一次性显示内部准备的答案;未进行新的事实核验。' };
1322
- yield { type: 'text', delta: candidate };
1323
- streamed = true;
1324
- publishedText = candidate;
1325
- lastFinishReason = candidateFinishReason;
1326
- publicationError = undefined;
1327
- }
966
+ if (!options.responseFormat && runtimeContext.profile === 'main' && output.finalDelivery === 'stream') {
967
+ const publication = yield* publishFinalAnswer({
968
+ provider,
969
+ messages: buildModelMessages(history, requestTransientContext, userMessage.id),
970
+ candidate: assistantText,
971
+ candidateFinishReason: lastFinishReason,
972
+ output,
973
+ chatFn,
974
+ options,
975
+ signal,
976
+ conversationMode: runtimeContext.conversationMode ?? 'private',
977
+ turnUsage,
978
+ });
979
+ const publishedText = publication.text;
980
+ ({ publicationError, publicationInterrupted, streamed, lastFinishReason } = publication);
1328
981
  assistantText = publishedText;
1329
982
  assistantMsg.content = publishedText || null;
1330
983
  if (!publishedText) {
1331
- if (publicationInterrupted) yield { ...interruption(), usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
1332
- else yield { type: 'error', code: 'llm_error', error: `最终答案生成失败:${String(publicationError)}`, usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
984
+ if (publicationInterrupted)
985
+ yield {
986
+ ...interruption(),
987
+ usage: {
988
+ ...turnUsage,
989
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
990
+ },
991
+ };
992
+ else
993
+ yield {
994
+ type: 'error',
995
+ code: 'llm_error',
996
+ error: `最终答案生成失败:${String(publicationError)}`,
997
+ usage: {
998
+ ...turnUsage,
999
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
1000
+ },
1001
+ };
1333
1002
  return;
1334
1003
  }
1335
1004
  }
1336
1005
  assistantMsg.presentation = 'final';
1337
1006
  trace('final_published');
1338
- if (assistantMsg.role === 'assistant') assistantMsg.advisorTaskVersion = advisorCoordinator.versions.taskVersion;
1007
+ if (assistantMsg.role === 'assistant')
1008
+ assistantMsg.advisorTaskVersion = advisorCoordinator.versions.taskVersion;
1339
1009
  assistantMsg.advisorCheckpoints = advisorCoordinator.drainDegradations();
1340
1010
  history.push(assistantMsg);
1341
1011
  // Non-interactive consumers retain atomic output. Interactive hosts
@@ -1347,8 +1017,24 @@ export async function* runQuery(
1347
1017
  };
1348
1018
  if (publicationInterrupted || publicationError) {
1349
1019
  yield { type: 'warning', message: '最终答案未完整生成,已保留已输出内容;未撤回或重新生成。' };
1350
- if (publicationInterrupted) yield { ...interruption(), usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
1351
- else yield { type: 'error', code: 'llm_error', error: `最终答案流中断:${String(publicationError)}`, usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
1020
+ if (publicationInterrupted)
1021
+ yield {
1022
+ ...interruption(),
1023
+ usage: {
1024
+ ...turnUsage,
1025
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
1026
+ },
1027
+ };
1028
+ else
1029
+ yield {
1030
+ type: 'error',
1031
+ code: 'llm_error',
1032
+ error: `最终答案流中断:${String(publicationError)}`,
1033
+ usage: {
1034
+ ...turnUsage,
1035
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
1036
+ },
1037
+ };
1352
1038
  return;
1353
1039
  }
1354
1040
  }
@@ -1366,11 +1052,8 @@ export async function* runQuery(
1366
1052
  // The final answer has already consumed the latest screenshot. Persist only a compact
1367
1053
  // marker so the next turn does not resend a large screen image.
1368
1054
  evictPriorVisionShots(history);
1369
- const estimatedTokens = countMessagesTokens(history) + getToolsSchemaTokens(activeTools);
1370
- const usedTokens = Math.min(
1371
- provider.contextWindow,
1372
- Math.max(lastPromptTokens ?? 0, estimatedTokens),
1373
- );
1055
+ const estimatedTokens = countMessagesTokens(history) + estimateToolsTokens(activeTools);
1056
+ const usedTokens = Math.min(provider.contextWindow, Math.max(lastPromptTokens ?? 0, estimatedTokens));
1374
1057
  yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('complete') };
1375
1058
  const claimValidation = validateFinalClaims(assistantText, evidenceLedger.snapshot());
1376
1059
  for (const warning of claimValidation.warnings) yield { type: 'warning', message: warning };
@@ -1428,8 +1111,12 @@ export async function* runQuery(
1428
1111
  usage,
1429
1112
  };
1430
1113
  } else {
1431
- yield { type: 'turn_done', completionStatus: 'completed', usage,
1432
- ...(emptyResponse ? { warning: '成果已提交,未生成文字总结;请查看已提交的成果。' } : {}) };
1114
+ yield {
1115
+ type: 'turn_done',
1116
+ completionStatus: 'completed',
1117
+ usage,
1118
+ ...(emptyResponse ? { warning: '成果已提交,未生成文字总结;请查看已提交的成果。' } : {}),
1119
+ };
1433
1120
  }
1434
1121
  return;
1435
1122
  }
@@ -1454,269 +1141,18 @@ export async function* runQuery(
1454
1141
  // (OpenAI 协议要求 tool 消息与上一条 assistant 的 tool_calls 一一对应)。
1455
1142
  yield { type: 'stage_change', stage: 'tool_executing' };
1456
1143
 
1457
- type WorkerOutcome = {
1458
- tc: ToolCall;
1459
- result: ToolResult;
1460
- };
1461
-
1462
- // 执行单个 tool call → WorkerOutcome(内部吞掉 abort/异常,永不 reject)。
1463
- const failureReviews: StallObservation[] = [];
1464
- const runOneImpl = async (
1465
- tc: ToolCall,
1466
- reportProgress?: (message: string, detail?: import('./types.js').ToolProgressDetail) => void,
1467
- ): Promise<WorkerOutcome> => {
1468
- try {
1469
- const handoff = options.agentHandoff?.current();
1470
- if (handoff && handoff.kind !== 'help') return { tc, result: { ok: false, disposition: 'deferred', error: '子任务已经提交交接,本批后续调用未执行' } };
1471
- if (signal?.aborted || options.hasQueuedInput?.()) {
1472
- return { tc, result: { ok: false, disposition: 'deferred', error: 'aborted' } };
1473
- }
1474
- const advisorAvailable = currentEffectiveToolSet.names.has('Advisor');
1475
- if (!advisorAvailable && stallGuard.shouldReject(tc)) {
1476
- return {
1477
- tc,
1478
- result: {
1479
- ok: false as const,
1480
- disposition: 'deferred',
1481
- error:
1482
- '检测到同一工具和参数已连续两次返回相同失败;第三次调用已在执行前拒绝,请改变输入或改用其他路径。',
1483
- recovery: 'change-input',
1484
- sensitivity: 'public',
1485
- },
1486
- };
1487
- }
1488
- // The model-visible catalog and the execution boundary are the same set.
1489
- // A provider may still emit a stale or fabricated tool call; return a
1490
- // recoverable result so the model can choose an available path.
1491
- if (!currentEffectiveToolSet.names.has(tc.function.name)) {
1492
- const boundary = options.toolBoundaryLabel ?? '当前宿主授权';
1493
- const visible = [...currentEffectiveToolSet.names];
1494
- const availableHint = visible.length
1495
- ? `(可用:${visible.slice(0, 12).join('、')}${visible.length > 12 ? '…' : ''})`
1496
- : '(本轮没有可用工具)';
1497
- const deniedReason = tc.function.name === 'Agent'
1498
- ? '当前上下文不允许调用 Agent;请直接完成子任务或改用已提供的工具'
1499
- : `工具 ${tc.function.name} 不在${boundary}的有效工具集中${availableHint},请改用已提供的工具继续任务`;
1500
- return {
1501
- tc,
1502
- result: {
1503
- ok: false as const,
1504
- error: deniedReason,
1505
- recovery: 'change-input',
1506
- sensitivity: 'public',
1507
- },
1508
- };
1509
- }
1510
- const checkpoint = options.advisorCheckpoints === false
1511
- ? { allow: true as const }
1512
- : advisorCoordinator.beforeTool(tc, {
1513
- ...advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name), { treatVerificationAsReadOnly: true }),
1514
- retriesFailure: stallGuard.shouldReject(tc),
1515
- });
1516
- if (!checkpoint.allow) {
1517
- return { tc, result: checkpoint.deferred! };
1518
- }
1519
- // 工具执行闸门:宿主注入后覆盖所有工具,包括只读工具。deny → 把 reason 当
1520
- // tool_result 回填,模型据此改道/如实报告,不抛异常不中断整轮。宿主异常一律 deny。
1521
- // Keep the host gate's side-effect classification identical to the
1522
- // Advisor classification. Shell tools are generic in their schema but
1523
- // individual commands can be deterministic read-only diagnostics.
1524
- let isReadOnly = currentEffectiveToolSet.tools.find(tool => tool.name === tc.function.name)?.isReadOnly === true;
1525
- if (tc.function.name === 'Bash' || tc.function.name === 'PowerShell') {
1526
- try {
1527
- const input = JSON.parse(tc.function.arguments || '{}') as { command?: unknown };
1528
- if (typeof input.command === 'string') isReadOnly = isReadOnlyShellCommand(input.command);
1529
- } catch { isReadOnly = false; }
1530
- }
1531
- const effectiveToolGate = runtimeContext.toolGate ?? options.toolGate;
1532
- if (effectiveToolGate) {
1533
- let decision;
1534
- try {
1535
- const gateDetails = getToolGateDetails(
1536
- tc.function.name,
1537
- tc.function.arguments,
1538
- { ...toolCallContext, cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd, toolCallId: tc.id, reportProgress },
1539
- );
1540
- decision = await effectiveToolGate(
1541
- {
1542
- name: tc.function.name,
1543
- argsJson: tc.function.arguments,
1544
- isReadOnly,
1545
- toolCallId: tc.id,
1546
- ...gateDetails,
1547
- },
1548
- signal,
1549
- );
1550
- } catch {
1551
- decision = { allow: false as const, reason: '工具执行审批失败(宿主异常)' };
1552
- }
1553
- if (!decision.allow) {
1554
- return { tc, result: { ok: false as const, error: decision.reason } };
1555
- }
1556
- }
1557
- if (signal?.aborted || options.hasQueuedInput?.()) {
1558
- return { tc, result: { ok: false, disposition: 'deferred', error: 'aborted' } };
1559
- }
1560
- options.onToolStart?.(tc.function.name, tc.id);
1561
- // 浅拷贝填入本次调用的 toolCallId:进度按调用实例路由(并行同名工具不串扰)。
1562
- // advisorCalls/agentCalls 是共享对象引用,计数仍全轮共享,不受拷贝影响。
1563
- const executionCwd = sessionState?.activeWorktree?.path ?? toolCallContext.cwd;
1564
- if (executionCwd !== modelEnvironmentCwd) return { tc, result: {
1565
- ok: false as const, disposition: 'deferred' as const,
1566
- error: '执行环境已改变,本批调用依据旧目录生成,尚未执行。请等待刷新环境和项目规则后重新生成调用。',
1567
- } };
1568
- // Load path-scoped rules before a direct file mutation. Returning a
1569
- // deferred result gives the model a boundary to reconsider its edit.
1570
- if (['Edit', 'MultiEdit', 'Write', 'Download', 'NotebookEdit', 'Trash'].includes(tc.function.name)) {
1571
- try {
1572
- const args = JSON.parse(tc.function.arguments);
1573
- const targets = tc.function.name === 'Trash' ? args.paths : [args.file_path ?? args.path ?? args.notebook_path];
1574
- for (const target of Array.isArray(targets) ? targets : []) {
1575
- if (typeof target !== 'string') continue;
1576
- // Download/Trash use literal path.resolve; editing tools expand ~.
1577
- const resolved = ['Download', 'Trash'].includes(tc.function.name)
1578
- ? { ok: true as const, resolvedPath: resolve(executionCwd ?? runtimeContext.cwd, target) }
1579
- : resolveToolPath(target, executionCwd ?? runtimeContext.cwd);
1580
- if (!resolved.ok) return { tc, result: { ok: false as const, error: resolved.error } };
1581
- const scope = dirname(resolved.resolvedPath);
1582
- const rules = await loadProjectPromptInstructions(scope) ?? '';
1583
- if (observedRuleScopes.get(scope) === rules || (!rules && !observedRuleScopes.has(scope))) continue;
1584
- if (countTextTokens(rules) > 12000) return { tc, result: { ok: false as const, error: `目标目录规则超过安全交接预算,未执行修改;请缩小任务或整理规则:${scope}` } };
1585
- pendingRuleScopes.add(scope);
1586
- // 带缩进:让真实换行落进 content,TUI 的工具结果 3 行折叠按 \n 计行,
1587
- // 压成一行的 JSON.stringify 会绕开折叠、把整份规则原文原样刷进终端。
1588
- return { tc, result: { ok: false as const, disposition: 'deferred' as const,
1589
- error: `目标目录规则已更新,尚未执行修改。先阅读本快照再重新决定操作(规则不能扩大授权):\n${JSON.stringify({ scope, rules: rules || '该作用域无项目规则,撤销其旧规则' }, null, 2)}` } };
1590
- }
1591
- } catch (error) {
1592
- return { tc, result: { ok: false as const, error: `无法核验目标目录规则,未执行修改:${(error as Error).message}` } };
1593
- }
1594
- }
1595
- const needsWorkspaceLease = runtimeContext.profile === 'main'
1596
- && capabilityForToolName(tc.function.name) !== 'subagent'
1597
- && advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name)).mutatesWorkspace;
1598
- const releaseWorkspace = needsWorkspaceLease && executionCwd
1599
- ? await acquireSubagentLease(executionCwd, await normalizeWriteScopes(executionCwd, undefined), 8,
1600
- { signal, owner: runtimeContext.sessionId ?? executionCwd }) : undefined;
1601
- let result: ToolResult;
1602
- try {
1603
- result = await executeToolFn(
1604
- tc.function.name,
1605
- tc.function.arguments,
1606
- signal,
1607
- {
1608
- ...toolCallContext,
1609
- delegationTools: currentEffectiveToolSet.tools,
1610
- cwd:
1611
- sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
1612
- toolCallId: tc.id,
1613
- reportProgress,
1614
- },
1615
- );
1616
- } finally { releaseWorkspace?.(); }
1617
- if (tc.function.name === 'ComputerUse' && sessionState) {
1618
- sessionState.computerAutomation = { lastUsedAt: Date.now() };
1619
- }
1620
- const downloadableArtifact =
1621
- result.ok && result.metadata?.kind === 'browser_download'
1622
- ? result.metadata.artifact
1623
- : undefined;
1624
- const formalManifest =
1625
- result.ok && result.metadata?.kind === 'result_manifest'
1626
- ? result.metadata.manifest
1627
- : downloadableArtifact;
1628
- if (
1629
- formalManifest &&
1630
- (tc.function.name === 'PresentResult' || downloadableArtifact) &&
1631
- options.commitFormalDelivery
1632
- ) {
1633
- try {
1634
- await options.commitFormalDelivery({
1635
- toolCallId: tc.id,
1636
- turnId: userMessage.id ?? options.userMessageId ?? 'turn:unknown',
1637
- manifest: formalManifest,
1638
- });
1639
- } catch (error) {
1640
- result = {
1641
- ok: false,
1642
- error: `正式交付未能可靠保存:${(error as Error).message}`,
1643
- recovery: 'retry',
1644
- sensitivity: 'local',
1645
- };
1646
- }
1647
- }
1648
- if (tc.function.name === 'Advisor' || tc.function.name === 'AdvisorDecision') {
1649
- // 串行批次内下一项可能就是 AdvisorDecision/受保护写入,必须立即推进协调器状态。
1650
- advisorCoordinator.observeToolResult(tc, result);
1651
- }
1652
- options.onToolEnd?.(tc.id, false);
1653
- return { tc, result };
1654
- } catch (e) {
1655
- const wasAborted = (e as Error).name === 'AbortError';
1656
- options.onToolEnd?.(tc.id, wasAborted);
1657
- if (wasAborted) {
1658
- return { tc, result: { ok: false as const, error: 'aborted' } };
1659
- }
1660
- return { tc, result: { ok: false as const, error: (e as Error).message } };
1661
- }
1662
- };
1663
-
1664
- const runOne: typeof runOneImpl = async (tc, reportProgress) => {
1665
- // Also settle denied/invalid/unavailable calls that never reached the
1666
- // provider adapter. This records a real attempt, not an ignored reminder.
1667
- let consultation;
1668
- if (tc.function.name === 'Advisor') {
1669
- let reason: import('./types.js').AdvisorReason | undefined;
1670
- try { reason = JSON.parse(tc.function.arguments).reason; } catch { /* validation handles malformed input */ }
1671
- consultation = advisorCoordinator.beginConsultation(reason);
1672
- }
1673
- const outcome = await runOneImpl(tc, reportProgress);
1674
- if (consultation && outcome.result.metadata?.kind !== 'advisor_consultation'
1675
- && !( !outcome.result.ok && outcome.result.error === 'aborted')) {
1676
- outcome.result = { ...outcome.result, metadata: advisorCoordinator.finishConsultation(consultation, outcome.result.ok) };
1677
- }
1678
- const metadata = outcome.result.metadata;
1679
- if (metadata?.kind === 'advisor_decision' && outcome.result.ok
1680
- || metadata?.kind === 'advisor_consultation') {
1681
- if (metadata.checkpoint === 'stalled') stallGuard.completeReview(metadata.checkpointKey.split(':').at(-1)!);
1682
- }
1683
- const failure = stallGuard.observeAttempt(tc, outcome.result);
1684
- if (failure.stalled && failure.signature) {
1685
- failureReviews.push(failure);
1686
- advisorCoordinator.requireFailureReview(failure.signature, failure.attempts ?? []);
1687
- }
1688
- return outcome;
1689
- };
1690
-
1691
- const startEvent = (
1692
- tc: ToolCall,
1693
- ): Extract<LoopEvent, { type: 'tool_start' }> => ({
1694
- type: 'tool_start',
1695
- toolCallId: tc.id,
1696
- toolName: tc.function.name,
1697
- argsPreview: previewArgs(tc.function.arguments),
1698
- argsFriendly: friendlyToolDescription(tc.function.name, tc.function.arguments),
1699
- argsConcise: friendlyToolDescription(tc.function.name, tc.function.arguments, conciseToolPath),
1700
- });
1701
- const endEvent = (
1702
- o: WorkerOutcome,
1703
- ): Extract<LoopEvent, { type: 'tool_end' }> => ({
1704
- type: 'tool_end',
1705
- toolCallId: o.tc.id,
1706
- toolName: o.tc.function.name,
1707
- ok: o.result.ok,
1708
- content: o.result.ok
1709
- ? o.result.content
1710
- : o.result.error === 'aborted'
1711
- ? '(已中断)'
1712
- : `Error: ${o.result.error}`,
1713
- metadata: o.result.metadata,
1714
- });
1715
-
1716
- const segments = executionSegments(toolCallsByIndex, (tc) => {
1717
- const tool = currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name);
1718
- return !['AskUserQuestion', 'Advisor', 'AdvisorDecision', 'OptimizeConversation', 'AgentReport', 'AgentResolve'].includes(tc.function.name)
1719
- && (tool?.isConcurrencySafe ?? getToolByName(tc.function.name)?.isConcurrencySafe) === true;
1144
+ const { runOne, failureReviews } = createToolExecutor({
1145
+ options,
1146
+ runtimeContext,
1147
+ toolCallContext,
1148
+ currentEffectiveToolSet,
1149
+ advisorCoordinator,
1150
+ stallGuard,
1151
+ modelEnvironmentCwd,
1152
+ observedRuleScopes,
1153
+ pendingRuleScopes,
1154
+ currentUserMessageId: userMessage.id!,
1155
+ executeToolFn,
1720
1156
  });
1721
1157
 
1722
1158
  let anyAborted = false;
@@ -1725,49 +1161,51 @@ export async function* runQuery(
1725
1161
  // settled. Both paths use this single writer, avoiding duplicate observation.
1726
1162
  const commitOutcome = async function* ({ tc, result }: WorkerOutcome): AsyncGenerator<LoopEvent> {
1727
1163
  if (tc.function.name !== 'Advisor' && tc.function.name !== 'AdvisorDecision') {
1728
- advisorCoordinator.observeToolResult(tc, result, advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name), { treatVerificationAsReadOnly: true }));
1164
+ advisorCoordinator.observeToolResult(
1165
+ tc,
1166
+ result,
1167
+ advisorSemanticsFor(
1168
+ tc,
1169
+ toolCallContext,
1170
+ currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name),
1171
+ { treatVerificationAsReadOnly: true },
1172
+ ),
1173
+ );
1729
1174
  }
1730
1175
  if (result.ok || result.disposition !== 'deferred') {
1731
1176
  evidenceLedger.record(tc.function.name, tc.function.arguments, result);
1732
1177
  }
1733
1178
  if (!result.ok && result.error === 'aborted') anyAborted = true;
1734
1179
  const browserArtifact =
1735
- result.ok && result.metadata?.kind === 'browser_download'
1736
- ? result.metadata.artifact
1737
- : undefined;
1180
+ result.ok && result.metadata?.kind === 'browser_download' ? result.metadata.artifact : undefined;
1738
1181
  if (
1739
1182
  result.ok &&
1740
- ((tc.function.name === 'PresentResult' &&
1741
- result.metadata?.kind === 'result_manifest') ||
1742
- browserArtifact)
1183
+ ((tc.function.name === 'PresentResult' && result.metadata?.kind === 'result_manifest') || browserArtifact)
1743
1184
  ) {
1744
1185
  resultPresented = true;
1745
1186
  // `not_run` only says that no optional, format-specific validator was
1746
1187
  // invoked. The PresentResult boundary has still checked the file and
1747
1188
  // persisted its fingerprint, so it must not downgrade a normal delivery.
1748
- const manifest =
1749
- result.metadata?.kind === 'result_manifest'
1750
- ? result.metadata.manifest
1751
- : browserArtifact;
1752
- presentedResultUnverified ||=
1753
- manifest?.files.some((file) => file.verification === 'failed') ??
1754
- false;
1189
+ const manifest = result.metadata?.kind === 'result_manifest' ? result.metadata.manifest : browserArtifact;
1190
+ presentedResultUnverified ||= manifest?.files.some((file) => file.verification === 'failed') ?? false;
1755
1191
  }
1756
1192
  const rawContent = result.ok ? result.content : `Error: ${result.error}`;
1757
1193
  const basePolicy = result.policy ?? getToolResultPolicy(tc.function.name);
1758
1194
  // 超大结果先归档再压缩:归档失败时保留原文,绝不因为磁盘问题破坏上下文。
1759
- const archived = result.ok && sessionState
1760
- ? await archiveToolResult(rawContent, sessionState.microCompact.archiveKey, tc.function.name)
1761
- : { content: rawContent, originalChars: rawContent.length };
1195
+ const archived =
1196
+ result.ok && sessionState && !(basePolicy.boundedWindow && basePolicy.archiveRef)
1197
+ ? await archiveToolResult(rawContent, sessionState.microCompact.archiveKey, tc.function.name)
1198
+ : { content: rawContent, originalChars: rawContent.length };
1762
1199
  // 归档退化必须发声:撞会话上限后每条超长结果都退回原文塞进上下文,
1763
1200
  // 也就是这个机制本来要解决的问题原样回来了 —— 静默的话没人会发现。
1764
1201
  if (archived.degraded && !archiveDegradedWarned) {
1765
1202
  archiveDegradedWarned = true;
1766
1203
  yield {
1767
1204
  type: 'warning',
1768
- message: archived.degraded === 'session-limit'
1769
- ? '工具结果归档已达本会话上限,后续超长结果将直接进入上下文(归档不再生效)。建议 /new 开新会话。'
1770
- : '工具结果归档写盘失败,后续超长结果将直接进入上下文。请检查磁盘空间与权限。',
1205
+ message:
1206
+ archived.degraded === 'session-limit'
1207
+ ? '工具结果归档已达本会话上限,后续超长结果将直接进入上下文(归档不再生效)。建议 /new 开新会话。'
1208
+ : '工具结果归档写盘失败,后续超长结果将直接进入上下文。请检查磁盘空间与权限。',
1771
1209
  };
1772
1210
  }
1773
1211
  const policy = archived.archiveRef
@@ -1785,9 +1223,12 @@ export async function* runQuery(
1785
1223
  tool_result_policy: policy,
1786
1224
  ...(!result.ok && result.disposition === 'deferred' ? { toolResultDisposition: 'deferred' as const } : {}),
1787
1225
  ...(tc === toolCallsByIndex.at(-1) ? { advisorCheckpoints: advisorCoordinator.drainDegradations() } : {}),
1788
- advisorMutatesWorkspace: advisorSemanticsFor(tc, toolCallContext,
1789
- currentEffectiveToolSet.tools.find(tool => tool.name === tc.function.name),
1790
- { treatVerificationAsReadOnly: true }).mutatesWorkspace,
1226
+ advisorMutatesWorkspace: advisorSemanticsFor(
1227
+ tc,
1228
+ toolCallContext,
1229
+ currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name),
1230
+ { treatVerificationAsReadOnly: true },
1231
+ ).mutatesWorkspace,
1791
1232
  ...(result.metadata ? { display_metadata: result.metadata } : {}),
1792
1233
  timestamp: Date.now(),
1793
1234
  id: crypto.randomUUID(),
@@ -1795,137 +1236,47 @@ export async function* runQuery(
1795
1236
  });
1796
1237
  };
1797
1238
 
1798
- const settled: WorkerOutcome[] = [];
1799
- let questionEncountered = false;
1800
- let advisorEncountered = false;
1801
-
1802
- for (const segment of segments) {
1803
- if (!questionEncountered && !advisorEncountered && segment.length > 1) {
1804
- // —— 并行:事件队列把各 worker 的 start/end 按真实完成顺序交错 yield 给 UI。
1805
- const queue: LoopEvent[] = [];
1806
- let signalNew: (() => void) | null = null;
1807
- const enqueue = (ev: LoopEvent) => {
1808
- queue.push(ev);
1809
- signalNew?.();
1810
- signalNew = null;
1811
- };
1812
-
1813
- // 默认并发 = 本轮工具调用数,即不设人为上限(orderedPool 内部本就会
1814
- // Math.min(concurrency, items.length))——这批工具已经过 allConcurrencySafe
1815
- // 判定全部只读/并发安全,能同时跑多少纯是吞吐量问题,不是正确性问题;宿主仍可显式传
1816
- // options.toolConcurrency 收紧("并发安全"不等于"内存/子进程/provider 配额无限",
1817
- // 真有这类顾虑应由宿主按自己的资源预算显式传值,而不是内核替所有宿主悄悄封顶)。
1818
- // ⚠️ 这条默认值曾被 9ce9be61 那次子Agent/浏览器重构悄悄改回 8——那次改动是照着一份
1819
- // 更早的 loop.ts 打的 diff,没带上这里的注释,属于历史真空期的意外覆盖,不是刻意
1820
- // 重新评估后的决定;发现后原样恢复。
1821
- const allDone = orderedPool(segment, options.toolConcurrency ?? segment.length, async (tc) => {
1822
- enqueue(startEvent(tc));
1823
- const o = await runOne(tc, (message, detail) => enqueue({
1824
- type: 'tool_progress',
1825
- toolCallId: tc.id,
1826
- toolName: tc.function.name,
1827
- message,
1828
- detail,
1829
- }));
1830
- enqueue(endEvent(o));
1831
- return o;
1832
- });
1833
-
1834
- let finished = false;
1835
- const wakeDone = () => {
1836
- finished = true;
1837
- signalNew?.();
1838
- signalNew = null;
1839
- };
1840
- void allDone.then(wakeDone, wakeDone);
1841
-
1842
- while (!finished || queue.length > 0) {
1843
- while (queue.length > 0) yield queue.shift()!;
1844
- if (finished) break;
1845
- await new Promise<void>((r) => {
1846
- signalNew = r;
1847
- });
1848
- }
1849
-
1850
- const outcomes = await allDone;
1851
- settled.push(...outcomes);
1852
- for (const outcome of outcomes) yield* commitOutcome(outcome);
1853
- } else {
1854
- // —— 串行:逐个执行(含写类工具,或只有一个工具)。事件直接顺序 yield,无需队列。
1855
- for (const tc of segment) {
1856
- if (questionEncountered || advisorEncountered) {
1857
- const outcome = { tc, result: { ok: false as const, disposition: 'deferred' as const,
1858
- error: questionEncountered
1859
- ? '此调用在用户回答前已生成,尚未执行。请先阅读提问结果并重新规划;仅在仍必要时重新调用。'
1860
- : '此调用在顾问返回前已生成,尚未执行。请先阅读顾问结果,自主决定采纳、部分采纳或拒绝,再重新生成必要的工具调用。咨询失败则自行判断继续,不必重复咨询。' } };
1861
- yield startEvent(tc);
1862
- yield endEvent(outcome);
1863
- settled.push(outcome);
1864
- yield* commitOutcome(outcome);
1865
- continue;
1866
- }
1867
- questionEncountered = tc.function.name === 'AskUserQuestion';
1868
- yield startEvent(tc);
1869
- const queue: LoopEvent[] = [];
1870
- let wake: (() => void) | null = null;
1871
- let finished = false;
1872
- const worker = runOne(tc, (message, detail) => {
1873
- queue.push({
1874
- type: 'tool_progress',
1875
- toolCallId: tc.id,
1876
- toolName: tc.function.name,
1877
- message,
1878
- detail,
1879
- });
1880
- wake?.();
1881
- wake = null;
1882
- }).finally(() => {
1883
- finished = true;
1884
- wake?.();
1885
- wake = null;
1886
- });
1887
- while (!finished || queue.length > 0) {
1888
- while (queue.length > 0) yield queue.shift()!;
1889
- if (finished) break;
1890
- await new Promise<void>((resolve) => { wake = resolve; });
1891
- }
1892
- const o = await worker;
1893
- // Every later call was planned without this second opinion, including
1894
- // decision records and further consultations. Return control to the LLM.
1895
- advisorEncountered = tc.function.name === 'Advisor';
1896
- yield endEvent(o);
1897
- settled.push(o);
1898
- yield* commitOutcome(o);
1899
- }
1900
- }
1901
- }
1902
-
1903
-
1239
+ const settled = yield* executeToolBatch({
1240
+ toolCallsByIndex,
1241
+ currentEffectiveToolSet,
1242
+ options,
1243
+ runOne,
1244
+ commitOutcome,
1245
+ });
1904
1246
 
1905
1247
  // Publish after every pending tool result has been appended, so hosts see a
1906
1248
  // complete protocol chain when persisting the compacted history.
1907
1249
  while (optimizationEvents.length > 0) yield optimizationEvents.shift()!;
1908
1250
  const childHandoff = options.agentHandoff?.current();
1909
1251
  if (childHandoff && childHandoff.kind !== 'help') {
1910
- yield { type: 'turn_done', completionStatus: childHandoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
1252
+ yield {
1253
+ type: 'turn_done',
1254
+ completionStatus: childHandoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
1911
1255
  warning: childHandoff.kind === 'blocked' ? '子任务已交回主 Agent 接力' : undefined,
1912
- usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
1256
+ usage: {
1257
+ ...turnUsage,
1258
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
1259
+ },
1260
+ };
1913
1261
  return;
1914
1262
  }
1915
1263
 
1916
1264
  // Failures are recorded at execution time; batch observation now supplements
1917
1265
  // them with the existing no-progress signal without counting attempts twice.
1918
- const stall = failureReviews.at(-1) ?? (turn + 1 < maxTurns
1919
- ? stallGuard.observe(
1920
- settled.map((item) => item.tc),
1921
- settled.map((item) => item.result),
1922
- assistantText,
1923
- )
1924
- : { stalled: false as const });
1266
+ const stall =
1267
+ failureReviews.at(-1) ??
1268
+ (turn + 1 < maxTurns
1269
+ ? stallGuard.observe(
1270
+ settled.map((item) => item.tc),
1271
+ settled.map((item) => item.result),
1272
+ assistantText,
1273
+ )
1274
+ : { stalled: false as const });
1925
1275
  if (stall.stalled) {
1926
- const message = stall.reason === 'repeated_failure'
1927
- ? '同一问题两次尝试失败,请停止原样重试;顾问可用时,继续解决或交付前先咨询,由主 Agent 自行核验和决策。只读诊断仍可继续。'
1928
- : '检测到连续工具轮次没有产生新文本或新结果;请切换路径或咨询 Advisor。';
1276
+ const message =
1277
+ stall.reason === 'repeated_failure'
1278
+ ? '同一问题两次尝试失败,请停止原样重试;顾问可用时,继续解决或交付前先咨询,由主 Agent 自行核验和决策。只读诊断仍可继续。'
1279
+ : '检测到连续工具轮次没有产生新文本或新结果;请切换路径或咨询 Advisor。';
1929
1280
  if (stall.reason !== 'repeated_failure') advisorCoordinator.notifyStalled(stall.signature ?? stall.reason);
1930
1281
  yield { type: 'warning', message };
1931
1282
  }
@@ -1936,7 +1287,9 @@ export async function* runQuery(
1936
1287
  let injectedShot: Message | null = null;
1937
1288
  try {
1938
1289
  injectedShot = await injectVisionFollowups(history, settled, provider);
1939
- } catch { /* 截图回填失败不影响主流程 */ }
1290
+ } catch {
1291
+ /* 截图回填失败不影响主流程 */
1292
+ }
1940
1293
  // The history copy is intentionally downgraded after the turn. Emit a detached snapshot
1941
1294
  // so TUI/Desktop stores do not see their already-rendered image mutate underneath them.
1942
1295
  if (injectedShot) {
@@ -1972,256 +1325,3 @@ export async function* runQuery(
1972
1325
  code: 'max_turns',
1973
1326
  };
1974
1327
  }
1975
-
1976
- // ---------------- 辅助函数 ----------------
1977
-
1978
- /**
1979
- * 易变上下文只存在于 provider 请求副本中,不会进入会话历史。
1980
- */
1981
- export const SYSTEM_REMINDER_OPEN = '<system-reminder>';
1982
- export const SYSTEM_REMINDER_CLOSE = '</system-reminder>';
1983
-
1984
- /**
1985
- * Attach transient context to the current turn's user message in a model-only
1986
- * clone. Later tool-loop requests reuse the same decorated message, making each
1987
- * serialized request a strict prefix extension of the previous one.
1988
- */
1989
- export function buildModelMessages(
1990
- history: Message[],
1991
- transientContext?: string,
1992
- currentUserMessageId?: string,
1993
- ): Message[] {
1994
- history = history.filter(message => !(message.role === 'system' && message._ephemeral));
1995
- const transient = transientContext?.trim();
1996
- if (!transient) return history;
1997
- let index = currentUserMessageId
1998
- ? history.findIndex((message) => message.role === 'user' && message.id === currentUserMessageId)
1999
- : -1;
2000
- if (index < 0) {
2001
- for (let cursor = history.length - 1; cursor >= 0; cursor--) {
2002
- if (history[cursor]?.role === 'user') {
2003
- index = cursor;
2004
- break;
2005
- }
2006
- }
2007
- }
2008
- if (index < 0) return history;
2009
- const target = history[index];
2010
- if (target.role !== 'user') return history;
2011
- const reminder = `${SYSTEM_REMINDER_OPEN}\n${transient}\n${SYSTEM_REMINDER_CLOSE}`;
2012
- const content = typeof target.content === 'string'
2013
- ? `${target.content}\n\n${reminder}`
2014
- : [...target.content, { type: 'text' as const, text: reminder }];
2015
- const next = [...history];
2016
- next[index] = { ...target, content };
2017
- return next;
2018
- }
2019
-
2020
- // 关键节点图像核验的合成消息标记:既是给模型的提示前缀,也是 evictPriorVisionShots 识别旧图消息的锚。
2021
- export const VISION_SHOT_MARKER = '【实况图像】';
2022
-
2023
- /**
2024
- * 历史标记。这套机制最初只有 WebBrowser 用得上,文案写死了「浏览器」;
2025
- * 现在 Bash 的 ATTACH_IMAGE sentinel 也能产图(屏幕截图 / 生成的产物),文案必须中性。
2026
- * 但**持久化会话里仍存着旧前缀的消息**,淘汰逻辑必须继续认它 ——
2027
- * 否则老会话里的旧截图永远不会被降级,图片一路累积撑爆上下文。
2028
- */
2029
- const LEGACY_VISION_SHOT_MARKERS = ['【浏览器实况截图】'] as const;
2030
-
2031
- const VISION_SHOT_PROMPT = `${VISION_SHOT_MARKER}上面是刚才工具执行后附带的真实图像(浏览器页面 / 屏幕截图 / 生成的产物)。请仔细看图核对:是否真的到达/呈现了你预期的状态?若与预期不符(空白/报错/弹窗遮挡/验证拦截/内容不对),不要假设成功,如实说明并调整下一步。`;
2032
-
2033
- /** 一条 user 消息的文本是否是「实况图像」合成消息(含历史前缀)。 */
2034
- function isVisionShotText(text: string): boolean {
2035
- return (
2036
- text.startsWith(VISION_SHOT_MARKER) ||
2037
- LEGACY_VISION_SHOT_MARKERS.some((marker) => text.startsWith(marker))
2038
- );
2039
- }
2040
-
2041
- /**
2042
- * 把本轮工具附带的实况截图(ToolResult.visionImages)组装成一条带图 user 消息喂给模型自我核验。
2043
- * - 仅在模型明确支持识图时注入(provider.supportsVision === true);否则丢弃(不假装核验、也不给非视觉端点发图触发 400)。
2044
- * - 注入前先把历史里旧的截图消息降级为纯文字占位(evictPriorVisionShots),保证上下文里最多一张实况图,
2045
- * 避免图片累积撑爆上下文(呼应浏览器 ADR「高频帧只存内存、只持久化最终结果」)。
2046
- * - **失败的工具结果同样回填**:出错现场那张图往往比成功时更有信息量(权限弹窗、
2047
- * 验证拦截、意外的前台窗口)。此前这里要求 `ok === true`,逼得想附图的工具只能
2048
- * 把失败伪装成成功——见 types.ts 里 ToolResult 那段注释。
2049
- */
2050
- async function injectVisionFollowups(
2051
- history: Message[],
2052
- settled: { result: ToolResult }[],
2053
- provider: Provider,
2054
- ): Promise<Message | null> {
2055
- if (provider.supportsVision === false) return null;
2056
- const images = settled.flatMap((s) => s.result.visionImages ?? []);
2057
- if (images.length === 0) return null;
2058
- evictPriorVisionShots(history);
2059
- // 工具可以给自己这批图配一句说明(visionNote)。内核只负责把它拼在通用提示之后,
2060
- // 不解读内容——「这是一组 1Hz 连续帧」这类语义只有产图的工具知道。
2061
- const notes = settled
2062
- .flatMap((s) => (s.result.visionNote ? [s.result.visionNote] : []))
2063
- .filter((note, index, all) => all.indexOf(note) === index);
2064
- const text = notes.length > 0
2065
- ? `${VISION_SHOT_PROMPT}\n\n${notes.join('\n\n')}`
2066
- : VISION_SHOT_PROMPT;
2067
- const content = await buildUserContent({ text, images });
2068
- const msg: Message = { role: 'user', content, timestamp: Date.now(), id: crypto.randomUUID() };
2069
- history.push(msg);
2070
- return msg;
2071
- }
2072
-
2073
- /** 把历史里旧的实况图像 user 消息降级为纯文字占位、剔除其图片,释放上下文(只保留最近一张真图)。 */
2074
- function evictPriorVisionShots(history: Message[]): void {
2075
- for (const msg of history) {
2076
- if (msg.role !== 'user' || !Array.isArray(msg.content)) continue;
2077
- const textPart = msg.content.find((p) => p.type === 'text');
2078
- if (textPart?.type === 'text' && isVisionShotText(textPart.text)) {
2079
- msg.content = `${VISION_SHOT_MARKER}(此前的实况图像已从上下文移除以节省空间。)`;
2080
- }
2081
- }
2082
- }
2083
-
2084
- /**
2085
- * 用户按ESC手动中断
2086
- */
2087
- function pushManualInterruptMarker(history: Message[]): void {
2088
- history.push({
2089
- role: 'user',
2090
- content: '(用户按下了 ESC/Ctrl+C 中断了任务。等待用户新指令。)',
2091
- timestamp: Date.now(),
2092
- id: crypto.randomUUID(),
2093
- });
2094
- }
2095
-
2096
- /**
2097
- * 有新的用户输入在队列中,当前安全停靠
2098
- */
2099
- function pushQueuedInputMarker(history: Message[]): void {
2100
- history.push({
2101
- role: 'user',
2102
- content: [
2103
- '(系统提示:用户在工作过程中发送了新的消息。',
2104
- '你现在看到的是上一轮工作在被打断前已完成的部分。',
2105
- '请阅读用户的新消息,判断:',
2106
- '1. 如果是不相关的新任务:简要确认已收到,转向新任务,可在新任务完成后询问是否回到之前工作',
2107
- '2. 如果是补充信息或前置依赖:把新信息纳入考虑,判断是否需要调整已做的工作,然后继续',
2108
- '3. 如果是改变方向或取消:评估已完成的部分,说明你对变更的理解,按新方向推进)',
2109
- ].join('\n'),
2110
- timestamp: Date.now(),
2111
- id: crypto.randomUUID(),
2112
- });
2113
- }
2114
-
2115
- /** 把一条 tool_call_delta 合并到累积数组上 */
2116
- function mergeToolCallDelta(
2117
- acc: ToolCall[],
2118
- ev: {
2119
- index: number;
2120
- id?: string;
2121
- name?: string;
2122
- argumentsDelta?: string;
2123
- },
2124
- ): void {
2125
- let slot = acc[ev.index];
2126
- if (!slot) {
2127
- slot = {
2128
- id: '',
2129
- type: 'function',
2130
- function: { name: '', arguments: '' },
2131
- };
2132
- acc[ev.index] = slot;
2133
- }
2134
- if (ev.id) slot.id = ev.id;
2135
- if (ev.name) slot.function.name += ev.name;
2136
- if (ev.argumentsDelta) slot.function.arguments += ev.argumentsDelta;
2137
- }
2138
-
2139
- /** 给 UI 展示用的参数预览(只取前 60 字符) */
2140
- function previewArgs(rawJson: string): string {
2141
- const oneLine = rawJson.replace(/\s+/g, ' ').trim();
2142
- if (oneLine.length <= 60) return oneLine;
2143
- return oneLine.slice(0, 60) + '...';
2144
- }
2145
-
2146
- /**
2147
- * 把工具名 + raw arguments JSON 转换成人话描述。
2148
- * UI 优先用这个显示在 spinner 行(如 "Reading src/foo.ts")。
2149
- * 已知工具走 switch;未知工具或 JSON parse 失败 fallback 到 `${toolName}(...)`。
2150
- */
2151
- function friendlyToolDescription(toolName: string, rawArgsJson: string, fileLabel?: (path: string) => string): string {
2152
- let args: Record<string, unknown> = {};
2153
- try {
2154
- args = JSON.parse(rawArgsJson) ?? {};
2155
- } catch {
2156
- return `${toolName}(...)`;
2157
- }
2158
- const truncate = (s: unknown, n: number): string => {
2159
- if (typeof s !== 'string') return '';
2160
- return s.length > n ? s.slice(0, n) + '…' : s;
2161
- };
2162
- const file = (value: unknown): string => {
2163
- if (typeof value !== 'string') return '';
2164
- if (fileLabel) return fileLabel(value);
2165
- return value.length > 64 ? `…${value.slice(-63)}` : value;
2166
- };
2167
- switch (toolName) {
2168
- case 'Skill': return `技能 · ${truncate(args.name, 60)}`;
2169
- case 'SearchSkills': return `查找技能 · ${truncate(args.query, 60)}`;
2170
- case 'Advisor': {
2171
- const reasons: Record<string, string> = { plan_review: '执行前评审', delivery_review: '交付前核验', stalled: '分析重复失败', uncertainty: '核查不确定问题', user_dissatisfaction: '复核用户反馈', evidence_conflict: '核查证据冲突' };
2172
- return `咨询顾问 · ${reasons[String(args.reason)] ?? '独立第二意见'}`;
2173
- }
2174
- case 'AdvisorDecision': return `顾问建议 · ${truncate(args.decision ?? args.action, 40) || '记录核验与采纳结论'}`;
2175
- case 'AskUserQuestion': return '询问关键决策';
2176
- case 'PresentResult': return '提交成果与验证结果';
2177
- case 'PowerShell': return `运行 PowerShell · ${truncate(args.description ?? args.command, 60)}`;
2178
- case 'OptimizeConversation': return '优化对话';
2179
- case 'Read': return `Reading ${file(args.file_path)}`;
2180
- case 'Edit': return `Editing ${file(args.file_path)}`;
2181
- case 'MultiEdit': {
2182
- const n = Array.isArray(args.edits) ? args.edits.length : 0;
2183
- return `Editing ${file(args.file_path)}${n ? ` (${n} 处)` : ''}`;
2184
- }
2185
- case 'Write': return `Writing ${file(args.file_path)}`;
2186
- case 'Trash': return `Moving to Trash ${file(args.file_path ?? args.path)}`;
2187
- case 'ApplyPatch': {
2188
- const patch = typeof args.patch === 'string' ? args.patch : typeof args.input === 'string' ? args.input : '';
2189
- const files = [...patch.matchAll(/^\*\*\* (Add|Update|Delete) File: (.+)$/gm)].map(m => `${file(m[2])}(${({ Add: '新增', Update: '修改', Delete: '删除' } as Record<string, string>)[m[1]]})`);
2190
- if (!files.length) files.push(...[...patch.matchAll(/^\+\+\+ [ab]\/([^\n]+)$/gm)].map(m => file(m[1])));
2191
- return files.length > 0 ? `Editing ${files.join(', ')}` : 'Editing patch';
2192
- }
2193
- case 'NotebookEdit': return `Editing ${file(args.notebook_path ?? args.file_path)}`;
2194
- case 'Bash': return typeof args.description === 'string' && args.description.trim()
2195
- ? `运行 ${truncate(args.description, 70)}` : `Running \`${truncate(args.command, 40)}\``;
2196
- case 'Grep': {
2197
- const p = truncate(args.pattern, 30);
2198
- const g = typeof args.glob === 'string' && args.glob.length > 0 ? ` in ${truncate(args.glob, 25)}` : '';
2199
- return `Searching \`${p}\`${g}`;
2200
- }
2201
- case 'Glob': return `Globbing \`${truncate(args.pattern, 50)}\``;
2202
- case 'WebBrowser': {
2203
- const actions: Record<string, string> = { start: '启动', navigate: '打开页面', screenshot: '截图', snapshot: '读取页面', click: '点击', fill: '填写', evaluate: '执行页面脚本', close: '关闭', stop: '停止', console: '查看控制台', network: '查看网络请求' };
2204
- let target = '';
2205
- try { target = new URL(String(args.url)).host; } catch { /* no URL for local actions */ }
2206
- return `浏览器 · ${actions[String(args.action)] ?? (truncate(args.action, 32) || '操作页面')}${target ? ` · ${target}` : ''}`;
2207
- }
2208
- case 'WebFetch': {
2209
- try {
2210
- return `Fetching ${new URL(String(args.url)).host}`;
2211
- } catch {
2212
- return `Fetching ...`;
2213
- }
2214
- }
2215
- case 'BrowserBatch': return `浏览器 · ${truncate(args.action, 30) || '批量操作'}(${Array.isArray(args.steps) ? args.steps.length : 0} 步)`;
2216
- case 'BrowserCDP': return `浏览器调试 · ${truncate(String(args.method ?? args.operation ?? ''), 45)}`;
2217
- case 'WebSearch': return `Searching \`${truncate(args.query, 50)}\``;
2218
- case 'Agent': {
2219
- const t = typeof args.agent_type === 'string' ? args.agent_type : 'explore';
2220
- return `子任务[${t}] ${truncate(args.description, 50)}`;
2221
- }
2222
- default: return `${toolName} · ${truncate(args.description ?? args.action ?? args.operation, 60) || '执行工具操作'}`;
2223
- }
2224
- }
2225
-
2226
- // 导出供测试用(friendlyToolDescription 是 module-private 纯函数)
2227
- export { friendlyToolDescription };