import { recordExecutedCall, type ExecutedCalls } from '../tools/agent/executedCalls.js'; import { dirname, resolve } from 'node:path'; import type { AdvisorNudge } from '../advisor/advisorNudge.js'; import { countTextTokens } from '../context/tokenCounter.js'; import { StallGuard, type StallObservation } from '../harness/stallGuard.js'; import { loadProjectPromptInstructions } from '../prompts/projectInstructions.js'; import type { AgentRuntimeContext } from '../runtime/agentRuntimeContext.js'; import { evaluateDeliveryGate } from '../runtime/deliveryGate.js'; import { acquireSubagentLease, normalizeWriteScopes } from '../tools/agent/coordinator.js'; import { applyPatchRuleScopes } from '../tools/applypatch/applyPatch.js'; import { isReadOnlyShellCommand } from '../tools/bash/semantics.js'; import { capabilityForToolName } from '../tools/capabilities.js'; import type { EffectiveToolSet } from '../tools/effectiveToolSet.js'; import { getToolByName, getToolGateDetails } from '../tools/index.js'; import { resolveToolPath } from '../tools/shared/fileUtils.js'; import { usesReadBudget } from '../tools/shared/readBudget.js'; import type { ToolCall, ToolCallContext, ToolResult } from '../types.js'; import type { RunQueryOptions } from './options.js'; import { advisorSemanticsFor } from './toolSemantics.js'; export type WorkerOutcome = { executed?: boolean; tc: ToolCall; result: ToolResult; }; interface ToolExecutorInput { options: Pick; runtimeContext: AgentRuntimeContext; toolCallContext: ToolCallContext; readBudgets: ReadonlyMap; onReadReserved?: (characters: number) => void; currentEffectiveToolSet: EffectiveToolSet; advisorNudge: AdvisorNudge; stallGuard: StallGuard; modelEnvironmentCwd: string; observedRuleScopes: Map; pendingRuleScopes: Set; currentUserMessageId: string; executeToolFn: NonNullable; } /** One batch's execution boundary. Scheduling and history writes belong to callers. */ export function createToolExecutor(input: ToolExecutorInput) { const { options, runtimeContext, toolCallContext, readBudgets, currentEffectiveToolSet, advisorNudge, stallGuard, modelEnvironmentCwd, observedRuleScopes, pendingRuleScopes, currentUserMessageId, executeToolFn, } = input; const { signal, sessionState } = options; // 有会话状态就挂在上面(跨回合存活);否则挂在本次运行的调用上下文上(子任务等)。 const executedLedger: ExecutedCalls = sessionState ? (sessionState.executedCalls ??= new Map()) : (toolCallContext.executedCalls ??= new Map()); // Convert tool execution failures/aborts into results; host hook failures are // not a successful tool outcome and may propagate to the batch boundary. const failureReviews: StallObservation[] = []; const runOneImpl = async ( tc: ToolCall, reportProgress?: (message: string, detail?: import('../types.js').ToolProgressDetail) => void, /** The batch may still create required work; a browser artifact must not be registered first. */ holdFormalDelivery = false, ): Promise => { let started = false; let executed = false; try { const handoff = options.agentHandoff?.current(); if (handoff && handoff.kind !== 'help') return { tc, result: { ok: false, disposition: 'deferred', error: '子任务已经提交交接,本批后续调用未执行', }, }; if (signal?.aborted || options.hasQueuedInput?.()) { return { tc, result: { ok: false, disposition: 'deferred', error: signal?.aborted ? 'aborted' : '收到用户补充,此旧调用尚未执行;先处理新要求再重新规划。' }, }; } // Rejecting a third identical failing call is the guard's own job, advisor or // not: the advisor is only a reminder now, so nothing else stops the loop. if (stallGuard.shouldReject(tc)) { return { tc, result: { ok: false as const, disposition: 'deferred', error: '检测到同一工具和参数已连续两次返回相同失败;第三次调用已在执行前拒绝,请改变输入或改用其他路径。', recovery: 'change-input', sensitivity: 'public', }, }; } // The model-visible catalog and the execution boundary are the same set. // A provider may still emit a stale or fabricated tool call; return a // recoverable result so the model can choose an available path. const definition = currentEffectiveToolSet.tools.find(tool => tool.name === tc.function.name); if (!definition) { const boundary = options.toolBoundaryLabel ?? '当前宿主授权'; const visible = [...currentEffectiveToolSet.names]; const availableHint = visible.length ? `(可用:${visible.slice(0, 12).join('、')}${visible.length > 12 ? '…' : ''})` : '(本轮没有可用工具)'; const deniedReason = tc.function.name === 'Agent' ? '当前上下文不允许调用 Agent;请直接完成子任务或改用已提供的工具' : `工具 ${tc.function.name} 不在${boundary}的有效工具集中${availableHint},请改用已提供的工具继续任务`; return { tc, result: { ok: false as const, error: deniedReason, recovery: 'change-input', sensitivity: 'public', }, }; } // 工具执行闸门:宿主注入后覆盖所有工具,包括只读工具。deny → 把 reason 当 // tool_result 回填,模型据此改道/如实报告,不抛异常不中断整轮。宿主异常一律 deny。 // Keep the host gate's side-effect classification identical to the // Advisor classification. Shell tools are generic in their schema but // individual commands can be deterministic read-only diagnostics. let isReadOnly = definition.isReadOnly === true; const builtin = definition === getToolByName(tc.function.name); if (builtin && (tc.function.name === 'Bash' || tc.function.name === 'PowerShell')) { try { const input = JSON.parse(tc.function.arguments || '{}') as { command?: unknown; }; if (typeof input.command === 'string') isReadOnly = isReadOnlyShellCommand(input.command); } catch { isReadOnly = false; } } const effectiveToolGate = runtimeContext.toolGate ?? options.toolGate; if (effectiveToolGate) { let decision; try { const gateDetails = getToolGateDetails(definition, tc.function.arguments, { ...toolCallContext, cwd: sessionState?.activeWorktree?.path ?? toolCallContext.cwd, toolCallId: tc.id, reportProgress, }); decision = await effectiveToolGate( { name: tc.function.name, argsJson: tc.function.arguments, isReadOnly, toolCallId: tc.id, ...gateDetails, }, signal, ); } catch { decision = { allow: false as const, reason: '工具执行审批失败(宿主异常)', }; } if (!decision.allow) { return { tc, result: { ok: false as const, error: decision.reason } }; } } if (signal?.aborted || options.hasQueuedInput?.()) { return { tc, result: { ok: false, disposition: 'deferred', error: signal?.aborted ? 'aborted' : '收到用户补充,此旧调用尚未执行;先处理新要求再重新规划。' }, }; } // 浅拷贝填入本次调用的 toolCallId:进度按调用实例路由(并行同名工具不串扰)。 // advisorCalls/agentCalls 是共享对象引用,计数仍全轮共享,不受拷贝影响。 const activeCwd = () => sessionState?.activeWorktree?.path ?? toolCallContext.cwd; const executionCwd = activeCwd(); const staleEnvironment = (): WorkerOutcome => ({ tc, result: { ok: false, disposition: 'deferred', error: '执行环境已改变,本批调用依据旧目录生成,尚未执行。请等待刷新环境和项目规则后重新生成调用。', } }); if (executionCwd !== modelEnvironmentCwd) return staleEnvironment(); const needsWorkspaceLease = runtimeContext.profile === 'main' && (!builtin || capabilityForToolName(tc.function.name) !== 'subagent') && advisorSemanticsFor( tc, toolCallContext, definition, ).mutatesWorkspace; const releaseWorkspace = needsWorkspaceLease && executionCwd ? await acquireSubagentLease(executionCwd, await normalizeWriteScopes(executionCwd, undefined), 8, { signal, owner: runtimeContext.sessionId ?? executionCwd, }) : undefined; let result: ToolResult; try { // A preceding lease holder may have changed the rules while this call // was queued. Read all scopes under the lease, including both sides of moves. if (['Edit', 'MultiEdit', 'Write', 'Download', 'NotebookEdit', 'Trash'].includes(tc.function.name) || (builtin && tc.function.name === 'ApplyPatch')) { try { const args = JSON.parse(tc.function.arguments); const cwd = executionCwd ?? runtimeContext.cwd; const scopes = new Set(); if (tc.function.name === 'ApplyPatch') { for (const scope of await applyPatchRuleScopes(args.patch, cwd)) scopes.add(scope); } else { const targets = tc.function.name === 'Trash' ? args.paths : [args.file_path ?? args.path ?? args.notebook_path]; for (const target of Array.isArray(targets) ? targets : []) { if (typeof target !== 'string') continue; const resolved = ['Download', 'Trash'].includes(tc.function.name) ? { ok: true as const, resolvedPath: resolve(cwd, target) } : resolveToolPath(target, cwd); if (!resolved.ok) return { tc, result: { ok: false, error: resolved.error } }; scopes.add(dirname(resolved.resolvedPath)); } } const changed = []; for (const scope of scopes) { const rules = (await loadProjectPromptInstructions(scope)) ?? ''; if (observedRuleScopes.get(scope) === rules || (!rules && !observedRuleScopes.has(scope))) continue; changed.push({ scope, rules: rules || '该作用域无项目规则,撤销其旧规则' }); } if (changed.length) { const snapshot = JSON.stringify(changed.length === 1 ? changed[0] : changed, null, 2); if (countTextTokens(snapshot) > 12000) return { tc, result: { ok: false, error: '目标目录规则超过安全交接预算,未执行修改;请缩小任务或整理规则。' } }; for (const { scope } of changed) pendingRuleScopes.add(scope); return { tc, result: { ok: false, disposition: 'deferred', error: `目标目录规则已更新,尚未执行修改。先阅读本快照再重新决定操作(规则不能扩大授权):\n${snapshot}`, } }; } } catch (error) { return { tc, result: { ok: false, error: `无法核验目标目录规则,未执行修改:${(error as Error).message}` } }; } } // Scope checks and workspace leases above can await IO. Recheck at the // actual launch boundary, while still releasing any acquired lease. if (signal?.aborted || options.hasQueuedInput?.()) return { tc, result: { ok: false, disposition: 'deferred', error: signal?.aborted ? 'aborted' : '收到用户补充,此旧调用尚未执行;先处理新要求再重新规划。' }, }; if (activeCwd() !== executionCwd) return staleEnvironment(); started = true; options.onToolStart?.(tc.function.name, tc.id); // 每个读取调用只能领取自己的计划额度,且累计不能超领。 // 未进入计划的读取调用按 0 处理,避免回退到默认额度。 let readAllowance = readBudgets.get(tc) ?? 0; const isBudgetedRead = usesReadBudget(tc.function.name); result = await executeToolFn(tc.function.name, tc.function.arguments, signal, { ...toolCallContext, ...(isBudgetedRead ? { reserveReadChars: (requested?: number) => { const wanted = requested ?? readAllowance; const granted = Number.isFinite(wanted) ? Math.min(readAllowance, Math.max(0, Math.floor(wanted))) : 0; readAllowance -= granted; input.onReadReserved?.(granted); return granted; }, } : {}), delegationTools: currentEffectiveToolSet.tools, cwd: executionCwd, toolCallId: tc.id, executedCalls: executedLedger, reportProgress, }); executed = result.ok || (result.disposition !== 'deferred' && result.disposition !== 'not_executed'); if (executed) recordExecutedCall(executedLedger, tc.id, tc.function.name); } finally { releaseWorkspace?.(); } if (tc.function.name === 'ComputerUse' && sessionState) { sessionState.computerAutomation = { lastUsedAt: Date.now() }; } let downloadableArtifact = result.ok && result.metadata?.kind === 'browser_download' ? result.metadata.artifact : undefined; // PresentResult checks the delivery gate itself. A browser artifact reaches // the same formal-delivery ledger through this boundary, so it is checked // here: the file stays saved (a download is a working step), but it is not // registered as a delivered result while required responsibility is open // or the ledger is unreadable. PresentResult can submit it later. if (downloadableArtifact && options.commitFormalDelivery && !options.agentHandoff) { const deliveryId = toolCallContext.deliveryId ?? currentUserMessageId; const gate = holdFormalDelivery ? undefined : await evaluateDeliveryGate(toolCallContext, deliveryId); if (holdFormalDelivery || gate?.kind !== 'ready') { if (result.ok && result.metadata?.kind === 'browser_download') { const { artifact: _withheld, ...rest } = result.metadata; result = { ...result, content: `${result.content} [成果未登记为正式交付] 必要子任务尚未收口或账本不可读,` + `文件已保存但不算已交付(${downloadableArtifact.files.map((file) => file.relativePath).join('、')})。` + `收口后用 PresentResult 提交这些路径。`, metadata: rest, }; } downloadableArtifact = undefined; } } let formalManifest = result.ok && result.metadata?.kind === 'result_manifest' ? result.metadata.manifest : downloadableArtifact; if (formalManifest && (signal?.aborted || options.hasQueuedInput?.())) { result = { ok: false, disposition: 'deferred', error: `成果检查已执行,但收到新输入或停止信号,尚未登记为正式交付。文件未回滚:${formalManifest.files.map(file => file.relativePath).join('、')}。先处理新要求,再用 PresentResult 提交;不要重跑生成操作。` }; formalManifest = undefined; } if ( formalManifest && (tc.function.name === 'PresentResult' || downloadableArtifact) && options.commitFormalDelivery ) { try { await options.commitFormalDelivery({ toolCallId: tc.id, turnId: currentUserMessageId, manifest: formalManifest, }); } catch (error) { result = { ok: false, error: `正式交付未能可靠保存:${(error as Error).message}`, recovery: 'retry', sensitivity: 'local', }; } } // A successful consultation lets the model try the failing path again: the // guard stops counting those failures against it. if (tc.function.name === 'Advisor' && result.ok) stallGuard.noteConsultation(); started = false; options.onToolEnd?.(tc.id, false); return { tc, result, executed }; } catch (e) { const wasAborted = (e as Error).name === 'AbortError'; if (started) options.onToolEnd?.(tc.id, wasAborted); if (wasAborted) { return { tc, executed, result: { ok: false as const, error: 'aborted' } }; } return { tc, executed, result: { ok: false as const, error: (e as Error).message }, }; } }; const runOne = async ( tc: ToolCall, reportProgress?: Parameters[1], holdFormalDelivery?: boolean, ): Promise => { const outcome = await runOneImpl(tc, reportProgress, holdFormalDelivery); const failure = stallGuard.observeAttempt(tc, outcome.result); if (failure.stalled && failure.signature) { failureReviews.push(failure); advisorNudge.notifyStalled(failure.signature); } return outcome; }; return { runOne, failureReviews }; }