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