minimal-agent 0.18.10 → 0.18.11

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.
package/src/loop.js CHANGED
@@ -1,175 +1,60 @@
1
+ import { DELIVERY_CORRECTION_REMINDER, expectsFormalDelivery } from './loop/deliveryIntent.js';
2
+ import { buildModelMessages, evictPriorVisionShots, injectVisionFollowups, mergeToolCallDelta, pushManualInterruptMarker, pushQueuedInputMarker, } from './loop/messages.js';
3
+ import { publishFinalAnswer } from './loop/publication.js';
4
+ import { prepareModelRequest } from './loop/requestPreparation.js';
5
+ import { executeToolBatch } from './loop/toolBatch.js';
6
+ import { createToolExecutor } from './loop/toolExecutor.js';
7
+ import { advisorSemanticsFor } from './loop/toolSemantics.js';
8
+ export { expectsFormalDelivery } from './loop/deliveryIntent.js';
9
+ export { buildModelMessages, SYSTEM_REMINDER_CLOSE, SYSTEM_REMINDER_OPEN, VISION_SHOT_MARKER, } from './loop/messages.js';
10
+ export { friendlyToolDescription } from './loop/toolPresentation.js';
11
+ export { advisorSemanticsFor } from './loop/toolSemantics.js';
1
12
  /**
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
- * ============================================================
13
+ * Agent turn orchestrator. Owns conversation state and continuation decisions.
14
+ * Request preparation, tool execution/scheduling and final publication live in
15
+ * ./loop/. Host options and LoopEvent remain the public compatibility boundary.
16
+ * See ./loop/README.md for phase ownership and invariants.
28
17
  */
29
18
  import crypto from 'node:crypto';
30
- import { answerPreparationNotice } from './runtime/answerPreparation.js';
31
- import { finalAnswerMessages } from './runtime/finalAnswer.js';
32
- import { resolveOutputContract, toolsForResponsePhase } from './runtime/outputContract.js';
33
- import { needsDiagramPreparation, visualPresentation } from './prompts/visualPresentation.js';
34
- import { createLifecycleTrace } from './runtime/lifecycleTrace.js';
35
- import { conciseToolPath } from './runtime/toolDisplay.js';
36
- import { dirname, resolve } from 'node:path';
37
- import { loadProjectPromptInstructions } from './prompts/projectInstructions.js';
38
- import { resolveToolPath } from './tools/shared/fileUtils.js';
39
- import { invocationInstructions, invocationToolAllowed } from './runtime/invocationPolicy.js';
40
- import { needsInteractiveQuestion } from './tools/ask/routing.js';
41
- import { autoCompactIfNeeded, getCompactThreshold, shouldAutoCompact } from './context/compact.js';
19
+ import { resolve } from 'node:path';
20
+ import { AdvisorCoordinator } from './advisor/advisorCoordinator.js';
21
+ import { collectReviewContext } from './advisor/reviewContext.js';
22
+ import { configService } from './config/configService.js';
23
+ import { buildContextBudgetPlan } from './context/budgetPlan.js';
24
+ import { getCompactThreshold } from './context/compact.js';
25
+ import { assembleContextBundle, contextFragment, resizeContextBundle } from './context/contextBundle.js';
26
+ import { expireOldEntries, getToolResultPolicy, incrementTurn, microCompact, reclaimOldToolResults, resetCacheEdits, } from './context/microCompactLite.js';
42
27
  import { createConversationOptimizer } from './context/optimizeConversation.js';
43
- import { microCompact, incrementTurn, expireOldEntries, reclaimOldToolResults, resetCacheEdits, getToolResultPolicy, } from './context/microCompactLite.js';
44
- import { isPromptTooLongError, reactiveCompactIfApplicable, } from './context/reactiveCompact.js';
45
- import { snipCompactIfNeeded } from './context/snipCompact.js';
28
+ import { isPromptTooLongError, reactiveCompactIfApplicable } from './context/reactiveCompact.js';
29
+ import { countMessagesTokens, estimateToolsTokens } from './context/tokenCounter.js';
46
30
  import { archiveToolResult } from './context/toolResultArchive.js';
47
- import { countMessagesTokens, countTextTokens, estimateToolsTokens, } from './context/tokenCounter.js';
48
- import { buildContextBudgetPlan, fitToolsForEmergency } from './context/budgetPlan.js';
49
- import { assembleContextBundle, contextFragment, resizeContextBundle } from './context/contextBundle.js';
31
+ import { validateFinalClaims } from './harness/claimValidation.js';
32
+ import { EvidenceLedger } from './harness/evidenceLedger.js';
33
+ import { StallGuard } from './harness/stallGuard.js';
50
34
  import { chat as defaultChat } from './llm/client.js';
51
35
  import { buildUserContent } from './multimodal.js';
52
- import { ALL_TOOLS, executeTool as defaultExecuteTool, getToolByName, getToolGateDetails, } from './tools/index.js';
53
- import { createReadBudget } from './tools/shared/readBudget.js';
54
- import { configService } from './config/configService.js';
36
+ import { delegationRuntimeGuidance } from './prompts/delegation.js';
37
+ import { capabilitiesForTools, enabledPolicyIds } from './prompts/policyRegistry.js';
38
+ import { loadProjectPromptInstructions } from './prompts/projectInstructions.js';
39
+ import { needsDiagramPreparation, visualPresentation } from './prompts/visualPresentation.js';
40
+ import { createAgentRuntimeContext } from './runtime/agentRuntimeContext.js';
41
+ import { answerPreparationNotice } from './runtime/answerPreparation.js';
42
+ import { invocationInstructions, invocationToolAllowed } from './runtime/invocationPolicy.js';
43
+ import { createLifecycleTrace } from './runtime/lifecycleTrace.js';
44
+ import { resolveOutputContract, toolsForResponsePhase } from './runtime/outputContract.js';
45
+ import { filterToolsForProvider } from './team/toolPolicy.js';
46
+ import { agentCoordinationContext, takeAgentNotifications } from './tools/agent/agentTaskService.js';
47
+ import { needsInteractiveQuestion } from './tools/ask/routing.js';
55
48
  import { capabilityForToolName } from './tools/capabilities.js';
56
- import { createEffectiveToolSet } from './tools/effectiveToolSet.js';
57
49
  import { classifyComputerAutomationIntent } from './tools/computeruse/computerIntent.js';
58
50
  import { recordComputerUseExposure } from './tools/computeruse/telemetryLog.js';
59
- import { filterToolsForProvider } from './team/toolPolicy.js';
51
+ import { createEffectiveToolSet } from './tools/effectiveToolSet.js';
52
+ import { ALL_TOOLS, executeTool as defaultExecuteTool } from './tools/index.js';
53
+ import { createReadBudget } from './tools/shared/readBudget.js';
60
54
  import { hydrateSessionWorktree } from './tools/worktree/sessionWorktree.js';
61
- import { capabilitiesForTools, enabledPolicyIds, } from './prompts/policyRegistry.js';
62
- import { EvidenceLedger } from './harness/evidenceLedger.js';
63
- import { StallGuard } from './harness/stallGuard.js';
64
- import { validateFinalClaims } from './harness/claimValidation.js';
65
- import { AdvisorCoordinator, } from './advisor/advisorCoordinator.js';
66
- import { toolEffectFor } from './tools/capabilities.js';
67
- import { isReadOnlyShellCommand, isVerificationShellCommand } from './tools/bash/semantics.js';
68
- import { collectReviewContext } from './advisor/reviewContext.js';
69
- import { createAgentRuntimeContext, } from './runtime/agentRuntimeContext.js';
70
55
  import { stripThinkBlocks } from './utils/stripThink.js';
