import { Agent, AgentOutputType } from '../agent'; import type { Computer } from '../computer'; import { UserError } from '../errors'; import { Handoff } from '../handoff'; import logger from '../logger'; import type { RunState } from '../runState'; import { ComputerTool, Tool, resolveComputer } from '../tool'; import { getFunctionToolNamespace, getFunctionToolQualifiedName, } from '../toolIdentity'; import { serializeHandoff, serializeTool } from '../utils/serialize'; import { ensureAgentSpan } from './tracing'; import { isDeferredHostedMcpTool, validateClientToolSearchSupport, } from './toolSearch'; import { AgentArtifacts, ProcessedResponse } from './types'; import type { ToolNameCollisionPolicy } from './runConfig'; const computerInitPromisesByRunState = new WeakMap< RunState, WeakMap> >(); // Recovery intent is owned by a live run and its public source Agent, never by // serialized processing metadata or a prepared capability clone. const deferredToolRecoveryAgents = new WeakMap< RunState, Agent >(); export function trackDeferredToolRecovery( state: RunState, sourceAgent: Agent, response: ProcessedResponse, ): void { if ( response.functionToolsNotFound?.some((call) => call.reason === 'not_loaded') ) { deferredToolRecoveryAgents.set(state, sourceAgent); } else { deferredToolRecoveryAgents.delete(state); } } function getComputerInitMap( state: RunState, ): WeakMap> { let initMap = computerInitPromisesByRunState.get(state); if (!initMap) { initMap = new WeakMap(); computerInitPromisesByRunState.set(state, initMap); } return initMap; } async function initComputerOnce( computer: Computer, state: RunState, ): Promise { if (typeof computer.initRun !== 'function') { return; } const initMap = getComputerInitMap(state); const existing = initMap.get(computer); if (existing) { await existing; return; } const initPromise = (async () => { await computer.initRun?.(state._context); })(); initMap.set(computer, initPromise); try { await initPromise; } catch (error) { initMap.delete(computer); throw error; } } /** * Collects tools and handoffs for the current agent so model calls and tracing share the same * snapshot of enabled capabilities. */ export async function prepareAgentArtifacts< TContext, TAgent extends Agent, >( state: RunState, executionAgent: Agent = state._currentAgent, toolNameCollisionPolicy: ToolNameCollisionPolicy = 'warn', ): Promise> { const collectedCapabilities = await collectAgentCapabilities( state, executionAgent, ); const capabilities = resolveModelVisibleToolNameCollisions( collectedCapabilities.tools, collectedCapabilities.handoffs, toolNameCollisionPolicy, ); if ( deferredToolRecoveryAgents.get(state) === state._currentAgent && !capabilities.tools.some(isDeferredHostedMcpTool) ) { // A hosted search may omit definitions already loaded in the response chain. // Use the existing local loader for this recovery turn so the active Agent // receives fresh discovery before any deferred function can execute. // Keep deferred MCP on server search: client output serializes its credentials. capabilities.tools = capabilities.tools.map((tool) => tool.type === 'hosted_tool' && tool.providerData?.type === 'tool_search' && tool.providerData.execution !== 'client' && tool.providerData.parameters == null ? { ...tool, providerData: { ...tool.providerData, execution: 'client' }, } : tool, ); } validateClientToolSearchSupport(capabilities.tools); await warmUpComputerTools(capabilities.tools, state._context); await initializeComputerTools(capabilities.tools, state); state.setCurrentAgentSpan( ensureAgentSpan({ agent: executionAgent, handoffs: capabilities.handoffs, tools: capabilities.tools, currentSpan: state._currentAgentSpan, }), ); return { ...capabilities, serializedHandoffs: capabilities.handoffs.map((handoff) => serializeHandoff(handoff), ), serializedTools: await Promise.all( capabilities.tools.map(async (tool) => serializeTool( tool.type === 'computer' ? { ...tool, // Another run may replace tool.computer while preparation awaits. computer: await resolveComputer({ tool, runContext: state._context, }), } : tool, ), ), ), toolsExplicitlyProvided: executionAgent.hasExplicitToolConfig(), }; } async function collectAgentCapabilities( state: RunState>, executionAgent: Agent, ): Promise<{ handoffs: Handoff[]; tools: Tool[]; }> { const handoffs = await executionAgent.getEnabledHandoffs(state._context); const configuredTools = (await executionAgent.getAllTools( state._context, state._currentAgentSpan, )) as Tool[]; const runtimeLoadedTools = state.getToolSearchRuntimeTools( state._currentAgent, ) as Tool[]; const enabledRuntimeTools = ( await Promise.all( runtimeLoadedTools.map(async (tool) => ({ tool, enabled: tool.type !== 'function' || (await tool.isEnabled(state._context, state._currentAgent)), })), ) ) .filter(({ enabled }) => enabled) .map(({ tool }) => tool); return { handoffs, tools: [...configuredTools, ...enabledRuntimeTools] }; } type ModelVisibleToolKind = 'function tool' | 'handoff'; type ModelVisibleFunctionCategory = 'top-level' | 'namespaced' | 'deferred'; type ModelVisibleToolEntry = { kind: ModelVisibleToolKind; index: number; functionCategory?: ModelVisibleFunctionCategory; }; /** @internal */ export function resolveModelVisibleToolNameCollisions( tools: Tool[], handoffs: Handoff[], collisionPolicy: ToolNameCollisionPolicy, ): { tools: Tool[]; handoffs: Handoff[] } { const topLevelEntriesByName = new Map(); const namespacedFunctionEntriesByName = new Map< string, ModelVisibleToolEntry[] >(); const deferredFunctionEntriesByName = new Map< string, ModelVisibleToolEntry[] >(); const addName = ( entriesByName: Map, name: string, entry: ModelVisibleToolEntry, ) => { const entries = entriesByName.get(name) ?? []; entries.push(entry); entriesByName.set(name, entries); }; for (const [index, tool] of tools.entries()) { if (tool.type === 'function') { const namespace = getFunctionToolNamespace(tool); if (namespace === tool.name) { throw new UserError( 'Responses tool search reserves same-name namespaces for deferred top-level function tools. Rename the namespace or tool name to avoid ambiguous dispatch.', ); } const functionCategory: ModelVisibleFunctionCategory = namespace ? 'namespaced' : tool.deferLoading === true ? 'deferred' : 'top-level'; const entry: ModelVisibleToolEntry = { kind: 'function tool', index, functionCategory, }; const dispatchName = getFunctionToolQualifiedName(tool) ?? tool.name; addName( functionCategory === 'namespaced' ? namespacedFunctionEntriesByName : functionCategory === 'deferred' ? deferredFunctionEntriesByName : topLevelEntriesByName, dispatchName, entry, ); } } for (const [index, handoff] of handoffs.entries()) { addName(topLevelEntriesByName, handoff.toolName, { kind: 'handoff', index, }); } const namespacedDuplicates = [...namespacedFunctionEntriesByName.entries()] .filter(([, entries]) => entries.length > 1) .sort(([left], [right]) => left.localeCompare(right)); const deferredDuplicates = [...deferredFunctionEntriesByName.entries()] .filter(([, entries]) => entries.length > 1) .sort(([left], [right]) => left.localeCompare(right)); const strictDuplicatesByName = new Map([ ...namespacedDuplicates, ...deferredDuplicates, ]); const strictDuplicates = [...strictDuplicatesByName.entries()].sort( ([left], [right]) => left.localeCompare(right), ); if (strictDuplicates.length > 0) { throwToolNameCollisionError(strictDuplicates); } const topLevelDuplicates = [...topLevelEntriesByName.entries()] .filter(([, entries]) => entries.length > 1) .sort(([left], [right]) => left.localeCompare(right)); if (topLevelDuplicates.length === 0) { return { tools, handoffs }; } if (collisionPolicy === 'error') { throwToolNameCollisionError(topLevelDuplicates); } const retainedToolIndices = new Set(tools.map((_, index) => index)); const retainedHandoffIndices = new Set(handoffs.map((_, index) => index)); for (const [name, entries] of topLevelDuplicates) { warnToolNameCollision(name, entries); const handoffEntries = entries.filter((entry) => entry.kind === 'handoff'); const winner = handoffEntries.at(-1) ?? entries.at(-1)!; for (const entry of entries) { if (entry === winner) { continue; } if (entry.kind === 'function tool') { retainedToolIndices.delete(entry.index); } else { retainedHandoffIndices.delete(entry.index); } } } return { tools: tools.filter((_, index) => retainedToolIndices.has(index)), handoffs: handoffs.filter((_, index) => retainedHandoffIndices.has(index)), }; } const toolNameCollisionRemediation = 'Function tools and handoffs must have unique routed names. Assign unique tool names or toolNameOverride values, or use a namespace.'; function throwToolNameCollisionError( duplicates: Array<[string, ModelVisibleToolEntry[]]>, ): never { if (logger.dontLogToolData) { throw new UserError( `Duplicate enabled function tool or handoff names found. ${toolNameCollisionRemediation}`, ); } const label = duplicates.length === 1 ? 'name' : 'names'; const details = duplicates .map( ([name, entries]) => `'${name}' (${formatToolKinds(entries.map((entry) => entry.kind))})`, ) .join(', '); throw new UserError( `Duplicate enabled tool ${label} found: ${details}. ${toolNameCollisionRemediation}`, ); } function warnToolNameCollision( name: string, entries: readonly ModelVisibleToolEntry[], ): void { if (logger.dontLogToolData) { logger.warn( 'Tool name collision detected. Assign unique routed tool names or enable tool data logging for details. Only the current dispatch winner will be exposed.', ); return; } logger.warn( `Duplicate enabled tool name found: '${name}' (${formatToolKinds(entries.map((entry) => entry.kind))}). ${toolNameCollisionRemediation} Only the current dispatch winner will be exposed.`, ); } function formatToolKinds(kinds: readonly ModelVisibleToolKind[]): string { const functionToolCount = kinds.filter( (kind) => kind === 'function tool', ).length; const handoffCount = kinds.length - functionToolCount; const descriptions: string[] = []; if (functionToolCount > 0) { descriptions.push( functionToolCount === 1 ? 'function tool' : `${functionToolCount} function tools`, ); } if (handoffCount > 0) { descriptions.push( handoffCount === 1 ? 'handoff' : `${handoffCount} handoffs`, ); } return descriptions.join(' and '); } async function warmUpComputerTools( tools: Tool[], runContext: RunState>['_context'], ): Promise { const computerTools = tools.filter( (tool) => tool.type === 'computer', ) as ComputerTool[]; if (computerTools.length === 0) { return; } await Promise.all( computerTools.map(async (tool) => { await resolveComputer({ tool, runContext }); }), ); } async function initializeComputerTools( tools: Tool[], state: RunState>, ): Promise { const computerTools = tools.filter( (tool) => tool.type === 'computer', ) as ComputerTool[]; if (computerTools.length === 0) { return; } await Promise.all( computerTools.map(async (tool) => { const computer = await resolveComputer({ tool, runContext: state._context, }); await initComputerOnce(computer, state); }), ); }