71
- import { orderedPool } from './runtime/orderedPool.js';
72
- import { takeAgentNotifications, agentCoordinationContext } from './tools/agent/agentTaskService.js';
73
- import { delegationRuntimeGuidance } from './prompts/delegation.js';
74
- import { executionSegments } from './tools/executionSegments.js';
75
- import { acquireSubagentLease, normalizeWriteScopes } from './tools/agent/coordinator.js';
76
- const DELIVERY_ARTIFACT = '(?:文件|合同|协议|方案|文档|表格|报告|图片|图像|海报|幻灯片|PPT|PDF|代码|脚本|压缩包|网页|页面|HTML|DOCX|XLSX|CSV|ZIP)';
77
- const DELIVERY_ACTION = '(?:发送|(?<![开研])发|交付|提交|(?<!宣)传(?!统)|制作|生成|创建|导出|输出|修改|更新|完成|写|起草|做|设计|整理)';
78
- const ENGLISH_DELIVERY_ARTIFACT = '(?:file|contract|document|report|spreadsheet|workbook|slides?|presentation|pdf|image|code|script|archive|zip|html|webpage|website)';
79
- const ENGLISH_DELIVERY_ACTION = '(?:send|deliver|submit|provide|create|generate|export|update|modify|finish|produce|draft|write|make|build)';
80
- /** Whether this turn explicitly asks for a concrete artifact that should be formally delivered. */
81
- export function expectsFormalDelivery(input) {
82
- // Questions about producing artifacts are not instructions to produce them.
83
- // Evaluate clauses independently so “解释原因,然后生成报告” still delivers.
84
- const clauses = input.split(/[。!?!?;;\n]|然后|随后|并且/).filter(Boolean);
85
- return clauses.some(expectsDeliveryClause);
86
- }
87
- function expectsDeliveryClause(input) {
88
- if (/为什么|为何|如何|怎么|怎样|是否|能否|能不能|不要|不必|无需|只(?:需|要)?(?:解释|分析|评估|讨论)|\b(?:why|how|whether|explain|analy[sz]e|discuss|do not|don't)\b/i.test(input))
89
- return false;
90
- const compact = input.replace(/\s+/g, '');
91
- const chinese = new RegExp(`${DELIVERY_ACTION}(?:给)?我?.{0,24}${DELIVERY_ARTIFACT}|${DELIVERY_ARTIFACT}.{0,24}${DELIVERY_ACTION}(?:给)?我?|给我.{0,24}${DELIVERY_ARTIFACT}|${DELIVERY_ARTIFACT}.{0,24}给我`, 'i');
92
- const english = new RegExp(`\\b${ENGLISH_DELIVERY_ACTION}\\b.{0,80}\\b${ENGLISH_DELIVERY_ARTIFACT}\\b|\\b${ENGLISH_DELIVERY_ARTIFACT}\\b.{0,80}\\b${ENGLISH_DELIVERY_ACTION}\\b`, 'i');
93
- return chinese.test(compact) || english.test(input);
94
- }
95
- const DELIVERY_CORRECTION_REMINDER = `The user requested a concrete final deliverable, but no successful PresentResult call has been made.
96
- Do not repeat the answer or mention a path only. Call PresentResult now with the actual final files and/or final http(s) links.
97
- Submit only final outputs, never temporary scripts, unpacked assets, caches, or reference sources. If no valid result exists, explain that honestly without inventing one.`;
98
- /**
99
- * 每轮 LLM 请求都会带上工具 schema,但 countMessagesTokens 只数历史消息、
100
- * 漏了这部分 → 系统性低估。autoCompact 判定阈值时加上它才准。
101
- *
102
- * ⚠️ 必须懒求值而非模块顶层求值:Agent 工具引入了 tools/index → agent → loop →
103
- * tools/index 的模块环,若从 tools/index 一侧先进入,顶层求值 ALL_TOOLS 时它还在
104
- * TDZ(临时死区),启动即 ReferenceError。函数体内访问时模块图早已初始化完毕。
105
- */
106
- /**
107
- * 本轮**真正发出去的**工具 schema 估算 token 数。
108
- *
109
- * 曾经这里数的是 `ALL_TOOLS`,那是错的:每回合发给模型的是 `activeTools`,
110
- * 会被 `allowedTools`(工作流步骤 / 子 agent 收窄)、`subagents.enabled`、
111
- * `computerRun` 是否注入等条件过滤掉一部分。ComputerUse 单个工具的 schema
112
- * 实测就有 ~5800 token(全量 ~18000 的三分之一),在没暴露它的会话里照样
113
- * 被计入压缩阈值 → **压缩提前触发**;被 `allowed_tools` 收窄到两三个工具的
114
- * 子 agent 偏差更大。
115
- *
116
- * 缓存必须按工具集**键控**:模块级单值缓存配上按回合变化的工具集,会让所有
117
- * 后续回合都拿到第一回合那个数字 —— 比不缓存更糟,因为它错得很稳定。
118
- */
119
- const toolsSchemaTokensCache = new Map();
120
- function getToolsSchemaTokens(tools, signature) {
121
- const key = signature ?? tools.map((t) => t.name).join(',');
122
- let cached = toolsSchemaTokensCache.get(key);
123
- if (cached === undefined) {
124
- cached = estimateToolsTokens(tools);
125
- toolsSchemaTokensCache.set(key, cached);
126
- }
127
- return cached;
128
- }
129
56
  /** 主工具循环的默认轮数上限。 */
130
57
  export const DEFAULT_MAX_TURNS = 200;
131
- export function advisorSemanticsFor(call, context, tool,
132
- // 默认 false:只有 advisor 检查点/记账(beforeTool、observeToolResult、
133
- // 持久化的 advisorMutatesWorkspace 标注)才传 true。工作区租约判定
134
- // (needsWorkspaceLease)必须保持严格定义不受影响——验证类命令仍可能写
135
- // 构建产物/缓存,并发场景下让它绕开租约会重新引入竞态。
136
- opts) {
137
- const definition = tool ?? getToolByName(call.function.name);
138
- const gate = context ? getToolGateDetails(call.function.name, call.function.arguments, context) : undefined;
139
- // Reuse the tool's side-effect contract, including shell/scripts, Trash and
140
- // generation tools. Shell tools refine their generic writable declaration
141
- // using the actual command; the same result is also used by the host gate.
142
- let isReadOnly = gate?.isReadOnly ?? definition?.isReadOnly ?? false;
143
- if (call.function.name === 'Agent') {
144
- try {
145
- const args = JSON.parse(call.function.arguments || '{}');
146
- isReadOnly = !args.resume_agent_id && (args.agent_type ?? 'explore') === 'explore';
147
- }
148
- catch {
149
- isReadOnly = false;
150
- }
151
- }
152
- if (call.function.name === 'Bash' || call.function.name === 'PowerShell') {
153
- try {
154
- const input = JSON.parse(call.function.arguments || '{}');
155
- if (typeof input.command === 'string') {
156
- // 跑测试/构建/lint 只是核对现状,不该被当成"开始实施改动"而白白烧掉
157
- // pre-execution 检查点——即使它们可能写构建产物/缓存,不满足
158
- // isReadOnlyShellCommand 的并发安全定义(见 opts 注释,那个场景仍要严格)。
159
- isReadOnly =
160
- isReadOnlyShellCommand(input.command) ||
161
- (opts?.treatVerificationAsReadOnly === true &&
162
- isVerificationShellCommand(input.command));
163
- }
164
- }
165
- catch {
166
- // Malformed input is left writable; normal tool validation reports it.
167
- isReadOnly = false;
168
- }
169
- }
170
- const mutatesWorkspace = toolEffectFor(call.function.name, isReadOnly) === 'execution';
171
- return { mutatesWorkspace };
172
- }
173
58
  /**
174
59
  * 执行一次"用户输入 → 模型回答完成"的完整流程。
175
60
  *
@@ -181,25 +66,24 @@ export async function* runQuery(userInput, options) {
181
66
  // Never carry a prior turn's base64 image into a new user request.
182
67
  evictPriorVisionShots(history);
183
68
  const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
184
- const inferredDesktop = options.browserRun?.supervised === true ||
185
- options.browserRun?.viewer === 'desktop';
186
- const baseRuntimeContext = options.runtimeContext ?? createAgentRuntimeContext({
187
- surface: inferredDesktop ? 'desktop' : 'headless',
188
- ...(inferredDesktop ? { host: 'desktop' } : {}),
189
- profile: 'main',
190
- cwd: process.cwd(),
191
- workspaceId: options.memoryContext?.workspaceId,
192
- sessionId: options.memoryContext?.sessionId,
193
- owner: options.memoryContext?.access !== 'denied' ? 'local-owner' : 'untrusted',
194
- memoryAccess: options.memoryContext?.access ?? 'denied',
195
- interactiveAsk: false,
196
- browser: options.browserRun,
197
- computer: options.computerRun,
198
- computerIntervention: options.computerIntervention,
199
- toolGate: options.toolGate,
200
- });
201
- const computerIntent = baseRuntimeContext.computerIntent
202
- ?? classifyComputerAutomationIntent(userInput, sessionState?.computerAutomation);
69
+ const inferredDesktop = options.browserRun?.supervised === true || options.browserRun?.viewer === 'desktop';
70
+ const baseRuntimeContext = options.runtimeContext ??
71
+ createAgentRuntimeContext({
72
+ surface: inferredDesktop ? 'desktop' : 'headless',
73
+ ...(inferredDesktop ? { host: 'desktop' } : {}),
74
+ profile: 'main',
75
+ cwd: process.cwd(),
76
+ workspaceId: options.memoryContext?.workspaceId,
77
+ sessionId: options.memoryContext?.sessionId,
78
+ owner: options.memoryContext?.access !== 'denied' ? 'local-owner' : 'untrusted',
79
+ memoryAccess: options.memoryContext?.access ?? 'denied',
80
+ interactiveAsk: false,
81
+ browser: options.browserRun,
82
+ computer: options.computerRun,
83
+ computerIntervention: options.computerIntervention,
84
+ toolGate: options.toolGate,
85
+ });
86
+ const computerIntent = baseRuntimeContext.computerIntent ?? classifyComputerAutomationIntent(userInput, sessionState?.computerAutomation);
203
87
  const runtimeContext = createAgentRuntimeContext({
204
88
  ...baseRuntimeContext,
205
89
  computerIntent,
@@ -221,7 +105,9 @@ export async function* runQuery(userInput, options) {
221
105
  const observedRuleScopes = new Map();
222
106
  const pendingRuleScopes = new Set();
223
107
  const transientFor = (tools) => {
224
- const opaque = [options.transientContext?.trim(), invocationInstructions(options.invocationPolicy)].filter(Boolean).join('\n\n');
108
+ const opaque = [options.transientContext?.trim(), invocationInstructions(options.invocationPolicy)]
109
+ .filter(Boolean)
110
+ .join('\n\n');
225
111
  const bundle = currentTransientBundle;
226
112
  if (!bundle)
227
113
  return opaque;
@@ -232,9 +118,7 @@ export async function* runQuery(userInput, options) {
232
118
  transientContext: opaque,
233
119
  });
234
120
  const availableForBundle = Math.max(0, basePlan.inputLimit - basePlan.historyTokens - basePlan.toolTokens - basePlan.transientTokens);
235
- const selected = availableForBundle >= bundle.diagnostics.usedTokens
236
- ? bundle
237
- : resizeContextBundle(bundle, availableForBundle);
121
+ const selected = availableForBundle >= bundle.diagnostics.usedTokens ? bundle : resizeContextBundle(bundle, availableForBundle);
238
122
  advisorContextBundle = selected;
239
123
  return [selected.text, opaque].filter(Boolean).join('\n\n');
240
124
  };
@@ -256,18 +140,43 @@ export async function* runQuery(userInput, options) {
256
140
  const toolCallContext = {
257
141
  output,
258
142
  availableToolNames: () => currentEffectiveToolSet.names,
259
- executionServices: { ...options.executionServices, executeTool: executeToolFn, chat: chatFn, invocationPolicy: options.invocationPolicy },
143
+ executionServices: {
144
+ ...options.executionServices,
145
+ executeTool: executeToolFn,
146
+ chat: chatFn,
147
+ invocationPolicy: options.invocationPolicy,
148
+ },
260
149
  history,
261
150
  sessionState,
262
151
  advisorReviewContext: () => ({
263
152
  ...collectReviewContext(advisorContextBundle),
264
- constraints: [...collectReviewContext(advisorContextBundle).constraints,
265
- { id: 'execution.boundary', authority: 'host', content: JSON.stringify({ cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
266
- conversationMode: toolCallContext.conversationMode, profile: runtimeContext.profile,
267
- availableTools: [...currentEffectiveToolSet.names], invocation: invocationInstructions(options.invocationPolicy) }) }],
268
- omittedIds: [...new Set([...(currentTransientBundle?.diagnostics.omittedIds ?? []), ...(advisorContextBundle?.diagnostics.omittedIds ?? [])]),
269
- ...(options.transientContext ? ['legacy.transient-context:not-forwarded'] : [])],
270
- clippedIds: [...new Set([...(currentTransientBundle?.diagnostics.clippedIds ?? []), ...(advisorContextBundle?.diagnostics.clippedIds ?? [])])],
153
+ constraints: [
154
+ ...collectReviewContext(advisorContextBundle).constraints,
155
+ {
156
+ id: 'execution.boundary',
157
+ authority: 'host',
158
+ content: JSON.stringify({
159
+ cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
160
+ conversationMode: toolCallContext.conversationMode,
161
+ profile: runtimeContext.profile,
162
+ availableTools: [...currentEffectiveToolSet.names],
163
+ invocation: invocationInstructions(options.invocationPolicy),
164
+ }),
165
+ },
166
+ ],
167
+ omittedIds: [
168
+ ...new Set([
169
+ ...(currentTransientBundle?.diagnostics.omittedIds ?? []),
170
+ ...(advisorContextBundle?.diagnostics.omittedIds ?? []),
171
+ ]),
172
+ ...(options.transientContext ? ['legacy.transient-context:not-forwarded'] : []),
173
+ ],
174
+ clippedIds: [
175
+ ...new Set([
176
+ ...(currentTransientBundle?.diagnostics.clippedIds ?? []),
177
+ ...(advisorContextBundle?.diagnostics.clippedIds ?? []),
178
+ ]),
179
+ ],
271
180
  }),
272
181
  // Statistics only; consultations have no per-turn quota.
273
182
  advisorCalls: { used: 0 },
@@ -297,10 +206,10 @@ export async function* runQuery(userInput, options) {
297
206
  // 传入数组时严格按数组过滤,[] 表示本轮不下发任何工具。
298
207
  // 同时约束模型可见工具和本循环实际执行的工具。
299
208
  const hostTools = filterToolsForProvider(options.availableTools ?? ALL_TOOLS, provider);
300
- const availableTools = hostTools.filter((tool) => invocationToolAllowed(tool.name, options.invocationPolicy)
301
- && (tool.name !== 'Agent' || subagents.enabled)
302
- && (tool.name !== 'ComputerUse'
303
- || (runtimeContext.computer !== undefined && runtimeContext.computerIntent?.needed === true)));
209
+ const availableTools = hostTools.filter((tool) => invocationToolAllowed(tool.name, options.invocationPolicy) &&
210
+ (tool.name !== 'Agent' || subagents.enabled) &&
211
+ (tool.name !== 'ComputerUse' ||
212
+ (runtimeContext.computer !== undefined && runtimeContext.computerIntent?.needed === true)));
304
213
  const effectiveToolSet = createEffectiveToolSet({
305
214
  availableTools,
306
215
  runtime: runtimeContext,
@@ -308,10 +217,10 @@ export async function* runQuery(userInput, options) {
308
217
  requiredNames: options.requiredTools,
309
218
  });
310
219
  const activeTools = effectiveToolSet.tools;
311
- const formalDeliveryRequired = explicitFileDeliveryRequested
312
- && runtimeContext.profile === 'main'
313
- && options.invocationPolicy?.delivery !== 'caller'
314
- && effectiveToolSet.names.has('PresentResult');
220
+ const formalDeliveryRequired = explicitFileDeliveryRequested &&
221
+ runtimeContext.profile === 'main' &&
222
+ options.invocationPolicy?.delivery !== 'caller' &&
223
+ effectiveToolSet.names.has('PresentResult');
315
224
  let currentEffectiveToolSet = effectiveToolSet;
316
225
  const advisorCoordinator = new AdvisorCoordinator({
317
226
  history,
@@ -330,28 +239,37 @@ export async function* runQuery(userInput, options) {
330
239
  const parts = [
331
240
  transientFor(activeTools),
332
241
  coordinationText,
333
- delegationRuntimeGuidance({ available: runtimeContext.profile === 'main' && currentEffectiveToolSet.names.has('Agent'),
334
- maxConcurrent: subagents.maxConcurrent, callsUsed: toolCallContext.agentCalls?.used ?? 0,
335
- maxCalls: toolCallContext.agentCalls?.max ?? 0 }),
242
+ delegationRuntimeGuidance({
243
+ available: runtimeContext.profile === 'main' && currentEffectiveToolSet.names.has('Agent'),
244
+ maxConcurrent: subagents.maxConcurrent,
245
+ callsUsed: toolCallContext.agentCalls?.used ?? 0,
246
+ maxCalls: toolCallContext.agentCalls?.max ?? 0,
247
+ }),
336
248
  diagramPreparationAttempted ? visualPresentation(output) : '',
337
- delegationCorrectionAttempted ? '本轮必要子任务尚未验收或接管完成。先读取结果、等待运行任务或完成接力,使用 AgentResolve 记录判断;若确实无法完成,明确报告缺口,不声称全部完成。' : '',
338
- askCorrectionAttempted ? '当前交互宿主支持 AskUserQuestion。若仍需用户选择或补充,请调用该工具一次只问一个问题,等待答案后继续;不要仅在正文列问后停止。若没有待决事项则正常回答,不必提问。' : '',
339
- emptyResponseRecoveryAttempted ? `上一次模型响应没有可交付正文(${emptyResponseRecoveryReason})。请基于已有历史和工具结果继续完成任务:信息充分则给出实质结论,不充分则继续必要操作或明确缺口。不要重复已经完成的调查或有副作用的操作;不要把未完成的任务说成完成。已有顾问意见继续有效,无需仅因恢复而再次咨询。` : '',
249
+ delegationCorrectionAttempted
250
+ ? '本轮必要子任务尚未验收或接管完成。先读取结果、等待运行任务或完成接力,使用 AgentResolve 记录判断;若确实无法完成,明确报告缺口,不声称全部完成。'
251
+ : '',
252
+ askCorrectionAttempted
253
+ ? '当前交互宿主支持 AskUserQuestion。若仍需用户选择或补充,请调用该工具一次只问一个问题,等待答案后继续;不要仅在正文列问后停止。若没有待决事项则正常回答,不必提问。'
254
+ : '',
255
+ emptyResponseRecoveryAttempted
256
+ ? `上一次模型响应没有可交付正文(${emptyResponseRecoveryReason})。请基于已有历史和工具结果继续完成任务:信息充分则给出实质结论,不充分则继续必要操作或明确缺口。不要重复已经完成的调查或有副作用的操作;不要把未完成的任务说成完成。已有顾问意见继续有效,无需仅因恢复而再次咨询。`
257
+ : '',
340
258
  deliveryCorrectionAttempted && !resultPresented ? DELIVERY_CORRECTION_REMINDER : '',
341
259
  advisorAvailable ? advisorCoordinator.transientReminder() : '',
342
- advisorAvailable
343
- ? advisorCoordinator.usageLine(toolCallContext.advisorCalls.used)
344
- : '',
260
+ advisorAvailable ? advisorCoordinator.usageLine(toolCallContext.advisorCalls.used) : '',
345
261
  ];
346
262
  return parts.filter(Boolean).join('\n\n');
347
263
  };
348
264
  let lastRequestTransientContext = [options.transientBundle?.text, options.transientContext]
349
- .filter(Boolean).join('\n\n');
265
+ .filter(Boolean)
266
+ .join('\n\n');
350
267
  const evidenceLedger = new EvidenceLedger();
351
268
  const stallGuard = new StallGuard();
352
269
  const harnessDiagnostics = (stopReason) => ({
353
270
  promptVersion: 'minimal-agent:prompt:v2',
354
- basePromptHash: crypto.createHash('sha256')
271
+ basePromptHash: crypto
272
+ .createHash('sha256')
355
273
  .update(history[0]?.role === 'system' ? history[0].content : '')
356
274
  .digest('hex'),
357
275
  enabledPolicyIds: enabledPolicyIds({
@@ -361,9 +279,11 @@ export async function* runQuery(userInput, options) {
361
279
  capabilities: capabilitiesForTools(currentEffectiveToolSet.tools),
362
280
  toolNames: currentEffectiveToolSet.names,
363
281
  }),
364
- enabledCapabilities: [...new Set(currentEffectiveToolSet.tools
282
+ enabledCapabilities: [
283
+ ...new Set(currentEffectiveToolSet.tools
365
284
  .map((tool) => capabilityForToolName(tool.name))
366
- .filter((capability) => Boolean(capability)))],
285
+ .filter((capability) => Boolean(capability))),
286
+ ],
367
287
  effectiveToolSetSignature: currentEffectiveToolSet.signature,
368
288
  tokenBudget: buildContextBudgetPlan({
369
289
  provider,
@@ -404,8 +324,7 @@ export async function* runQuery(userInput, options) {
404
324
  message: `未作为图片附加:${skipped.source}(${skipped.reason}),已按普通文本处理。`,
405
325
  };
406
326
  }
407
- let visionRequiredThisTurn = Array.isArray(userContent)
408
- && userContent.some((part) => part.type === 'image_url' || part.type === 'video_url');
327
+ let visionRequiredThisTurn = Array.isArray(userContent) && userContent.some((part) => part.type === 'image_url' || part.type === 'video_url');
409
328
  if (visionRequiredThisTurn && provider.supportsVision === false) {
410
329
  yield {
411
330
  type: 'error',
@@ -464,14 +383,15 @@ export async function* runQuery(userInput, options) {
464
383
  };
465
384
  const optimizationEvents = [];
466
385
  toolCallContext.optimizeConversation = createConversationOptimizer({
467
- history, provider,
386
+ history,
387
+ provider,
468
388
  // This additional model call must contribute to the turn's resource ledger,
469
389
  // without replacing the main model's context/cache usage measurements.
470
390
  chat: async function* (args) {
471
391
  turnUsage.totalCalls += 1;
472
392
  for await (const event of chatFn(args)) {
473
- if (event.type === 'done'
474
- && (typeof event.promptTokens === 'number' || typeof event.outputTokens === 'number')) {
393
+ if (event.type === 'done' &&
394
+ (typeof event.promptTokens === 'number' || typeof event.outputTokens === 'number')) {
475
395
  turnUsage.reportedCalls += 1;
476
396
  turnUsage.inputTokens += event.promptTokens ?? 0;
477
397
  turnUsage.outputTokens += event.outputTokens ?? 0;
@@ -480,8 +400,9 @@ export async function* runQuery(userInput, options) {
480
400
  }
481
401
  },
482
402
  promptCache: options.promptCache,
483
- replaceHistory, hasQueuedInput: options.hasQueuedInput,
484
- onCompacted: event => optimizationEvents.push(event),
403
+ replaceHistory,
404
+ hasQueuedInput: options.hasQueuedInput,
405
+ onCompacted: (event) => optimizationEvents.push(event),
485
406
  });
486
407
  const interruption = () => {
487
408
  if (options.hasQueuedInput?.()) {
@@ -502,19 +423,38 @@ export async function* runQuery(userInput, options) {
502
423
  }
503
424
  modelEnvironmentCwd = nextEnvironmentCwd;
504
425
  try {
505
- const rules = await loadProjectPromptInstructions(modelEnvironmentCwd) ?? '';
426
+ const rules = (await loadProjectPromptInstructions(modelEnvironmentCwd)) ?? '';
506
427
  observedRuleScopes.set(resolve(modelEnvironmentCwd), rules);
507
428
  for (const scope of new Set([...observedRuleScopes.keys(), ...pendingRuleScopes])) {
508
429
  if (scope !== resolve(modelEnvironmentCwd))
509
- observedRuleScopes.set(scope, await loadProjectPromptInstructions(scope) ?? '');
430
+ observedRuleScopes.set(scope, (await loadProjectPromptInstructions(scope)) ?? '');
510
431
  }
511
432
  pendingRuleScopes.clear();
512
- const mergedRules = await loadProjectPromptInstructions(modelEnvironmentCwd, [...observedRuleScopes.keys()]) ?? '';
433
+ const mergedRules = (await loadProjectPromptInstructions(modelEnvironmentCwd, [...observedRuleScopes.keys()])) ?? '';
513
434
  currentTransientBundle = assembleContextBundle([
514
- ...(options.transientBundle?.fragments ?? []).filter(f => f.id !== 'project.instructions' && f.id !== 'runtime.execution-environment'),
515
- contextFragment({ id: 'runtime.execution-environment', kind: 'runtime', authority: 'host', priority: 100, required: true, atomic: true,
516
- content: `当前有效执行目录:${modelEnvironmentCwd}。此宿主快照替换旧执行目录;项目规则以本次快照为准,旧历史中的版本不再生效。${rules ? '' : '当前目录及父目录没有适用的项目规则文件,旧规则不得恢复。'}工具权限仍以本次有效工具集和宿主闸门为准。` }),
517
- ...(mergedRules ? [contextFragment({ id: 'project.instructions', kind: 'project', authority: 'constraint', priority: 90, required: true, atomic: true, content: mergedRules })] : []),
435
+ ...(options.transientBundle?.fragments ?? []).filter((f) => f.id !== 'project.instructions' && f.id !== 'runtime.execution-environment'),
436
+ contextFragment({
437
+ id: 'runtime.execution-environment',
438
+ kind: 'runtime',
439
+ authority: 'host',
440
+ priority: 100,
441
+ required: true,
442
+ atomic: true,
443
+ content: `当前有效执行目录:${modelEnvironmentCwd}。此宿主快照替换旧执行目录;项目规则以本次快照为准,旧历史中的版本不再生效。${rules ? '' : '当前目录及父目录没有适用的项目规则文件,旧规则不得恢复。'}工具权限仍以本次有效工具集和宿主闸门为准。`,
444
+ }),
445
+ ...(mergedRules
446
+ ? [
447
+ contextFragment({
448
+ id: 'project.instructions',
449
+ kind: 'project',
450
+ authority: 'constraint',
451
+ priority: 90,
452
+ required: true,
453
+ atomic: true,
454
+ content: mergedRules,
455
+ }),
456
+ ]
457
+ : []),
518
458
  ], options.transientBundle?.diagnostics.budgetTokens);
519
459
  }
520
460
  catch (error) {
@@ -524,12 +464,18 @@ export async function* runQuery(userInput, options) {
524
464
  }
525
465
  const handoff = options.agentHandoff?.current();
526
466
  if (handoff && handoff.kind !== 'help') {
527
- yield { type: 'turn_done', completionStatus: handoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
467
+ yield {
468
+ type: 'turn_done',
469
+ completionStatus: handoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
528
470
  warning: handoff.kind === 'blocked' ? '子任务已交回主 Agent 接力' : undefined,
529
- usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
471
+ usage: {
472
+ ...turnUsage,
473
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
474
+ },
475
+ };
530
476
  return;
531
477
  }
532
- history.push(...(options.takePendingMessages?.() ?? []), ...await takeAgentNotifications(toolCallContext));
478
+ history.push(...(options.takePendingMessages?.() ?? []), ...(await takeAgentNotifications(toolCallContext)));
533
479
  if (runtimeContext.profile === 'main')
534
480
  coordinationText = (await agentCoordinationContext(toolCallContext)).text;
535
481
  incrementTurn(sessionState?.microCompact);
@@ -563,175 +509,51 @@ export async function* runQuery(userInput, options) {
563
509
  }
564
510
  return;
565
511
  }
566
- // 2. 自动压缩(判据 = max(上一轮真实 usage, 历史估算 + 工具 schema),
567
- // 阈值 provider 无关、按 contextWindow × compactRatio 比例触发)
568
- let requestTransientContext = buildRequestTransientContext();
569
- lastRequestTransientContext = requestTransientContext;
570
- const preCompactBudget = buildContextBudgetPlan({
571
- provider,
512
+ const prepared = yield* prepareModelRequest({
572
513
  history,
573
- tools: activeTools,
574
- transientContext: requestTransientContext,
575
- });
576
- if (preCompactBudget.overBudget || lastPromptTokens !== undefined) {
577
- try {
578
- const compactOptions = {
579
- actualPromptTokens: lastPromptTokens,
580
- toolsTokens: getToolsSchemaTokens(activeTools, effectiveToolSet.signature),
581
- transientTokens: countTextTokens(requestTransientContext),
582
- // cacheEdits 判据校正:本地 history 未瘦身,扣掉服务端已删部分的估算,
583
- // 防止虚高估算劫持 Math.max 导致压缩过早触发(压缩会重建整个前缀缓存)。
584
- ...(cacheEditsMode && sessionState?.microCompact
585
- ? { serverDeletedTokens: sessionState.microCompact.cacheEdits.activeDeletedTokens }
586
- : {}),
587
- signal,
588
- promptCache: options.promptCache,
589
- chat: chatFn,
590
- };
591
- if (shouldAutoCompact(history, provider, compactOptions)) {
592
- yield { type: 'compact_start' };
593
- yield { type: 'stage_change', stage: 'compacting' };
594
- }
595
- const compact = await autoCompactIfNeeded(history, provider, compactOptions);
596
- if (compact.compacted) {
597
- replaceHistory(compact.messages);
598
- yield {
599
- type: 'compact_done',
600
- before: compact.before,
601
- after: compact.after,
602
- trigger: 'threshold',
603
- mode: compact.mode,
604
- degraded: compact.degraded,
605
- ...(compact.fallbackReason ? { fallbackReason: compact.fallbackReason } : {}),
606
- ...(compact.messagesRemoved !== undefined ? { messagesRemoved: compact.messagesRemoved } : {}),
607
- ...(compact.tokensFreed !== undefined ? { tokensFreed: compact.tokensFreed } : {}),
608
- };
609
- yield { type: 'stage_change', stage: 'thinking' };
610
- }
611
- }
612
- catch (e) {
613
- if (signal?.aborted || e.name === 'AbortError') {
614
- yield interruption();
615
- return;
616
- }
617
- // 压缩失败不要让整个对话挂掉:先 snip 砍最老消息释放空间再继续。
618
- let recovered = false;
619
- try {
620
- const before = countMessagesTokens(history);
621
- const snipped = snipCompactIfNeeded(history, { force: true, snipPercent: 0.3 });
622
- if (snipped.messagesRemoved > 0) {
623
- replaceHistory(snipped.messages);
624
- recovered = true;
625
- yield {
626
- type: 'compact_done',
627
- before,
628
- after: countMessagesTokens(history),
629
- trigger: 'threshold',
630
- mode: 'snip-fallback',
631
- degraded: true,
632
- fallbackReason: 'llm-error',
633
- messagesRemoved: snipped.messagesRemoved,
634
- tokensFreed: snipped.tokensFreed,
635
- };
636
- }
637
- }
638
- catch {
639
- /* snip 也失败 → 真的只能硬上 */
640
- }
641
- if (!recovered) {
642
- // 事件是 provider 原始报错唯一该去的地方:只到 stderr / UI,不进 history、
643
- // 不落盘、不会在后续轮次重新发给模型(compact.ts 里那条降级消息因此保持无错误体)。
644
- yield {
645
- type: 'error',
646
- error: `自动压缩失败,规则式截断也未能释放空间;已继续尝试回答:${e.message}`,
647
- code: 'compact_failed',
648
- };
649
- }
650
- }
651
- }
652
- // Re-open transient capacity after compaction. If the compacted tail is still
653
- // too large, trim old history before sacrificing any model-visible ability.
654
- requestTransientContext = buildRequestTransientContext();
655
- lastRequestTransientContext = requestTransientContext;
656
- let postCompactBudget = buildContextBudgetPlan({
657
514
  provider,
658
- history,
659
- tools: activeTools,
660
- transientContext: requestTransientContext,
661
- });
662
- if (postCompactBudget.overBudget) {
663
- const before = countMessagesTokens(history);
664
- const snipped = snipCompactIfNeeded(history, { force: true, snipPercent: 0.3 });
665
- if (snipped.messagesRemoved > 0) {
666
- replaceHistory(snipped.messages);
667
- yield {
668
- type: 'compact_done',
669
- before,
670
- after: countMessagesTokens(history),
671
- trigger: 'post-budget',
672
- mode: 'snip-fallback',
673
- degraded: true,
674
- fallbackReason: 'still-over-budget',
675
- messagesRemoved: snipped.messagesRemoved,
676
- tokensFreed: snipped.tokensFreed,
677
- };
678
- requestTransientContext = buildRequestTransientContext();
679
- lastRequestTransientContext = requestTransientContext;
680
- postCompactBudget = buildContextBudgetPlan({
681
- provider,
682
- history,
683
- tools: activeTools,
684
- transientContext: requestTransientContext,
685
- });
686
- }
687
- }
688
- const emergencyFit = fitToolsForEmergency({
689
- provider,
690
- history,
691
- tools: activeTools,
692
- transientContext: requestTransientContext,
693
- requiredNames: effectiveToolSet.requiredNames,
694
- });
695
- currentEffectiveToolSet = emergencyFit.removedNames.length === 0
696
- ? effectiveToolSet
697
- : createEffectiveToolSet({
698
- availableTools: emergencyFit.tools,
699
- runtime: runtimeContext,
700
- requiredNames: [...effectiveToolSet.requiredNames],
701
- });
702
- advisorCoordinator.setAvailable(currentEffectiveToolSet.names.has('Advisor'));
703
- // Tool availability may change during emergency fitting. Rebuild dynamic
704
- // guidance against the actual request boundary, then account for its size.
705
- requestTransientContext = buildRequestTransientContext();
706
- lastRequestTransientContext = requestTransientContext;
707
- const finalRequestBudget = buildContextBudgetPlan({
708
- provider, history, tools: currentEffectiveToolSet.tools,
709
- transientContext: requestTransientContext,
515
+ activeTools,
516
+ effectiveToolSet,
517
+ runtimeContext,
518
+ sessionState,
519
+ signal,
520
+ lastPromptTokens,
521
+ cacheEditsMode,
522
+ options,
523
+ chatFn,
524
+ replaceHistory,
525
+ buildRequestTransientContext: (tools) => {
526
+ currentEffectiveToolSet = tools;
527
+ advisorCoordinator.setAvailable(tools.names.has('Advisor'));
528
+ lastRequestTransientContext = buildRequestTransientContext();
529
+ return lastRequestTransientContext;
530
+ },
710
531
  });
711
- if (emergencyFit.removedNames.length > 0) {
712
- yield {
713
- type: 'warning',
714
- message: `当前模型窗口压力过高,本次请求临时省略工具 Schema:${emergencyFit.removedNames.join(', ')};下一轮会重新评估并恢复。`,
715
- };
532
+ if (prepared.kind === 'interrupted') {
533
+ yield interruption();
534
+ return;
716
535
  }
717
- toolCallContext.reserveReadChars = createReadBudget(finalRequestBudget.inputLimit - finalRequestBudget.totalInputTokens);
718
- if (finalRequestBudget.overBudget) {
719
- yield {
720
- type: 'error',
721
- error: `当前请求即使经过上下文降级仍需要约 ${finalRequestBudget.totalInputTokens} tokens,超过模型输入上限 ${finalRequestBudget.inputLimit}。已停止发送,避免 Provider 接收必然失败的超限请求。`,
722
- code: 'context_overflow',
723
- };
536
+ if (prepared.kind === 'overflow') {
724
537
  yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('error') };
725
538
  return;
726
539
  }
540
+ const requestTransientContext = prepared.requestTransientContext;
541
+ currentEffectiveToolSet = prepared.currentEffectiveToolSet;
542
+ toolCallContext.reserveReadChars = createReadBudget(prepared.remainingTokens);
727
543
  // 3. 调 LLM 并组装 assistant 消息
728
544
  trace('model_start');
729
545
  let assistantText = '';
730
546
  // Candidate text is private until the delivery gates allow publication.
731
547
  // Keep the compatibility event as a phase notice, never as a text retraction.
732
548
  function* retireDraft(reason) {
733
- const message = { role: 'system', content: answerPreparationNotice(reason), id: crypto.randomUUID(),
734
- timestamp: Date.now(), _ephemeral: true, _uiProgress: true };
549
+ const message = {
550
+ role: 'system',
551
+ content: answerPreparationNotice(reason),
552
+ id: crypto.randomUUID(),
553
+ timestamp: Date.now(),
554
+ _ephemeral: true,
555
+ _uiProgress: true,
556
+ };
735
557
  history.push(message);
736
558
  yield { type: 'injected_message', message };
737
559
  if (reason !== 'interrupted')
@@ -767,12 +589,8 @@ export async function* runQuery(userInput, options) {
767
589
  promptCache: options.promptCache,
768
590
  visionPolicy: visionRequiredThisTurn ? 'required' : 'optional-history',
769
591
  // cacheEdits 回收状态(同一会话级对象跨轮复用;compact 后由 resetCacheEdits 清空)
770
- ...(cacheEditsMode && sessionState?.microCompact
771
- ? { cacheEdits: sessionState.microCompact.cacheEdits }
772
- : {}),
773
- ...(options.responseFormat
774
- ? { responseFormat: options.responseFormat }
775
- : {}),
592
+ ...(cacheEditsMode && sessionState?.microCompact ? { cacheEdits: sessionState.microCompact.cacheEdits } : {}),
593
+ ...(options.responseFormat ? { responseFormat: options.responseFormat } : {}),
776
594
  })) {
777
595
  if (ev.type === 'text_delta') {
778
596
  assistantText += ev.delta;
@@ -910,14 +728,19 @@ export async function* runQuery(userInput, options) {
910
728
  // A pending review must run before another solving/publishing attempt.
911
729
  // Read-only diagnosis and human questions remain available while stalled.
912
730
  const pendingReview = options.advisorCheckpoints === false ? undefined : advisorCoordinator.pendingReview();
913
- if (pendingReview && turn < maxTurns && toolCallsByIndex.length > 0
914
- && !toolCallsByIndex.some(tc => ['Advisor', 'AskUserQuestion'].includes(tc.function.name))
915
- && toolCallsByIndex.some(tc => tc.function.name === 'PresentResult'
916
- || advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find(t => t.name === tc.function.name), { treatVerificationAsReadOnly: true }).mutatesWorkspace
917
- || stallGuard.shouldReject(tc))) {
731
+ if (pendingReview &&
732
+ turn < maxTurns &&
733
+ toolCallsByIndex.length > 0 &&
734
+ !toolCallsByIndex.some((tc) => ['Advisor', 'AskUserQuestion'].includes(tc.function.name)) &&
735
+ toolCallsByIndex.some((tc) => tc.function.name === 'PresentResult' ||
736
+ advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((t) => t.name === tc.function.name), { treatVerificationAsReadOnly: true }).mutatesWorkspace ||
737
+ stallGuard.shouldReject(tc))) {
918
738
  yield* retireDraft('advisor_checkpoint');
919
- toolCallsByIndex.splice(0, toolCallsByIndex.length, { id: crypto.randomUUID(), type: 'function',
920
- function: { name: 'Advisor', arguments: JSON.stringify(pendingReview) } });
739
+ toolCallsByIndex.splice(0, toolCallsByIndex.length, {
740
+ id: crypto.randomUUID(),
741
+ type: 'function',
742
+ function: { name: 'Advisor', arguments: JSON.stringify(pendingReview) },
743
+ });
921
744
  assistantText = '';
922
745
  }
923
746
  // Count the calls that survived review scheduling, including failed loads.
@@ -928,7 +751,9 @@ export async function* runQuery(userInput, options) {
928
751
  if (JSON.parse(call.function.arguments).name === 'dynamic-ui')
929
752
  diagramPreparationAttempted = true;
930
753
  }
931
- catch { /* Ordinary tool validation reports malformed arguments. */ }
754
+ catch {
755
+ /* Ordinary tool validation reports malformed arguments. */
756
+ }
932
757
  }
933
758
  const assistantMsg = {
934
759
  role: 'assistant',
@@ -945,21 +770,31 @@ export async function* runQuery(userInput, options) {
945
770
  finalResponse: if (toolCallsByIndex.length === 0) {
946
771
  // Repair only private preparation, through the ordinary tool pipeline.
947
772
  // One attempt per turn, including missing/failed skills; never rewind a reply.
948
- if (!diagramPreparationAttempted && !options.responseFormat
949
- && runtimeContext.profile === 'main' && output.diagrams.length > 0
950
- && currentEffectiveToolSet.names.has('Skill') && turn < maxTurns
951
- && needsDiagramPreparation(assistantText, userInput)) {
773
+ if (!diagramPreparationAttempted &&
774
+ !options.responseFormat &&
775
+ runtimeContext.profile === 'main' &&
776
+ output.diagrams.length > 0 &&
777
+ currentEffectiveToolSet.names.has('Skill') &&
778
+ turn < maxTurns &&
779
+ needsDiagramPreparation(assistantText, userInput)) {
952
780
  diagramPreparationAttempted = true;
953
- toolCallsByIndex.push({ id: crypto.randomUUID(), type: 'function', function: {
954
- name: 'Skill', arguments: JSON.stringify({ name: 'dynamic-ui' }),
955
- } });
781
+ toolCallsByIndex.push({
782
+ id: crypto.randomUUID(),
783
+ type: 'function',
784
+ function: {
785
+ name: 'Skill',
786
+ arguments: JSON.stringify({ name: 'dynamic-ui' }),
787
+ },
788
+ });
956
789
  assistantMsg.content = null;
957
790
  assistantMsg.tool_calls = toolCallsByIndex;
958
791
  break finalResponse;
959
792
  }
960
- if (!askCorrectionAttempted && runtimeContext.interactiveAsk
961
- && currentEffectiveToolSet.names.has('AskUserQuestion')
962
- && needsInteractiveQuestion(stripThinkBlocks(assistantText)) && turn < maxTurns) {
793
+ if (!askCorrectionAttempted &&
794
+ runtimeContext.interactiveAsk &&
795
+ currentEffectiveToolSet.names.has('AskUserQuestion') &&
796
+ needsInteractiveQuestion(stripThinkBlocks(assistantText)) &&
797
+ turn < maxTurns) {
963
798
  askCorrectionAttempted = true;
964
799
  yield* retireDraft('interactive_question');
965
800
  continue;
@@ -973,7 +808,10 @@ export async function* runQuery(userInput, options) {
973
808
  yield* retireDraft('formal_delivery');
974
809
  continue;
975
810
  }
976
- const pendingMessages = [...(options.takePendingMessages?.() ?? []), ...await takeAgentNotifications(toolCallContext)];
811
+ const pendingMessages = [
812
+ ...(options.takePendingMessages?.() ?? []),
813
+ ...(await takeAgentNotifications(toolCallContext)),
814
+ ];
977
815
  if (pendingMessages.length) {
978
816
  history.push(...pendingMessages);
979
817
  continue;
@@ -981,10 +819,11 @@ export async function* runQuery(userInput, options) {
981
819
  // A model occasionally writes a path/link in prose and stops without formally
982
820
  // presenting it. Give it one model-only corrective pass; the reminder is
983
821
  // transient and therefore never pollutes persisted conversation history.
984
- if (!emptyResponse && formalDeliveryRequired
985
- && !resultPresented
986
- && !deliveryCorrectionAttempted
987
- && turn < maxTurns) {
822
+ if (!emptyResponse &&
823
+ formalDeliveryRequired &&
824
+ !resultPresented &&
825
+ !deliveryCorrectionAttempted &&
826
+ turn < maxTurns) {
988
827
  deliveryCorrectionAttempted = true;
989
828
  yield* retireDraft('formal_delivery');
990
829
  continue;
@@ -993,14 +832,20 @@ export async function* runQuery(userInput, options) {
993
832
  ? { allow: true }
994
833
  : advisorCoordinator.beforeDelivery(assistantText);
995
834
  const fallbackReview = !emptyResponse && options.advisorCheckpoints !== false
996
- ? advisorCoordinator.pendingReview(assistantText) : undefined;
835
+ ? advisorCoordinator.pendingReview(assistantText)
836
+ : undefined;
997
837
  if (fallbackReview && turn < maxTurns) {
998
838
  yield* retireDraft('advisor_checkpoint');
999
839
  // Reuse the effective tool boundary, permissions, cancellation, events and
1000
840
  // persistence. Never call a provider behind the host's tool pipeline.
1001
- toolCallsByIndex.push({ id: crypto.randomUUID(), type: 'function', function: {
1002
- name: 'Advisor', arguments: JSON.stringify(fallbackReview),
1003
- } });
841
+ toolCallsByIndex.push({
842
+ id: crypto.randomUUID(),
843
+ type: 'function',
844
+ function: {
845
+ name: 'Advisor',
846
+ arguments: JSON.stringify(fallbackReview),
847
+ },
848
+ });
1004
849
  assistantMsg.content = null;
1005
850
  assistantMsg.tool_calls = toolCallsByIndex;
1006
851
  break finalResponse;
@@ -1020,11 +865,20 @@ export async function* runQuery(userInput, options) {
1020
865
  // advisor state. Never replay tools or expose an empty candidate as an answer.
1021
866
  if (!resultPresented && !emptyResponseRecoveryAttempted && turn < maxTurns) {
1022
867
  emptyResponseRecoveryAttempted = true;
1023
- emptyResponseRecoveryReason = lastFinishReason === 'length'
1024
- ? '输出额度耗尽' : lastFinishReason === 'unknown'
1025
- ? '响应流缺少正常结束状态' : '响应为空或仅含思考内容';
1026
- const message = { role: 'system', content: '正在恢复回答,已保留调查结果与工作进展。',
1027
- id: crypto.randomUUID(), timestamp: Date.now(), _ephemeral: true, _uiProgress: true };
868
+ emptyResponseRecoveryReason =
869
+ lastFinishReason === 'length'
870
+ ? '输出额度耗尽'
871
+ : lastFinishReason === 'unknown'
872
+ ? '响应流缺少正常结束状态'
873
+ : '响应为空或仅含思考内容';
874
+ const message = {
875
+ role: 'system',
876
+ content: '正在恢复回答,已保留调查结果与工作进展。',
877
+ id: crypto.randomUUID(),
878
+ timestamp: Date.now(),
879
+ _ephemeral: true,
880
+ _uiProgress: true,
881
+ };
1028
882
  history.push(message);
1029
883
  yield { type: 'injected_message', message };
1030
884
  continue;
@@ -1037,85 +891,42 @@ export async function* runQuery(userInput, options) {
1037
891
  let publicationError;
1038
892
  let publicationInterrupted = false;
1039
893
  let streamed = false;
1040
- if (!options.responseFormat && runtimeContext.profile === 'main'
1041
- && output.finalDelivery === 'stream') {
1042
- const candidate = assistantText;
1043
- const candidateFinishReason = lastFinishReason;
1044
- let publishedText = '';
1045
- let publicationDone = false;
1046
- yield { type: 'stage_change', stage: 'streaming' };
1047
- try {
1048
- const publicationMessages = finalAnswerMessages(buildModelMessages(history, requestTransientContext, userMessage.id), assistantText, output);
1049
- const publicationPlan = buildContextBudgetPlan({ provider, history: publicationMessages, tools: [] });
1050
- if (publicationPlan.overBudget)
1051
- throw new Error('最终表达上下文超过模型输入上限,未发送请求。');
1052
- if (signal?.aborted || options.hasQueuedInput?.()) {
1053
- publicationInterrupted = true;
1054
- throw new Error('最终发布已取消。');
1055
- }
1056
- turnUsage.totalCalls += 1;
1057
- for await (const event of chatFn({
1058
- provider,
1059
- messages: publicationMessages,
1060
- tools: toolsForResponsePhase(currentEffectiveToolSet.tools, 'publication'), signal,
1061
- conversationMode: runtimeContext.conversationMode ?? 'private',
1062
- promptCache: options.promptCache,
1063
- })) {
1064
- if (event.type === 'done' && !publicationDone) {
1065
- publicationDone = true;
1066
- if (typeof event.promptTokens === 'number' || typeof event.outputTokens === 'number') {
1067
- turnUsage.reportedCalls += 1;
1068
- turnUsage.inputTokens += event.promptTokens ?? 0;
1069
- turnUsage.outputTokens += event.outputTokens ?? 0;
1070
- }
1071
- }
1072
- if (signal?.aborted || options.hasQueuedInput?.()) {
1073
- publicationInterrupted = true;
1074
- break;
1075
- }
1076
- if (event.type === 'text_delta') {
1077
- // Final expression is live generation, not an exact-copy replay.
1078
- // Once visible, text is never replaced or joined with a different draft.
1079
- publishedText += event.delta;
1080
- streamed = true;
1081
- yield { type: 'text', delta: event.delta };
1082
- }
1083
- else if (event.type === 'tool_call_delta') {
1084
- throw new Error('最终表达阶段返回了非预期工具调用,未执行该工具。');
1085
- }
1086
- else if (event.type === 'done') {
1087
- publicationDone = true;
1088
- lastFinishReason = event.stopReason;
1089
- if (event.stopReason === 'aborted')
1090
- publicationInterrupted = true;
1091
- }
1092
- }
1093
- if (!publicationDone && !publicationInterrupted)
1094
- throw new Error('最终答案流未正常结束。');
1095
- if (!publicationInterrupted && lastFinishReason !== 'stop' && lastFinishReason !== 'length')
1096
- throw new Error('最终答案流缺少有效的结束状态。');
1097
- if (!publishedText.trim() && !publicationInterrupted)
1098
- throw new Error('最终表达未返回正文。');
1099
- }
1100
- catch (error) {
1101
- publicationInterrupted ||= signal?.aborted === true || options.hasQueuedInput?.() === true || error?.name === 'AbortError';
1102
- publicationError = error;
1103
- }
1104
- if (publicationError && !publicationInterrupted && !publishedText) {
1105
- yield { type: 'warning', message: '最终回答流未能开始,已一次性显示内部准备的答案;未进行新的事实核验。' };
1106
- yield { type: 'text', delta: candidate };
1107
- streamed = true;
1108
- publishedText = candidate;
1109
- lastFinishReason = candidateFinishReason;
1110
- publicationError = undefined;
1111
- }
894
+ if (!options.responseFormat && runtimeContext.profile === 'main' && output.finalDelivery === 'stream') {
895
+ const publication = yield* publishFinalAnswer({
896
+ provider,
897
+ messages: buildModelMessages(history, requestTransientContext, userMessage.id),
898
+ candidate: assistantText,
899
+ candidateFinishReason: lastFinishReason,
900
+ output,
901
+ chatFn,
902
+ options,
903
+ signal,
904
+ conversationMode: runtimeContext.conversationMode ?? 'private',
905
+ turnUsage,
906
+ });
907
+ const publishedText = publication.text;
908
+ ({ publicationError, publicationInterrupted, streamed, lastFinishReason } = publication);
1112
909
  assistantText = publishedText;
1113
910
  assistantMsg.content = publishedText || null;
1114
911
  if (!publishedText) {
1115
912
  if (publicationInterrupted)
1116
- yield { ...interruption(), usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
913
+ yield {
914
+ ...interruption(),
915
+ usage: {
916
+ ...turnUsage,
917
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
918
+ },
919
+ };
1117
920
  else
1118
- yield { type: 'error', code: 'llm_error', error: `最终答案生成失败:${String(publicationError)}`, usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
921
+ yield {
922
+ type: 'error',
923
+ code: 'llm_error',
924
+ error: `最终答案生成失败:${String(publicationError)}`,
925
+ usage: {
926
+ ...turnUsage,
927
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
928
+ },
929
+ };
1119
930
  return;
1120
931
  }
1121
932
  }
@@ -1136,9 +947,23 @@ export async function* runQuery(userInput, options) {
1136
947
  if (publicationInterrupted || publicationError) {
1137
948
  yield { type: 'warning', message: '最终答案未完整生成,已保留已输出内容;未撤回或重新生成。' };
1138
949
  if (publicationInterrupted)
1139
- yield { ...interruption(), usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
950
+ yield {
951
+ ...interruption(),
952
+ usage: {
953
+ ...turnUsage,
954
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
955
+ },
956
+ };
1140
957
  else
1141
- yield { type: 'error', code: 'llm_error', error: `最终答案流中断:${String(publicationError)}`, usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
958
+ yield {
959
+ type: 'error',
960
+ code: 'llm_error',
961
+ error: `最终答案流中断:${String(publicationError)}`,
962
+ usage: {
963
+ ...turnUsage,
964
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
965
+ },
966
+ };
1142
967
  return;
1143
968
  }
1144
969
  }
@@ -1155,7 +980,7 @@ export async function* runQuery(userInput, options) {
1155
980
  // The final answer has already consumed the latest screenshot. Persist only a compact
1156
981
  // marker so the next turn does not resend a large screen image.
1157
982
  evictPriorVisionShots(history);
1158
- const estimatedTokens = countMessagesTokens(history) + getToolsSchemaTokens(activeTools);
983
+ const estimatedTokens = countMessagesTokens(history) + estimateToolsTokens(activeTools);
1159
984
  const usedTokens = Math.min(provider.contextWindow, Math.max(lastPromptTokens ?? 0, estimatedTokens));
1160
985
  yield { type: 'harness_diagnostics', diagnostics: harnessDiagnostics('complete') };
1161
986
  const claimValidation = validateFinalClaims(assistantText, evidenceLedger.snapshot());
@@ -1220,8 +1045,12 @@ export async function* runQuery(userInput, options) {
1220
1045
  };
1221
1046
  }
1222
1047
  else {
1223
- yield { type: 'turn_done', completionStatus: 'completed', usage,
1224
- ...(emptyResponse ? { warning: '成果已提交,未生成文字总结;请查看已提交的成果。' } : {}) };
1048
+ yield {
1049
+ type: 'turn_done',
1050
+ completionStatus: 'completed',
1051
+ usage,
1052
+ ...(emptyResponse ? { warning: '成果已提交,未生成文字总结;请查看已提交的成果。' } : {}),
1053
+ };
1225
1054
  }
1226
1055
  return;
1227
1056
  }
@@ -1243,256 +1072,18 @@ export async function* runQuery(userInput, options) {
1243
1072
  // 两种路径下,history 里的 tool 消息都严格按 toolCallsByIndex 索引顺序回填
1244
1073
  // (OpenAI 协议要求 tool 消息与上一条 assistant 的 tool_calls 一一对应)。
1245
1074
  yield { type: 'stage_change', stage: 'tool_executing' };
1246
- // 执行单个 tool call → WorkerOutcome(内部吞掉 abort/异常,永不 reject)。
1247
- const failureReviews = [];
1248
- const runOneImpl = async (tc, reportProgress) => {
1249
- try {
1250
- const handoff = options.agentHandoff?.current();
1251
- if (handoff && handoff.kind !== 'help')
1252
- return { tc, result: { ok: false, disposition: 'deferred', error: '子任务已经提交交接,本批后续调用未执行' } };
1253
- if (signal?.aborted || options.hasQueuedInput?.()) {
1254
- return { tc, result: { ok: false, disposition: 'deferred', error: 'aborted' } };
1255
- }
1256
- const advisorAvailable = currentEffectiveToolSet.names.has('Advisor');
1257
- if (!advisorAvailable && stallGuard.shouldReject(tc)) {
1258
- return {
1259
- tc,
1260
- result: {
1261
- ok: false,
1262
- disposition: 'deferred',
1263
- error: '检测到同一工具和参数已连续两次返回相同失败;第三次调用已在执行前拒绝,请改变输入或改用其他路径。',
1264
- recovery: 'change-input',
1265
- sensitivity: 'public',
1266
- },
1267
- };
1268
- }
1269
- // The model-visible catalog and the execution boundary are the same set.
1270
- // A provider may still emit a stale or fabricated tool call; return a
1271
- // recoverable result so the model can choose an available path.
1272
- if (!currentEffectiveToolSet.names.has(tc.function.name)) {
1273
- const boundary = options.toolBoundaryLabel ?? '当前宿主授权';
1274
- const visible = [...currentEffectiveToolSet.names];
1275
- const availableHint = visible.length
1276
- ? `(可用:${visible.slice(0, 12).join('、')}${visible.length > 12 ? '…' : ''})`
1277
- : '(本轮没有可用工具)';
1278
- const deniedReason = tc.function.name === 'Agent'
1279
- ? '当前上下文不允许调用 Agent;请直接完成子任务或改用已提供的工具'
1280
- : `工具 ${tc.function.name} 不在${boundary}的有效工具集中${availableHint},请改用已提供的工具继续任务`;
1281
- return {
1282
- tc,
1283
- result: {
1284
- ok: false,
1285
- error: deniedReason,
1286
- recovery: 'change-input',
1287
- sensitivity: 'public',
1288
- },
1289
- };
1290
- }
1291
- const checkpoint = options.advisorCheckpoints === false
1292
- ? { allow: true }
1293
- : advisorCoordinator.beforeTool(tc, {
1294
- ...advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name), { treatVerificationAsReadOnly: true }),
1295
- retriesFailure: stallGuard.shouldReject(tc),
1296
- });
1297
- if (!checkpoint.allow) {
1298
- return { tc, result: checkpoint.deferred };
1299
- }
1300
- // 工具执行闸门:宿主注入后覆盖所有工具,包括只读工具。deny → 把 reason 当
1301
- // tool_result 回填,模型据此改道/如实报告,不抛异常不中断整轮。宿主异常一律 deny。
1302
- // Keep the host gate's side-effect classification identical to the
1303
- // Advisor classification. Shell tools are generic in their schema but
1304
- // individual commands can be deterministic read-only diagnostics.
1305
- let isReadOnly = currentEffectiveToolSet.tools.find(tool => tool.name === tc.function.name)?.isReadOnly === true;
1306
- if (tc.function.name === 'Bash' || tc.function.name === 'PowerShell') {
1307
- try {
1308
- const input = JSON.parse(tc.function.arguments || '{}');
1309
- if (typeof input.command === 'string')
1310
- isReadOnly = isReadOnlyShellCommand(input.command);
1311
- }
1312
- catch {
1313
- isReadOnly = false;
1314
- }
1315
- }
1316
- const effectiveToolGate = runtimeContext.toolGate ?? options.toolGate;
1317
- if (effectiveToolGate) {
1318
- let decision;
1319
- try {
1320
- const gateDetails = getToolGateDetails(tc.function.name, tc.function.arguments, { ...toolCallContext, cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd, toolCallId: tc.id, reportProgress });
1321
- decision = await effectiveToolGate({
1322
- name: tc.function.name,
1323
- argsJson: tc.function.arguments,
1324
- isReadOnly,
1325
- toolCallId: tc.id,
1326
- ...gateDetails,
1327
- }, signal);
1328
- }
1329
- catch {
1330
- decision = { allow: false, reason: '工具执行审批失败(宿主异常)' };
1331
- }
1332
- if (!decision.allow) {
1333
- return { tc, result: { ok: false, error: decision.reason } };
1334
- }
1335
- }
1336
- if (signal?.aborted || options.hasQueuedInput?.()) {
1337
- return { tc, result: { ok: false, disposition: 'deferred', error: 'aborted' } };
1338
- }
1339
- options.onToolStart?.(tc.function.name, tc.id);
1340
- // 浅拷贝填入本次调用的 toolCallId:进度按调用实例路由(并行同名工具不串扰)。
1341
- // advisorCalls/agentCalls 是共享对象引用,计数仍全轮共享,不受拷贝影响。
1342
- const executionCwd = sessionState?.activeWorktree?.path ?? toolCallContext.cwd;
1343
- if (executionCwd !== modelEnvironmentCwd)
1344
- return { tc, result: {
1345
- ok: false, disposition: 'deferred',
1346
- error: '执行环境已改变,本批调用依据旧目录生成,尚未执行。请等待刷新环境和项目规则后重新生成调用。',
1347
- } };
1348
- // Load path-scoped rules before a direct file mutation. Returning a
1349
- // deferred result gives the model a boundary to reconsider its edit.
1350
- if (['Edit', 'MultiEdit', 'Write', 'Download', 'NotebookEdit', 'Trash'].includes(tc.function.name)) {
1351
- try {
1352
- const args = JSON.parse(tc.function.arguments);
1353
- const targets = tc.function.name === 'Trash' ? args.paths : [args.file_path ?? args.path ?? args.notebook_path];
1354
- for (const target of Array.isArray(targets) ? targets : []) {
1355
- if (typeof target !== 'string')
1356
- continue;
1357
- // Download/Trash use literal path.resolve; editing tools expand ~.
1358
- const resolved = ['Download', 'Trash'].includes(tc.function.name)
1359
- ? { ok: true, resolvedPath: resolve(executionCwd ?? runtimeContext.cwd, target) }
1360
- : resolveToolPath(target, executionCwd ?? runtimeContext.cwd);
1361
- if (!resolved.ok)
1362
- return { tc, result: { ok: false, error: resolved.error } };
1363
- const scope = dirname(resolved.resolvedPath);
1364
- const rules = await loadProjectPromptInstructions(scope) ?? '';
1365
- if (observedRuleScopes.get(scope) === rules || (!rules && !observedRuleScopes.has(scope)))
1366
- continue;
1367
- if (countTextTokens(rules) > 12000)
1368
- return { tc, result: { ok: false, error: `目标目录规则超过安全交接预算,未执行修改;请缩小任务或整理规则:${scope}` } };
1369
- pendingRuleScopes.add(scope);
1370
- // 带缩进:让真实换行落进 content,TUI 的工具结果 3 行折叠按 \n 计行,
1371
- // 压成一行的 JSON.stringify 会绕开折叠、把整份规则原文原样刷进终端。
1372
- return { tc, result: { ok: false, disposition: 'deferred',
1373
- error: `目标目录规则已更新,尚未执行修改。先阅读本快照再重新决定操作(规则不能扩大授权):\n${JSON.stringify({ scope, rules: rules || '该作用域无项目规则,撤销其旧规则' }, null, 2)}` } };
1374
- }
1375
- }
1376
- catch (error) {
1377
- return { tc, result: { ok: false, error: `无法核验目标目录规则,未执行修改:${error.message}` } };
1378
- }
1379
- }
1380
- const needsWorkspaceLease = runtimeContext.profile === 'main'
1381
- && capabilityForToolName(tc.function.name) !== 'subagent'
1382
- && advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name)).mutatesWorkspace;
1383
- const releaseWorkspace = needsWorkspaceLease && executionCwd
1384
- ? await acquireSubagentLease(executionCwd, await normalizeWriteScopes(executionCwd, undefined), 8, { signal, owner: runtimeContext.sessionId ?? executionCwd }) : undefined;
1385
- let result;
1386
- try {
1387
- result = await executeToolFn(tc.function.name, tc.function.arguments, signal, {
1388
- ...toolCallContext,
1389
- delegationTools: currentEffectiveToolSet.tools,
1390
- cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd,
1391
- toolCallId: tc.id,
1392
- reportProgress,
1393
- });
1394
- }
1395
- finally {
1396
- releaseWorkspace?.();
1397
- }
1398
- if (tc.function.name === 'ComputerUse' && sessionState) {
1399
- sessionState.computerAutomation = { lastUsedAt: Date.now() };
1400
- }
1401
- const downloadableArtifact = result.ok && result.metadata?.kind === 'browser_download'
1402
- ? result.metadata.artifact
1403
- : undefined;
1404
- const formalManifest = result.ok && result.metadata?.kind === 'result_manifest'
1405
- ? result.metadata.manifest
1406
- : downloadableArtifact;
1407
- if (formalManifest &&
1408
- (tc.function.name === 'PresentResult' || downloadableArtifact) &&
1409
- options.commitFormalDelivery) {
1410
- try {
1411
- await options.commitFormalDelivery({
1412
- toolCallId: tc.id,
1413
- turnId: userMessage.id ?? options.userMessageId ?? 'turn:unknown',
1414
- manifest: formalManifest,
1415
- });
1416
- }
1417
- catch (error) {
1418
- result = {
1419
- ok: false,
1420
- error: `正式交付未能可靠保存:${error.message}`,
1421
- recovery: 'retry',
1422
- sensitivity: 'local',
1423
- };
1424
- }
1425
- }
1426
- if (tc.function.name === 'Advisor' || tc.function.name === 'AdvisorDecision') {
1427
- // 串行批次内下一项可能就是 AdvisorDecision/受保护写入,必须立即推进协调器状态。
1428
- advisorCoordinator.observeToolResult(tc, result);
1429
- }
1430
- options.onToolEnd?.(tc.id, false);
1431
- return { tc, result };
1432
- }
1433
- catch (e) {
1434
- const wasAborted = e.name === 'AbortError';
1435
- options.onToolEnd?.(tc.id, wasAborted);
1436
- if (wasAborted) {
1437
- return { tc, result: { ok: false, error: 'aborted' } };
1438
- }
1439
- return { tc, result: { ok: false, error: e.message } };
1440
- }
1441
- };
1442
- const runOne = async (tc, reportProgress) => {
1443
- // Also settle denied/invalid/unavailable calls that never reached the
1444
- // provider adapter. This records a real attempt, not an ignored reminder.
1445
- let consultation;
1446
- if (tc.function.name === 'Advisor') {
1447
- let reason;
1448
- try {
1449
- reason = JSON.parse(tc.function.arguments).reason;
1450
- }
1451
- catch { /* validation handles malformed input */ }
1452
- consultation = advisorCoordinator.beginConsultation(reason);
1453
- }
1454
- const outcome = await runOneImpl(tc, reportProgress);
1455
- if (consultation && outcome.result.metadata?.kind !== 'advisor_consultation'
1456
- && !(!outcome.result.ok && outcome.result.error === 'aborted')) {
1457
- outcome.result = { ...outcome.result, metadata: advisorCoordinator.finishConsultation(consultation, outcome.result.ok) };
1458
- }
1459
- const metadata = outcome.result.metadata;
1460
- if (metadata?.kind === 'advisor_decision' && outcome.result.ok
1461
- || metadata?.kind === 'advisor_consultation') {
1462
- if (metadata.checkpoint === 'stalled')
1463
- stallGuard.completeReview(metadata.checkpointKey.split(':').at(-1));
1464
- }
1465
- const failure = stallGuard.observeAttempt(tc, outcome.result);
1466
- if (failure.stalled && failure.signature) {
1467
- failureReviews.push(failure);
1468
- advisorCoordinator.requireFailureReview(failure.signature, failure.attempts ?? []);
1469
- }
1470
- return outcome;
1471
- };
1472
- const startEvent = (tc) => ({
1473
- type: 'tool_start',
1474
- toolCallId: tc.id,
1475
- toolName: tc.function.name,
1476
- argsPreview: previewArgs(tc.function.arguments),
1477
- argsFriendly: friendlyToolDescription(tc.function.name, tc.function.arguments),
1478
- argsConcise: friendlyToolDescription(tc.function.name, tc.function.arguments, conciseToolPath),
1479
- });
1480
- const endEvent = (o) => ({
1481
- type: 'tool_end',
1482
- toolCallId: o.tc.id,
1483
- toolName: o.tc.function.name,
1484
- ok: o.result.ok,
1485
- content: o.result.ok
1486
- ? o.result.content
1487
- : o.result.error === 'aborted'
1488
- ? '(已中断)'
1489
- : `Error: ${o.result.error}`,
1490
- metadata: o.result.metadata,
1491
- });
1492
- const segments = executionSegments(toolCallsByIndex, (tc) => {
1493
- const tool = currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name);
1494
- return !['AskUserQuestion', 'Advisor', 'AdvisorDecision', 'OptimizeConversation', 'AgentReport', 'AgentResolve'].includes(tc.function.name)
1495
- && (tool?.isConcurrencySafe ?? getToolByName(tc.function.name)?.isConcurrencySafe) === true;
1075
+ const { runOne, failureReviews } = createToolExecutor({
1076
+ options,
1077
+ runtimeContext,
1078
+ toolCallContext,
1079
+ currentEffectiveToolSet,
1080
+ advisorCoordinator,
1081
+ stallGuard,
1082
+ modelEnvironmentCwd,
1083
+ observedRuleScopes,
1084
+ pendingRuleScopes,
1085
+ currentUserMessageId: userMessage.id,
1086
+ executeToolFn,
1496
1087
  });
1497
1088
  let anyAborted = false;
1498
1089
  // Commit serial outcomes before the next tool starts: Advisor must see the
@@ -1507,23 +1098,15 @@ export async function* runQuery(userInput, options) {
1507
1098
  }
1508
1099
  if (!result.ok && result.error === 'aborted')
1509
1100
  anyAborted = true;
1510
- const browserArtifact = result.ok && result.metadata?.kind === 'browser_download'
1511
- ? result.metadata.artifact
1512
- : undefined;
1101
+ const browserArtifact = result.ok && result.metadata?.kind === 'browser_download' ? result.metadata.artifact : undefined;
1513
1102
  if (result.ok &&
1514
- ((tc.function.name === 'PresentResult' &&
1515
- result.metadata?.kind === 'result_manifest') ||
1516
- browserArtifact)) {
1103
+ ((tc.function.name === 'PresentResult' && result.metadata?.kind === 'result_manifest') || browserArtifact)) {
1517
1104
  resultPresented = true;
1518
1105
  // `not_run` only says that no optional, format-specific validator was
1519
1106
  // invoked. The PresentResult boundary has still checked the file and
1520
1107
  // persisted its fingerprint, so it must not downgrade a normal delivery.
1521
- const manifest = result.metadata?.kind === 'result_manifest'
1522
- ? result.metadata.manifest
1523
- : browserArtifact;
1524
- presentedResultUnverified ||=
1525
- manifest?.files.some((file) => file.verification === 'failed') ??
1526
- false;
1108
+ const manifest = result.metadata?.kind === 'result_manifest' ? result.metadata.manifest : browserArtifact;
1109
+ presentedResultUnverified ||= manifest?.files.some((file) => file.verification === 'failed') ?? false;
1527
1110
  }
1528
1111
  const rawContent = result.ok ? result.content : `Error: ${result.error}`;
1529
1112
  const basePolicy = result.policy ?? getToolResultPolicy(tc.function.name);
@@ -1557,134 +1140,43 @@ export async function* runQuery(userInput, options) {
1557
1140
  tool_result_policy: policy,
1558
1141
  ...(!result.ok && result.disposition === 'deferred' ? { toolResultDisposition: 'deferred' } : {}),
1559
1142
  ...(tc === toolCallsByIndex.at(-1) ? { advisorCheckpoints: advisorCoordinator.drainDegradations() } : {}),
1560
- advisorMutatesWorkspace: advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find(tool => tool.name === tc.function.name), { treatVerificationAsReadOnly: true }).mutatesWorkspace,
1143
+ advisorMutatesWorkspace: advisorSemanticsFor(tc, toolCallContext, currentEffectiveToolSet.tools.find((tool) => tool.name === tc.function.name), { treatVerificationAsReadOnly: true }).mutatesWorkspace,
1561
1144
  ...(result.metadata ? { display_metadata: result.metadata } : {}),
1562
1145
  timestamp: Date.now(),
1563
1146
  id: crypto.randomUUID(),
1564
1147
  ...(options.messageProvenance ? { provenance: options.messageProvenance } : {}),
1565
1148
  });
1566
1149
  };
1567
- const settled = [];
1568
- let questionEncountered = false;
1569
- let advisorEncountered = false;
1570
- for (const segment of segments) {
1571
- if (!questionEncountered && !advisorEncountered && segment.length > 1) {
1572
- // —— 并行:事件队列把各 worker 的 start/end 按真实完成顺序交错 yield 给 UI。
1573
- const queue = [];
1574
- let signalNew = null;
1575
- const enqueue = (ev) => {
1576
- queue.push(ev);
1577
- signalNew?.();
1578
- signalNew = null;
1579
- };
1580
- // 默认并发 = 本轮工具调用数,即不设人为上限(orderedPool 内部本就会
1581
- // Math.min(concurrency, items.length))——这批工具已经过 allConcurrencySafe
1582
- // 判定全部只读/并发安全,能同时跑多少纯是吞吐量问题,不是正确性问题;宿主仍可显式传
1583
- // options.toolConcurrency 收紧("并发安全"不等于"内存/子进程/provider 配额无限",
1584
- // 真有这类顾虑应由宿主按自己的资源预算显式传值,而不是内核替所有宿主悄悄封顶)。
1585
- // ⚠️ 这条默认值曾被 9ce9be61 那次子Agent/浏览器重构悄悄改回 8——那次改动是照着一份
1586
- // 更早的 loop.ts 打的 diff,没带上这里的注释,属于历史真空期的意外覆盖,不是刻意
1587
- // 重新评估后的决定;发现后原样恢复。
1588
- const allDone = orderedPool(segment, options.toolConcurrency ?? segment.length, async (tc) => {
1589
- enqueue(startEvent(tc));
1590
- const o = await runOne(tc, (message, detail) => enqueue({
1591
- type: 'tool_progress',
1592
- toolCallId: tc.id,
1593
- toolName: tc.function.name,
1594
- message,
1595
- detail,
1596
- }));
1597
- enqueue(endEvent(o));
1598
- return o;
1599
- });
1600
- let finished = false;
1601
- const wakeDone = () => {
1602
- finished = true;
1603
- signalNew?.();
1604
- signalNew = null;
1605
- };
1606
- void allDone.then(wakeDone, wakeDone);
1607
- while (!finished || queue.length > 0) {
1608
- while (queue.length > 0)
1609
- yield queue.shift();
1610
- if (finished)
1611
- break;
1612
- await new Promise((r) => {
1613
- signalNew = r;
1614
- });
1615
- }
1616
- const outcomes = await allDone;
1617
- settled.push(...outcomes);
1618
- for (const outcome of outcomes)
1619
- yield* commitOutcome(outcome);
1620
- }
1621
- else {
1622
- // —— 串行:逐个执行(含写类工具,或只有一个工具)。事件直接顺序 yield,无需队列。
1623
- for (const tc of segment) {
1624
- if (questionEncountered || advisorEncountered) {
1625
- const outcome = { tc, result: { ok: false, disposition: 'deferred',
1626
- error: questionEncountered
1627
- ? '此调用在用户回答前已生成,尚未执行。请先阅读提问结果并重新规划;仅在仍必要时重新调用。'
1628
- : '此调用在顾问返回前已生成,尚未执行。请先阅读顾问结果,自主决定采纳、部分采纳或拒绝,再重新生成必要的工具调用。咨询失败则自行判断继续,不必重复咨询。' } };
1629
- yield startEvent(tc);
1630
- yield endEvent(outcome);
1631
- settled.push(outcome);
1632
- yield* commitOutcome(outcome);
1633
- continue;
1634
- }
1635
- questionEncountered = tc.function.name === 'AskUserQuestion';
1636
- yield startEvent(tc);
1637
- const queue = [];
1638
- let wake = null;
1639
- let finished = false;
1640
- const worker = runOne(tc, (message, detail) => {
1641
- queue.push({
1642
- type: 'tool_progress',
1643
- toolCallId: tc.id,
1644
- toolName: tc.function.name,
1645
- message,
1646
- detail,
1647
- });
1648
- wake?.();
1649
- wake = null;
1650
- }).finally(() => {
1651
- finished = true;
1652
- wake?.();
1653
- wake = null;
1654
- });
1655
- while (!finished || queue.length > 0) {
1656
- while (queue.length > 0)
1657
- yield queue.shift();
1658
- if (finished)
1659
- break;
1660
- await new Promise((resolve) => { wake = resolve; });
1661
- }
1662
- const o = await worker;
1663
- // Every later call was planned without this second opinion, including
1664
- // decision records and further consultations. Return control to the LLM.
1665
- advisorEncountered = tc.function.name === 'Advisor';
1666
- yield endEvent(o);
1667
- settled.push(o);
1668
- yield* commitOutcome(o);
1669
- }
1670
- }
1671
- }
1150
+ const settled = yield* executeToolBatch({
1151
+ toolCallsByIndex,
1152
+ currentEffectiveToolSet,
1153
+ options,
1154
+ runOne,
1155
+ commitOutcome,
1156
+ });
1672
1157
  // Publish after every pending tool result has been appended, so hosts see a
1673
1158
  // complete protocol chain when persisting the compacted history.
1674
1159
  while (optimizationEvents.length > 0)
1675
1160
  yield optimizationEvents.shift();
1676
1161
  const childHandoff = options.agentHandoff?.current();
1677
1162
  if (childHandoff && childHandoff.kind !== 'help') {
1678
- yield { type: 'turn_done', completionStatus: childHandoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
1163
+ yield {
1164
+ type: 'turn_done',
1165
+ completionStatus: childHandoff.kind === 'result' ? 'completed' : 'delivery_incomplete',
1679
1166
  warning: childHandoff.kind === 'blocked' ? '子任务已交回主 Agent 接力' : undefined,
1680
- usage: { ...turnUsage, trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls } };
1167
+ usage: {
1168
+ ...turnUsage,
1169
+ trustworthy: turnUsage.totalCalls > 0 && turnUsage.reportedCalls === turnUsage.totalCalls,
1170
+ },
1171
+ };
1681
1172
  return;
1682
1173
  }
1683
1174
  // Failures are recorded at execution time; batch observation now supplements
1684
1175
  // them with the existing no-progress signal without counting attempts twice.
1685
- const stall = failureReviews.at(-1) ?? (turn + 1 < maxTurns
1686
- ? stallGuard.observe(settled.map((item) => item.tc), settled.map((item) => item.result), assistantText)
1687
- : { stalled: false });
1176
+ const stall = failureReviews.at(-1) ??
1177
+ (turn + 1 < maxTurns
1178
+ ? stallGuard.observe(settled.map((item) => item.tc), settled.map((item) => item.result), assistantText)
1179
+ : { stalled: false });
1688
1180
  if (stall.stalled) {
1689
1181
  const message = stall.reason === 'repeated_failure'
1690
1182
  ? '同一问题两次尝试失败,请停止原样重试;顾问可用时,继续解决或交付前先咨询,由主 Agent 自行核验和决策。只读诊断仍可继续。'
@@ -1700,7 +1192,9 @@ export async function* runQuery(userInput, options) {
1700
1192
  try {
1701
1193
  injectedShot = await injectVisionFollowups(history, settled, provider);
1702
1194
  }
1703
- catch { /* 截图回填失败不影响主流程 */ }
1195
+ catch {
1196
+ /* 截图回填失败不影响主流程 */
1197
+ }
1704
1198
  // The history copy is intentionally downgraded after the turn. Emit a detached snapshot
1705
1199
  // so TUI/Desktop stores do not see their already-rendered image mutate underneath them.
1706
1200
  if (injectedShot) {
@@ -1733,242 +1227,3 @@ export async function* runQuery(userInput, options) {
1733
1227
  code: 'max_turns',
1734
1228
  };
1735
1229
  }
1736
- // ---------------- 辅助函数 ----------------
1737
- /**
1738
- * 易变上下文只存在于 provider 请求副本中,不会进入会话历史。
1739
- */
1740
- export const SYSTEM_REMINDER_OPEN = '<system-reminder>';
1741
- export const SYSTEM_REMINDER_CLOSE = '</system-reminder>';
1742
- /**
1743
- * Attach transient context to the current turn's user message in a model-only
1744
- * clone. Later tool-loop requests reuse the same decorated message, making each
1745
- * serialized request a strict prefix extension of the previous one.
1746
- */
1747
- export function buildModelMessages(history, transientContext, currentUserMessageId) {
1748
- history = history.filter(message => !(message.role === 'system' && message._ephemeral));
1749
- const transient = transientContext?.trim();
1750
- if (!transient)
1751
- return history;
1752
- let index = currentUserMessageId
1753
- ? history.findIndex((message) => message.role === 'user' && message.id === currentUserMessageId)
1754
- : -1;
1755
- if (index < 0) {
1756
- for (let cursor = history.length - 1; cursor >= 0; cursor--) {
1757
- if (history[cursor]?.role === 'user') {
1758
- index = cursor;
1759
- break;
1760
- }
1761
- }
1762
- }
1763
- if (index < 0)
1764
- return history;
1765
- const target = history[index];
1766
- if (target.role !== 'user')
1767
- return history;
1768
- const reminder = `${SYSTEM_REMINDER_OPEN}\n${transient}\n${SYSTEM_REMINDER_CLOSE}`;
1769
- const content = typeof target.content === 'string'
1770
- ? `${target.content}\n\n${reminder}`
1771
- : [...target.content, { type: 'text', text: reminder }];
1772
- const next = [...history];
1773
- next[index] = { ...target, content };
1774
- return next;
1775
- }
1776
- // 关键节点图像核验的合成消息标记:既是给模型的提示前缀,也是 evictPriorVisionShots 识别旧图消息的锚。
1777
- export const VISION_SHOT_MARKER = '【实况图像】';
1778
- /**
1779
- * 历史标记。这套机制最初只有 WebBrowser 用得上,文案写死了「浏览器」;
1780
- * 现在 Bash 的 ATTACH_IMAGE sentinel 也能产图(屏幕截图 / 生成的产物),文案必须中性。
1781
- * 但**持久化会话里仍存着旧前缀的消息**,淘汰逻辑必须继续认它 ——
1782
- * 否则老会话里的旧截图永远不会被降级,图片一路累积撑爆上下文。
1783
- */
1784
- const LEGACY_VISION_SHOT_MARKERS = ['【浏览器实况截图】'];
1785
- const VISION_SHOT_PROMPT = `${VISION_SHOT_MARKER}上面是刚才工具执行后附带的真实图像(浏览器页面 / 屏幕截图 / 生成的产物)。请仔细看图核对:是否真的到达/呈现了你预期的状态?若与预期不符(空白/报错/弹窗遮挡/验证拦截/内容不对),不要假设成功,如实说明并调整下一步。`;
1786
- /** 一条 user 消息的文本是否是「实况图像」合成消息(含历史前缀)。 */
1787
- function isVisionShotText(text) {
1788
- return (text.startsWith(VISION_SHOT_MARKER) ||
1789
- LEGACY_VISION_SHOT_MARKERS.some((marker) => text.startsWith(marker)));
1790
- }
1791
- /**
1792
- * 把本轮工具附带的实况截图(ToolResult.visionImages)组装成一条带图 user 消息喂给模型自我核验。
1793
- * - 仅在模型明确支持识图时注入(provider.supportsVision === true);否则丢弃(不假装核验、也不给非视觉端点发图触发 400)。
1794
- * - 注入前先把历史里旧的截图消息降级为纯文字占位(evictPriorVisionShots),保证上下文里最多一张实况图,
1795
- * 避免图片累积撑爆上下文(呼应浏览器 ADR「高频帧只存内存、只持久化最终结果」)。
1796
- * - **失败的工具结果同样回填**:出错现场那张图往往比成功时更有信息量(权限弹窗、
1797
- * 验证拦截、意外的前台窗口)。此前这里要求 `ok === true`,逼得想附图的工具只能
1798
- * 把失败伪装成成功——见 types.ts 里 ToolResult 那段注释。
1799
- */
1800
- async function injectVisionFollowups(history, settled, provider) {
1801
- if (provider.supportsVision === false)
1802
- return null;
1803
- const images = settled.flatMap((s) => s.result.visionImages ?? []);
1804
- if (images.length === 0)
1805
- return null;
1806
- evictPriorVisionShots(history);
1807
- // 工具可以给自己这批图配一句说明(visionNote)。内核只负责把它拼在通用提示之后,
1808
- // 不解读内容——「这是一组 1Hz 连续帧」这类语义只有产图的工具知道。
1809
- const notes = settled
1810
- .flatMap((s) => (s.result.visionNote ? [s.result.visionNote] : []))
1811
- .filter((note, index, all) => all.indexOf(note) === index);
1812
- const text = notes.length > 0
1813
- ? `${VISION_SHOT_PROMPT}\n\n${notes.join('\n\n')}`
1814
- : VISION_SHOT_PROMPT;
1815
- const content = await buildUserContent({ text, images });
1816
- const msg = { role: 'user', content, timestamp: Date.now(), id: crypto.randomUUID() };
1817
- history.push(msg);
1818
- return msg;
1819
- }
1820
- /** 把历史里旧的实况图像 user 消息降级为纯文字占位、剔除其图片,释放上下文(只保留最近一张真图)。 */
1821
- function evictPriorVisionShots(history) {
1822
- for (const msg of history) {
1823
- if (msg.role !== 'user' || !Array.isArray(msg.content))
1824
- continue;
1825
- const textPart = msg.content.find((p) => p.type === 'text');
1826
- if (textPart?.type === 'text' && isVisionShotText(textPart.text)) {
1827
- msg.content = `${VISION_SHOT_MARKER}(此前的实况图像已从上下文移除以节省空间。)`;
1828
- }
1829
- }
1830
- }
1831
- /**
1832
- * 用户按ESC手动中断
1833
- */
1834
- function pushManualInterruptMarker(history) {
1835
- history.push({
1836
- role: 'user',
1837
- content: '(用户按下了 ESC/Ctrl+C 中断了任务。等待用户新指令。)',
1838
- timestamp: Date.now(),
1839
- id: crypto.randomUUID(),
1840
- });
1841
- }
1842
- /**
1843
- * 有新的用户输入在队列中,当前安全停靠
1844
- */
1845
- function pushQueuedInputMarker(history) {
1846
- history.push({
1847
- role: 'user',
1848
- content: [
1849
- '(系统提示:用户在工作过程中发送了新的消息。',
1850
- '你现在看到的是上一轮工作在被打断前已完成的部分。',
1851
- '请阅读用户的新消息,判断:',
1852
- '1. 如果是不相关的新任务:简要确认已收到,转向新任务,可在新任务完成后询问是否回到之前工作',
1853
- '2. 如果是补充信息或前置依赖:把新信息纳入考虑,判断是否需要调整已做的工作,然后继续',
1854
- '3. 如果是改变方向或取消:评估已完成的部分,说明你对变更的理解,按新方向推进)',
1855
- ].join('\n'),
1856
- timestamp: Date.now(),
1857
- id: crypto.randomUUID(),
1858
- });
1859
- }
1860
- /** 把一条 tool_call_delta 合并到累积数组上 */
1861
- function mergeToolCallDelta(acc, ev) {
1862
- let slot = acc[ev.index];
1863
- if (!slot) {
1864
- slot = {
1865
- id: '',
1866
- type: 'function',
1867
- function: { name: '', arguments: '' },
1868
- };
1869
- acc[ev.index] = slot;
1870
- }
1871
- if (ev.id)
1872
- slot.id = ev.id;
1873
- if (ev.name)
1874
- slot.function.name += ev.name;
1875
- if (ev.argumentsDelta)
1876
- slot.function.arguments += ev.argumentsDelta;
1877
- }
1878
- /** 给 UI 展示用的参数预览(只取前 60 字符) */
1879
- function previewArgs(rawJson) {
1880
- const oneLine = rawJson.replace(/\s+/g, ' ').trim();
1881
- if (oneLine.length <= 60)
1882
- return oneLine;
1883
- return oneLine.slice(0, 60) + '...';
1884
- }
1885
- /**
1886
- * 把工具名 + raw arguments JSON 转换成人话描述。
1887
- * UI 优先用这个显示在 spinner 行(如 "Reading src/foo.ts")。
1888
- * 已知工具走 switch;未知工具或 JSON parse 失败 fallback 到 `${toolName}(...)`。
1889
- */
1890
- function friendlyToolDescription(toolName, rawArgsJson, fileLabel) {
1891
- let args = {};
1892
- try {
1893
- args = JSON.parse(rawArgsJson) ?? {};
1894
- }
1895
- catch {
1896
- return `${toolName}(...)`;
1897
- }
1898
- const truncate = (s, n) => {
1899
- if (typeof s !== 'string')
1900
- return '';
1901
- return s.length > n ? s.slice(0, n) + '…' : s;
1902
- };
1903
- const file = (value) => {
1904
- if (typeof value !== 'string')
1905
- return '';
1906
- if (fileLabel)
1907
- return fileLabel(value);
1908
- return value.length > 64 ? `…${value.slice(-63)}` : value;
1909
- };
1910
- switch (toolName) {
1911
- case 'Skill': return `技能 · ${truncate(args.name, 60)}`;
1912
- case 'SearchSkills': return `查找技能 · ${truncate(args.query, 60)}`;
1913
- case 'Advisor': {
1914
- const reasons = { plan_review: '执行前评审', delivery_review: '交付前核验', stalled: '分析重复失败', uncertainty: '核查不确定问题', user_dissatisfaction: '复核用户反馈', evidence_conflict: '核查证据冲突' };
1915
- return `咨询顾问 · ${reasons[String(args.reason)] ?? '独立第二意见'}`;
1916
- }
1917
- case 'AdvisorDecision': return `顾问建议 · ${truncate(args.decision ?? args.action, 40) || '记录核验与采纳结论'}`;
1918
- case 'AskUserQuestion': return '询问关键决策';
1919
- case 'PresentResult': return '提交成果与验证结果';
1920
- case 'PowerShell': return `运行 PowerShell · ${truncate(args.description ?? args.command, 60)}`;
1921
- case 'OptimizeConversation': return '优化对话';
1922
- case 'Read': return `Reading ${file(args.file_path)}`;
1923
- case 'Edit': return `Editing ${file(args.file_path)}`;
1924
- case 'MultiEdit': {
1925
- const n = Array.isArray(args.edits) ? args.edits.length : 0;
1926
- return `Editing ${file(args.file_path)}${n ? ` (${n} 处)` : ''}`;
1927
- }
1928
- case 'Write': return `Writing ${file(args.file_path)}`;
1929
- case 'Trash': return `Moving to Trash ${file(args.file_path ?? args.path)}`;
1930
- case 'ApplyPatch': {
1931
- const patch = typeof args.patch === 'string' ? args.patch : typeof args.input === 'string' ? args.input : '';
1932
- const files = [...patch.matchAll(/^\*\*\* (Add|Update|Delete) File: (.+)$/gm)].map(m => `${file(m[2])}(${{ Add: '新增', Update: '修改', Delete: '删除' }[m[1]]})`);
1933
- if (!files.length)
1934
- files.push(...[...patch.matchAll(/^\+\+\+ [ab]\/([^\n]+)$/gm)].map(m => file(m[1])));
1935
- return files.length > 0 ? `Editing ${files.join(', ')}` : 'Editing patch';
1936
- }
1937
- case 'NotebookEdit': return `Editing ${file(args.notebook_path ?? args.file_path)}`;
1938
- case 'Bash': return typeof args.description === 'string' && args.description.trim()
1939
- ? `运行 ${truncate(args.description, 70)}` : `Running \`${truncate(args.command, 40)}\``;
1940
- case 'Grep': {
1941
- const p = truncate(args.pattern, 30);
1942
- const g = typeof args.glob === 'string' && args.glob.length > 0 ? ` in ${truncate(args.glob, 25)}` : '';
1943
- return `Searching \`${p}\`${g}`;
1944
- }
1945
- case 'Glob': return `Globbing \`${truncate(args.pattern, 50)}\``;
1946
- case 'WebBrowser': {
1947
- const actions = { start: '启动', navigate: '打开页面', screenshot: '截图', snapshot: '读取页面', click: '点击', fill: '填写', evaluate: '执行页面脚本', close: '关闭', stop: '停止', console: '查看控制台', network: '查看网络请求' };
1948
- let target = '';
1949
- try {
1950
- target = new URL(String(args.url)).host;
1951
- }
1952
- catch { /* no URL for local actions */ }
1953
- return `浏览器 · ${actions[String(args.action)] ?? (truncate(args.action, 32) || '操作页面')}${target ? ` · ${target}` : ''}`;
1954
- }
1955
- case 'WebFetch': {
1956
- try {
1957
- return `Fetching ${new URL(String(args.url)).host}`;
1958
- }
1959
- catch {
1960
- return `Fetching ...`;
1961
- }
1962
- }
1963
- case 'BrowserBatch': return `浏览器 · ${truncate(args.action, 30) || '批量操作'}(${Array.isArray(args.steps) ? args.steps.length : 0} 步)`;
1964
- case 'BrowserCDP': return `浏览器调试 · ${truncate(String(args.method ?? args.operation ?? ''), 45)}`;
1965
- case 'WebSearch': return `Searching \`${truncate(args.query, 50)}\``;
1966
- case 'Agent': {
1967
- const t = typeof args.agent_type === 'string' ? args.agent_type : 'explore';
1968
- return `子任务[${t}] ${truncate(args.description, 50)}`;
1969
- }
1970
- default: return `${toolName} · ${truncate(args.description ?? args.action ?? args.operation, 60) || '执行工具操作'}`;
1971
- }
1972
- }
1973
- // 导出供测试用(friendlyToolDescription 是 module-private 纯函数)
1974
- export { friendlyToolDescription };