UNPKG

@openai/agents-realtime

Version:

The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. This package contains the logic for building realtime voice agents on the server or in the browser.

1,556 lines • 70.2 kB
import { getTransferMessage, ModelBehaviorError, OutputGuardrailTripwireTriggered, RunContext, RunToolApprovalItem, UserError, invokeFunctionTool, } from '@openai/agents-core';
import { RuntimeEventEmitter } from '@openai/agents-core/_shims';
import { isZodObject, toSmartString } from '@openai/agents-core/utils';
import { getFunctionToolApprovalInput, prepareFunctionToolInput, setFunctionToolPreparedInput, getSafeErrorType, getBoundToolInvocationRejectionMessage, getHostedMcpApprovalToolName, hasDynamicFunctionToolApprovalPolicy, hasInspectableFunctionToolArguments, getToolInvocationApproval, getToolInvocationRejectionMessage, logToolActionError, validateHandoffToolInvocation, validateToolInvocationApproval, validateToolInvocationName, } from '@openai/agents-core/utils/internal';
import { toNewSessionConfig } from "./clientMessages.mjs";
import { defineRealtimeOutputGuardrail, formatRealtimeGuardrailOutputInfo, getRealtimeGuardrailFeedbackMessage, getRealtimeGuardrailSettings, } from "./guardrail.mjs";
import { DEFAULT_OPENAI_REALTIME_SESSION_CONFIG, } from "./openaiRealtimeBase.mjs";
import { OpenAIRealtimeWebRTC } from "./openaiRealtimeWebRtc.mjs";
import { OpenAIRealtimeWebSocket } from "./openaiRealtimeWebsocket.mjs";
import { RealtimeAgent } from "./realtimeAgent.mjs";
import { approvalItemToRealtimeApprovalItem, getLastTextFromAudioOutputMessage, hasWebRTCSupport, realtimeApprovalItemToApprovalItem, updateRealtimeHistory, } from "./utils.mjs";
import logger from "./logger.mjs";
import { isBackgroundResult, isValidRealtimeTool, toRealtimeToolDefinition, validateRealtimeToolNames, } from "./tool.mjs";
import { runToolInputGuardrails, runToolOutputGuardrails, } from '@openai/agents-core';
function cloneDefaultSessionConfig(audioFormat) {
    const defaults = DEFAULT_OPENAI_REALTIME_SESSION_CONFIG;
    return JSON.parse(JSON.stringify({
        ...defaults,
        audio: {
            ...defaults.audio,
            input: {
                ...defaults.audio?.input,
                format: audioFormat ?? defaults.audio?.input?.format,
            },
            output: {
                ...defaults.audio?.output,
                format: audioFormat ?? defaults.audio?.output?.format,
            },
        },
    }));
}
function validateRealtimeToolExecutionConfig(config) {
    if (typeof config?.preApprovalInputGuardrails !== 'undefined' &&
        typeof config.preApprovalInputGuardrails !== 'boolean') {
        throw new UserError('toolExecution.preApprovalInputGuardrails must be a boolean when provided.');
    }
    return config;
}
const TOOL_APPROVAL_REJECTION_MESSAGE = 'Tool execution was not approved.';
function normalizeRealtimeFunctionCallId(toolCall) {
    const callId = toolCall.callId || toolCall.id || '';
    return callId === toolCall.callId ? toolCall : { ...toolCall, callId };
}
function getStartedResponseId(event) {
    const response = event.providerData?.response;
    if (typeof response !== 'object' || response === null) {
        return undefined;
    }
    const responseId = response.id;
    return typeof responseId === 'string' ? responseId : undefined;
}
function toErrorMessage(error) {
    return error instanceof Error ? error.message : String(error);
}
/**
 * A `RealtimeSession` is the cornerstone of building Voice Agents. It's the equivalent of a
 * Runner in text-based agents except that it automatically handles multiple turns by maintaining a
 * connection with the underlying transport layer.
 *
 * The session handles managing the local history copy, executes tools, runs output guardrails, and
 * facilitates handoffs.
 *
 * The actual audio handling and generation of model responses is handled by the underlying
 * transport layer. By default if you are using a browser with WebRTC support, the session will
 * automatically use the WebRTC version of the OpenAI Realtime API. On the server or if you pass
 * `websocket` as the transport layer, the session will establish a connection using WebSockets.
 *
 * In the case of WebRTC, in the browser, the transport layer will also automatically configure the
 * microphone and audio output to be used by the session.
 *
 * You can also create a transport layer instance yourself and pass it in to have more control over
 * the configuration or even extend the existing ones. Check out the `TwilioRealtimeTransportLayer`
 * for an example of how to create a custom transport layer.
 *
 * @example
 * ```ts
 * const agent = new RealtimeAgent({
 *   name: 'my-agent',
 *   instructions: 'You are a helpful assistant that can answer questions and help with tasks.',
 * })
 *
 * const session = new RealtimeSession(agent);
 * session.connect({
 *   apiKey: 'your-api-key',
 * });
 * ```
 */
export class RealtimeSession extends RuntimeEventEmitter {
    initialAgent;
    options;
    #transport;
    #currentAgent;
    #currentTools;
    #currentDispatchSnapshot;
    #responseDispatchSnapshots = new Map();
    #pendingResponseDispatchSnapshot;
    #pendingFunctionCalls = new Map();
    #issuedApprovals = new WeakMap();
    #mcpApprovalInvocations = new Map();
    #completedToolCalls = new Map();
    #sendingToolCallOutputs = new Map();
    #activeToolCalls = new Map();
    #context;
    #outputGuardrails = [];
    #outputGuardrailSettings;
    #outputGuardrailDeltaState = new Map();
    #history = [];
    #shouldIncludeAudioData;
    #interruptedByGuardrail = {};
    #activeResponseId;
    #responseGeneration = 0;
    #connectionGeneration = 0;
    #connectedGeneration;
    #audioStarted = false;
    // Tracks all MCP tools fetched per server label (from mcp_list_tools results).
    #allMcpToolsByServer = new Map();
    // Tracks currently available MCP tools based on the active agent's configured server_labels.
    #availableMcpTools = [];
    // Keeps track of the last full session config we sent (camelCase keys) so that
    // subsequent updates (e.g. during agent handoffs) preserve properties that are
    // not explicitly recalculated here (such as inputAudioFormat, outputAudioFormat,
    // modalities, speed, toolChoice, turnDetection, etc.). Without this, updating
    // the agent would drop audio format overrides (e.g. g711_ulaw) and revert to
    // transport defaults causing issues for integrations like Twilio.
    #lastSessionConfig = null;
    #defaultAudioFormat;
    #automaticallyTriggerResponseForMcpToolCalls = true;
    #toolExecution;
    #eventListenersAttached = false;
    constructor(initialAgent, options = {}) {
        super();
        this.initialAgent = initialAgent;
        this.options = options;
        if ((typeof options.transport === 'undefined' && hasWebRTCSupport()) ||
            options.transport === 'webrtc') {
            this.#transport = new OpenAIRealtimeWebRTC();
        }
        else if (options.transport === 'websocket' ||
            typeof options.transport === 'undefined') {
            this.#transport = new OpenAIRealtimeWebSocket();
        }
        else {
            this.#transport = options.transport;
        }
        this.#defaultAudioFormat = this.#transport.getDefaultAudioFormat?.();
        this.#lastSessionConfig = cloneDefaultSessionConfig(this.#defaultAudioFormat);
        this.#currentAgent = initialAgent;
        this.#context = new RunContext({
            ...(options.context ?? {}),
            history: this.#history,
        });
        this.#outputGuardrails = (options.outputGuardrails ?? []).map(defineRealtimeOutputGuardrail);
        this.#outputGuardrailSettings = getRealtimeGuardrailSettings(options.outputGuardrailSettings ?? {});
        this.#shouldIncludeAudioData = options.historyStoreAudio ?? false;
        this.#automaticallyTriggerResponseForMcpToolCalls =
            options.automaticallyTriggerResponseForMcpToolCalls ?? true;
        this.#toolExecution = validateRealtimeToolExecutionConfig(options.toolExecution);
    }
    /**
     * The transport layer used by the session.
     */
    get transport() {
        return this.#transport;
    }
    /**
     * The current agent in the session.
     */
    get currentAgent() {
        return this.#currentAgent;
    }
    /**
     * The current usage of the session.
     */
    get usage() {
        return this.#context.usage;
    }
    /**
     * The current context of the session.
     */
    get context() {
        return this.#context;
    }
    /**
     * Whether the session is muted. Might be `null` if the underlying transport layer does not
     * support muting.
     */
    get muted() {
        return this.#transport.muted;
    }
    /**
     * The history of the session.
     */
    get history() {
        return this.#history;
    }
    get availableMcpTools() {
        return this.#availableMcpTools;
    }
    async #prepareAgent(agent) {
        const [handoffs, agentTools] = await Promise.all([
            agent.getEnabledHandoffs(this.#context),
            agent.getAllTools(this.#context),
        ]);
        const handoffTools = handoffs.map((handoff) => handoff.getHandoffAsFunctionTool());
        const realtimeTools = agentTools.filter(isValidRealtimeTool);
        const functionTools = realtimeTools.filter((tool) => tool.type === 'function');
        validateRealtimeToolNames(functionTools, handoffs);
        const hasToolsDefined = typeof agent.tools !== 'undefined' ||
            typeof agent.mcpServers !== 'undefined';
        const hasHandoffsDefined = handoffs.length > 0;
        return {
            agent,
            toolDefinitions: hasToolsDefined || hasHandoffsDefined
                ? [...realtimeTools.map(toRealtimeToolDefinition), ...handoffTools]
                : undefined,
            dispatchSnapshot: {
                agent,
                functionTools,
                handoffs,
            },
        };
    }
    #applyPreparedAgent(prepared) {
        this.#currentAgent = prepared.agent;
        this.#currentTools = prepared.toolDefinitions;
        this.#currentDispatchSnapshot = prepared.dispatchSnapshot;
        // Recompute currently available MCP tools based on the new agent's active server labels.
        this.#updateAvailableMcpTools();
    }
    async #setCurrentAgent(agent) {
        const prepared = await this.#prepareAgent(agent);
        this.#applyPreparedAgent(prepared);
    }
    #captureResponseDispatchSnapshot(responseId) {
        const existingSnapshot = this.#responseDispatchSnapshots.get(responseId);
        if (existingSnapshot) {
            return existingSnapshot;
        }
        const snapshot = this.#pendingResponseDispatchSnapshot ?? this.#currentDispatchSnapshot;
        this.#pendingResponseDispatchSnapshot = undefined;
        if (snapshot) {
            this.#responseDispatchSnapshots.set(responseId, snapshot);
        }
        return snapshot;
    }
    async #getSessionConfig(phase, additionalConfig = {}, preparedAgent, connectionGeneration) {
        const configAgent = preparedAgent?.agent ?? this.#currentAgent;
        const configTools = preparedAgent?.toolDefinitions ?? this.#currentTools;
        const overridesConfig = additionalConfig ?? {};
        const optionsConfig = this.options.config ?? {};
        const instructions = await configAgent.getSystemPrompt(this.#context);
        const getAudioOutputVoiceOverride = (config) => {
            const audioConfig = config
                .audio;
            return audioConfig?.output?.voice;
        };
        // Realtime expects tracing to be explicitly null to disable it; leaving the previous config
        // in place would otherwise continue emitting spans.
        const tracingConfig = this.options
            .tracingDisabled
            ? null
            : this.options.workflowName
                ? {
                    workflow_name: this.options.workflowName,
                }
                : 'auto';
        if (tracingConfig !== null && tracingConfig !== 'auto') {
            if (this.options.groupId) {
                tracingConfig.group_id = this.options.groupId;
            }
            if (this.options.traceMetadata) {
                tracingConfig.metadata = this.options.traceMetadata;
            }
        }
        else if (this.options.groupId || this.options.traceMetadata) {
            logger.warn('In order to set traceMetadata or a groupId you need to specify a workflowName.');
        }
        const audioOutputVoiceOverride = getAudioOutputVoiceOverride(overridesConfig) ??
            getAudioOutputVoiceOverride(optionsConfig);
        const topLevelVoiceOverride = overridesConfig.voice ?? optionsConfig.voice;
        const resolvedVoice = typeof audioOutputVoiceOverride !== 'undefined'
            ? audioOutputVoiceOverride
            : typeof topLevelVoiceOverride !== 'undefined'
                ? topLevelVoiceOverride
                : configAgent.voice;
        // Start from any previously-sent config (so we preserve values like audio formats)
        // and the original options.config provided by the user. Preference order:
        // 1. Last session config we sent (#lastSessionConfig)
        // 2. Original options.config
        // 3. Additional config passed into this invocation (explicit overrides)
        // Finally we overwrite dynamic fields (instructions, voice, model, tools, tracing)
        // to ensure they always reflect the current agent & runtime state.
        let base = {
            ...(this.#lastSessionConfig ?? {}),
            ...optionsConfig,
            ...overridesConfig,
        };
        // A partial audio override replaces the seeded audio object. Restore only
        // missing codec defaults for transports that opt in, after caller merging.
        if (this.#defaultAudioFormat !== undefined) {
            const normalized = toNewSessionConfig(base);
            base = {
                ...normalized,
                audio: {
                    ...normalized.audio,
                    input: {
                        ...normalized.audio?.input,
                        format: normalized.audio?.input?.format ?? this.#defaultAudioFormat,
                    },
                    output: {
                        ...normalized.audio?.output,
                        // Keep the current resolved voice authoritative over cached values.
                        voice: resolvedVoice,
                        format: normalized.audio?.output?.format ?? this.#defaultAudioFormat,
                    },
                },
            };
        }
        // Note: Certain fields cannot be updated after the session begins, such as voice and model
        const fullConfig = {
            ...base,
            instructions,
            voice: resolvedVoice,
            model: this.options.model,
            tools: configTools,
            tracing: tracingConfig,
            prompt: typeof configAgent.prompt === 'function'
                ? await configAgent.prompt(this.#context, configAgent)
                : configAgent.prompt,
        };
        // Update our cache so subsequent updates inherit the full set including any
        // dynamic fields we just overwrote.
        if (connectionGeneration === undefined ||
            connectionGeneration === this.#connectionGeneration) {
            this.#lastSessionConfig = fullConfig;
        }
        // Empty tool arrays retain their released transport semantics elsewhere.
        // Only agent transitions without a target prompt explicitly revoke old tools.
        // Keep this wire override out of the cache so later prompts can inherit tools.
        if (phase === 'update' && configTools?.length === 0 && !fullConfig.prompt) {
            return {
                ...fullConfig,
                providerData: { ...fullConfig.providerData, tools: [] },
            };
        }
        return fullConfig;
    }
    /**
     * Compute the initial session config that the current session will use when connecting.
     *
     * This mirrors the configuration payload we send during `connect`, including dynamic values
     * such as the upstream agent instructions, tool definitions, and prompt content generated at
     * runtime. Keeping this helper exposed allows transports or orchestration layers to precompute
     * a CallAccept-compatible payload without opening a socket.
     *
     * @param overrides - Additional config overrides applied on top of the session options.
     */
    async getInitialSessionConfig(overrides = {}) {
        await this.#setCurrentAgent(this.initialAgent);
        return this.#getSessionConfig('initial', {
            ...(this.options.config ?? {}),
            ...(overrides ?? {}),
        });
    }
    /**
     * Convenience helper to compute the initial session config without manually instantiating and connecting a session.
     *
     * This is primarily useful for integrations that must provide the session configuration to a
     * third party (for example the SIP `calls.accept` endpoint) before the actual realtime session
     * is attached. The helper instantiates a throwaway session so all agent-driven dynamic fields
     * resolve in exactly the same way as the live session path.
     *
     * @param agent - The starting agent for the session.
     * @param options - Session options used to seed the config calculation.
     * @param overrides - Additional config overrides applied on top of the provided options.
     */
    static async computeInitialSessionConfig(agent, options = {}, overrides = {}) {
        const session = new RealtimeSession(agent, options);
        try {
            return await session.getInitialSessionConfig(overrides);
        }
        finally {
            session.close();
        }
    }
    async updateAgent(newAgent) {
        const prepared = await this.#prepareAgent(newAgent);
        this.#currentAgent.emit('agent_handoff', this.#context, newAgent);
        this.emit('agent_handoff', this.#context, this.#currentAgent, newAgent);
        this.#applyPreparedAgent(prepared);
        await this.#transport.updateSessionConfig(await this.#getSessionConfig('update'));
        return newAgent;
    }
    async #handleHandoff(toolCall, handoff, sourceAgent, invocation) {
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        const newAgent = (await handoff.onInvokeHandoff(this.#context, toolCall.arguments));
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        const prepared = await this.#prepareAgent(newAgent);
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        const sessionConfig = await this.#getSessionConfig('update', {}, prepared, invocation.connectionGeneration);
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        await this.#transport.updateSessionConfig(sessionConfig);
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        sourceAgent.emit('agent_handoff', this.#context, newAgent);
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        this.emit('agent_handoff', this.#context, sourceAgent, newAgent);
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return undefined;
        }
        // update session with new agent
        this.#applyPreparedAgent(prepared);
        const output = getTransferMessage(newAgent);
        this.#sendCommittedFunctionCallOutput(sourceAgent, invocation, toolCall, output, true);
        return newAgent;
    }
    #getPendingFunctionCalls(agent) {
        let calls = this.#pendingFunctionCalls.get(agent);
        if (!calls) {
            calls = new Map();
            this.#pendingFunctionCalls.set(agent, calls);
        }
        return calls;
    }
    #getMcpApprovalInvocations(agent) {
        let invocations = this.#mcpApprovalInvocations.get(agent);
        if (!invocations) {
            invocations = new Map();
            this.#mcpApprovalInvocations.set(agent, invocations);
        }
        return invocations;
    }
    #deletePendingFunctionCall(agent, callId) {
        const calls = this.#pendingFunctionCalls.get(agent);
        calls?.delete(callId);
        if (calls?.size === 0) {
            this.#pendingFunctionCalls.delete(agent);
        }
    }
    #sendCommittedFunctionCallOutput(agent, invocation, toolCall, output, startResponse) {
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        let sending = this.#sendingToolCallOutputs.get(agent);
        if (!sending) {
            sending = new Set();
            this.#sendingToolCallOutputs.set(agent, sending);
        }
        if (sending.has(invocation.callId)) {
            return;
        }
        let calls = this.#completedToolCalls.get(agent);
        if (!calls) {
            calls = new Map();
            this.#completedToolCalls.set(agent, calls);
        }
        calls.set(invocation.callId, {
            fingerprint: invocation.fingerprint,
            output,
            startResponse,
        });
        sending.add(invocation.callId);
        try {
            this.#transport.sendFunctionCallOutput(toolCall, output, startResponse);
        }
        finally {
            sending.delete(invocation.callId);
            if (sending.size === 0) {
                this.#sendingToolCallOutputs.delete(agent);
            }
        }
    }
    #isCurrentRealtimeInvocation(invocation) {
        return (invocation.connectionGeneration === this.#connectionGeneration &&
            invocation.connectionGeneration === this.#connectedGeneration);
    }
    async #runRealtimeToolInvocation(agent, invocation, toolCall, execute) {
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        const completed = this.#completedToolCalls
            .get(agent)
            ?.get(invocation.callId);
        if (completed) {
            if (completed.fingerprint !== invocation.fingerprint) {
                throw new ModelBehaviorError(`Tool call ID ${invocation.callId} was reused for a different realtime invocation after completion.`);
            }
            this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, completed.output, completed.startResponse);
            return;
        }
        const activeCalls = this.#getActiveToolCalls(agent);
        const active = activeCalls.get(invocation.callId);
        if (active) {
            if (active.fingerprint !== invocation.fingerprint) {
                throw new ModelBehaviorError(`Tool call ID ${invocation.callId} was reused for a different realtime invocation while execution was active.`);
            }
            const activeOutcome = await active.completion;
            if (activeOutcome &&
                invocation.connectionGeneration === this.#connectionGeneration) {
                this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, activeOutcome.output, activeOutcome.startResponse);
            }
            return;
        }
        let resolveCompletion = () => { };
        const completion = new Promise((resolve) => {
            resolveCompletion = resolve;
        });
        const activeCall = {
            fingerprint: invocation.fingerprint,
            completion,
            resolve: resolveCompletion,
        };
        activeCalls.set(invocation.callId, activeCall);
        try {
            if (this.#isCurrentRealtimeInvocation(invocation)) {
                await execute();
            }
        }
        finally {
            resolveCompletion(this.#completedToolCalls.get(agent)?.get(invocation.callId));
            if (activeCalls.get(invocation.callId) === activeCall) {
                activeCalls.delete(invocation.callId);
            }
            if (activeCalls.size === 0 &&
                this.#activeToolCalls.get(agent) === activeCalls) {
                this.#activeToolCalls.delete(agent);
            }
        }
    }
    #transferActiveToolCallToPendingApproval(agent, invocation) {
        const activeCalls = this.#activeToolCalls.get(agent);
        const active = activeCalls?.get(invocation.callId);
        if (!active) {
            return;
        }
        if (active.fingerprint !== invocation.fingerprint) {
            throw new ModelBehaviorError(`Tool call ID ${invocation.callId} changed while transferring realtime approval ownership.`);
        }
        active.resolve(undefined);
        activeCalls?.delete(invocation.callId);
        if (activeCalls?.size === 0 &&
            this.#activeToolCalls.get(agent) === activeCalls) {
            this.#activeToolCalls.delete(agent);
        }
    }
    #getActiveToolCalls(agent) {
        let calls = this.#activeToolCalls.get(agent);
        if (!calls) {
            calls = new Map();
            this.#activeToolCalls.set(agent, calls);
        }
        return calls;
    }
    #resetToolInvocationState() {
        for (const calls of this.#activeToolCalls.values()) {
            for (const active of calls.values()) {
                active.resolve(undefined);
            }
        }
        this.#pendingFunctionCalls.clear();
        this.#mcpApprovalInvocations.clear();
        this.#completedToolCalls.clear();
        this.#sendingToolCallOutputs.clear();
        this.#activeToolCalls.clear();
    }
    async #resolveApprovalRejectionMessage(tool, toolCall, agent, toolType = 'function') {
        // Per-call message from state.reject(item, { message }) takes precedence.
        const perCallMessage = getToolInvocationRejectionMessage(this.#context, agent, tool, toolCall);
        if (typeof perCallMessage === 'string') {
            return perCallMessage;
        }
        const { toolErrorFormatter } = this.options;
        if (!toolErrorFormatter) {
            return TOOL_APPROVAL_REJECTION_MESSAGE;
        }
        try {
            const formattedMessage = await toolErrorFormatter({
                kind: 'approval_rejected',
                toolType,
                toolName: tool.name,
                callId: toolCall.callId,
                defaultMessage: TOOL_APPROVAL_REJECTION_MESSAGE,
                runContext: this.#context,
            });
            if (typeof formattedMessage === 'string') {
                return formattedMessage;
            }
            if (typeof formattedMessage !== 'undefined') {
                logger.warn('toolErrorFormatter returned a non-string value. Falling back to the default tool approval rejection message.');
            }
        }
        catch (error) {
            const errorDetails = logger.dontLogToolData
                ? getSafeErrorType(error)
                : toErrorMessage(error);
            logger.warn(`toolErrorFormatter threw while formatting approval rejection: ${errorDetails}`);
        }
        return TOOL_APPROVAL_REJECTION_MESSAGE;
    }
    async #handleFunctionToolCall(incomingToolCall, tool, agent, dispatchSnapshot, preparedInput) {
        const toolCall = normalizeRealtimeFunctionCallId(incomingToolCall);
        const invocation = {
            ...validateToolInvocationApproval(this.#context, agent, tool, toolCall),
            connectionGeneration: this.#connectionGeneration,
        };
        const pending = this.#pendingFunctionCalls
            .get(agent)
            ?.get(invocation.callId);
        if (pending) {
            if (pending.fingerprint !== invocation.fingerprint) {
                throw new ModelBehaviorError(`Tool call ID ${invocation.callId} was reused for a different realtime invocation while approval was pending.`);
            }
            return;
        }
        await this.#runRealtimeToolInvocation(agent, invocation, toolCall, () => this.#executeFunctionToolCall(toolCall, tool, agent, dispatchSnapshot, invocation, preparedInput));
    }
    async #executeFunctionToolCall(toolCall, tool, agent, dispatchSnapshot, invocation, preparedInput) {
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        this.#context.context.history = JSON.parse(JSON.stringify(this.#history)); // deep copy of the history
        let parsedArgs = toolCall.arguments;
        const dynamicApprovalPolicy = hasDynamicFunctionToolApprovalPolicy(tool);
        let argumentParseError;
        try {
            if (tool.parameters) {
                if (isZodObject(tool.parameters)) {
                    parsedArgs = tool.parameters.parse(parsedArgs);
                }
                else {
                    parsedArgs = JSON.parse(parsedArgs);
                }
            }
        }
        catch (error) {
            if (!dynamicApprovalPolicy) {
                throw error;
            }
            argumentParseError = error;
        }
        const existingApproval = dynamicApprovalPolicy
            ? getToolInvocationApproval(this.context, agent, tool, toolCall)
            : undefined;
        if (dynamicApprovalPolicy &&
            existingApproval !== false &&
            argumentParseError === undefined) {
            preparedInput ??= prepareFunctionToolInput(tool, toolCall.arguments);
            if (preparedInput?.result.success) {
                parsedArgs = getFunctionToolApprovalInput(preparedInput.result.value);
            }
        }
        const forceApproval = dynamicApprovalPolicy &&
            (argumentParseError !== undefined ||
                preparedInput?.result.success === false ||
                !hasInspectableFunctionToolArguments(parsedArgs));
        const needsApproval = forceApproval ||
            existingApproval !== undefined ||
            (await tool.needsApproval(this.#context, parsedArgs, toolCall.callId));
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        if (needsApproval) {
            const approval = existingApproval ??
                getToolInvocationApproval(this.context, agent, tool, toolCall);
            if (approval === false) {
                this.#deletePendingFunctionCall(agent, toolCall.callId);
                this.emit('agent_tool_start', this.#context, agent, tool, {
                    toolCall,
                });
                if (!this.#isCurrentRealtimeInvocation(invocation)) {
                    return;
                }
                agent.emit('agent_tool_start', this.#context, tool, {
                    toolCall,
                });
                if (!this.#isCurrentRealtimeInvocation(invocation)) {
                    return;
                }
                const result = await this.#resolveApprovalRejectionMessage(tool, toolCall, agent);
                if (!this.#isCurrentRealtimeInvocation(invocation)) {
                    return;
                }
                this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, result, true);
                this.emit('agent_tool_end', this.#context, agent, tool, result, {
                    toolCall,
                });
                agent.emit('agent_tool_end', this.#context, tool, result, {
                    toolCall,
                });
                return;
            }
            else if (typeof approval === 'undefined') {
                if (this.#toolExecution?.preApprovalInputGuardrails === true) {
                    const inputGuardrailResult = await runToolInputGuardrails({
                        guardrails: tool.inputGuardrails,
                        context: this.#context,
                        agent,
                        toolCall: toolCall,
                    });
                    if (!this.#isCurrentRealtimeInvocation(invocation)) {
                        return;
                    }
                    if (inputGuardrailResult.type === 'reject') {
                        this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, inputGuardrailResult.message, true);
                        return;
                    }
                }
                const trustedToolCall = { ...toolCall };
                const trustedApprovalItem = new RunToolApprovalItem(trustedToolCall, agent);
                const approvalItem = new RunToolApprovalItem({ ...trustedToolCall }, agent);
                this.#getPendingFunctionCalls(agent).set(toolCall.callId, {
                    toolCall: trustedToolCall,
                    tool,
                    agent,
                    dispatchSnapshot,
                    approvalItem: trustedApprovalItem,
                    fingerprint: invocation.fingerprint,
                    connectionGeneration: invocation.connectionGeneration,
                    preparedInput,
                });
                this.#issuedApprovals.set(approvalItem, {
                    kind: 'function',
                    connectionGeneration: invocation.connectionGeneration,
                    agent,
                    callId: invocation.callId,
                    fingerprint: invocation.fingerprint,
                    toolName: tool.name,
                    rawName: trustedToolCall.name,
                    tool,
                    trustedApprovalItem,
                    decisionState: 'pending',
                });
                this.#transferActiveToolCallToPendingApproval(agent, invocation);
                this.emit('tool_approval_requested', this.#context, agent, {
                    type: 'function_approval',
                    tool,
                    approvalItem,
                });
                return;
            }
        }
        this.#deletePendingFunctionCall(agent, toolCall.callId);
        if (argumentParseError !== undefined) {
            const errorMessage = 'An error occurred while parsing tool arguments. Please try again with valid JSON.';
            this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, errorMessage, true);
            return;
        }
        const inputGuardrailResult = await runToolInputGuardrails({
            guardrails: tool.inputGuardrails,
            context: this.#context,
            agent,
            toolCall: toolCall,
        });
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        this.emit('agent_tool_start', this.#context, agent, tool, {
            toolCall,
        });
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        agent.emit('agent_tool_start', this.#context, tool, {
            toolCall,
        });
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        this.#context.context.history = JSON.parse(JSON.stringify(this.#history)); // deep copy of the history
        const details = { toolCall };
        if (preparedInput) {
            setFunctionToolPreparedInput(details, preparedInput);
        }
        const result = inputGuardrailResult.type === 'reject'
            ? inputGuardrailResult.message
            : await invokeFunctionTool({
                tool,
                runContext: this.#context,
                input: toolCall.arguments,
                details,
            });
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        const guardedResult = inputGuardrailResult.type === 'reject'
            ? result
            : await runToolOutputGuardrails({
                guardrails: tool.outputGuardrails,
                context: this.#context,
                agent,
                toolCall: toolCall,
                toolOutput: result,
            });
        if (!this.#isCurrentRealtimeInvocation(invocation)) {
            return;
        }
        let stringResult;
        if (isBackgroundResult(guardedResult)) {
            // Don't generate a new response, just send the result
            stringResult = toSmartString(guardedResult.content);
            this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, stringResult, false);
        }
        else {
            stringResult = toSmartString(guardedResult);
            this.#sendCommittedFunctionCallOutput(agent, invocation, toolCall, stringResult, true);
        }
        this.emit('agent_tool_end', this.#context, agent, tool, stringResult, {
            toolCall,
        });
        agent.emit('agent_tool_end', this.#context, tool, stringResult, {
            toolCall,
        });
    }
    async #handleFunctionCall(incomingToolCall, dispatchSnapshot) {
        const toolCall = normalizeRealtimeFunctionCallId(incomingToolCall);
        const candidateFunctionTool = dispatchSnapshot.functionTools.find((tool) => tool.name === toolCall.name);
        const candidateHandoff = dispatchSnapshot.handoffs.find((handoff) => handoff.toolName === toolCall.name);
        const validatedInvocation = candidateFunctionTool
            ? validateToolInvocationApproval(this.#context, dispatchSnapshot.agent, candidateFunctionTool, toolCall)
            : candidateHandoff
                ? validateHandoffToolInvocation(this.#context, dispatchSnapshot.agent, candidateHandoff.toolName, toolCall)
                : validateToolInvocationName(this.#context, dispatchSnapshot.agent, toolCall.name, toolCall);
        const invocation = {
            ...validatedInvocation,
            connectionGeneration: this.#connectionGeneration,
        };
        const pending = this.#pendingFunctionCalls
            .get(dispatchSnapshot.agent)
            ?.get(invocation.callId);
        if (pending) {
            if (pending.fingerprint !== invocation.fingerprint) {
                throw new ModelBehaviorError(`Tool call ID ${invocation.callId} was reused for a different realtime invocation while approval was pending.`);
            }
            return;
        }
        await this.#runRealtimeToolInvocation(dispatchSnapshot.agent, invocation, toolCall, async () => {
            const [toolEnabled, handoffEnabled] = await Promise.all([
                Promise.all(dispatchSnapshot.functionTools.map((tool) => tool.isEnabled(this.#context, dispatchSnapshot.agent))),
                Promise.all(dispatchSnapshot.handoffs.map((handoff) => handoff.isEnabled({
                    runContext: this.#context,
                    agent: dispatchSnapshot.agent,
                }))),
            ]);
            if (!this.#isCurrentRealtimeInvocation(invocation)) {
                return;
            }
            const filteredSnapshot = {
                agent: dispatchSnapshot.agent,
                functionTools: dispatchSnapshot.functionTools.filter((_tool, index) => toolEnabled[index]),
                handoffs: dispatchSnapshot.handoffs.filter((_handoff, index) => handoffEnabled[index]),
            };
            validateRealtimeToolNames(filteredSnapshot.functionTools, filteredSnapshot.handoffs);
            const functionToolMap = new Map(filteredSnapshot.functionTools.map((tool) => [tool.name, tool]));
            const handoffMap = new Map(filteredSnapshot.handoffs.map((handoff) => [
                handoff.toolName,
                handoff,
            ]));
            const functionTool = functionToolMap.get(toolCall.name);
            if (functionTool) {
                await this.#executeFunctionToolCall(toolCall, functionTool, filteredSnapshot.agent, filteredSnapshot, invocation);
                return;
            }
            const possibleHandoff = handoffMap.get(toolCall.name);
            if (possibleHandoff) {
                await this.#handleHandoff(toolCall, possibleHandoff, filteredSnapshot.agent, invocation);
                return;
            }
            const message = `Tool ${toolCall.name} not found`;
            this.#sendCommittedFunctionCallOutput(filteredSnapshot.agent, invocation, toolCall, message, false);
            this.emit('error', {
                type: 'error',
                error: new ModelBehaviorError(message),
            });
        });
    }
    async #runOutputGuardrails(output, responseId, itemId, sourceAgent, source, responseGeneration, connectionGeneration) {
        if (this.#outputGuardrails.length === 0) {
            return;
        }
        const guardrailArgs = {
            agent: sourceAgent,
            agentOutput: output,
            context: this.#context,
        };
        const results = await Promise.all(this.#outputGuardrails.map((guardrail) => guardrail.run(guardrailArgs)));
        const firstTripwireTriggered = results.find((result) => result.output.tripwireTriggered);
        if (firstTripwireTriggered) {
            if (connectionGeneration !== this.#connectionGeneration) {
                return;
            }
            // this ensures that if one guardrail already trips and we are in the middle of another
            // guardrail run, we don't trip again
            if (this.#interruptedByGuardrail[responseId]) {
                return;
            }
            this.#interruptedByGuardrail[responseId] = true;
            const error = new OutputGuardrailTripwireTriggered(`Output guardrail triggered: ${formatRealtimeGuardrailOutputInfo(firstTripwireTriggered.output.outputInfo)}`, firstTripwireTriggered);
            this.emit('guardrail_tripped', this.#context, sourceAgent, error, {
                itemId,
            });
            if (responseGeneration !== this.#responseGeneration ||
                (this.#activeResponseId !== undefined &&
                    this.#activeResponseId !== responseId)) {
                return;
            }
            if (source === 'text' && this.#activeResponseId === responseId) {
                this.#transport.sendEvent({
                    type: 'response.cancel',
                    response_id: responseId,
                });
            }
            else if (source !== 'text') {
                this.interrupt();
            }
            const feedbackText = getRealtimeGuardrailFeedbackMessage(firstTripwireTriggered);
            this.sendMessage(feedbackText);
            return;
        }
    }
    #scheduleOutputGuardrails(output, responseId, itemId, source, sourceAgent, responseGeneration = this.#responseGeneration, connectionGeneration = this.#connectionGeneration) {
        void this.#runOutputGuardrails(output, responseId, itemId, sourceAgent, source, responseGeneration, connectionGeneration).catch((error) => {
            this.emit('error', { type: 'error', error });
        });
    }
    #handleOutputGuardrailDelta(event, source) {
        const { delta, itemId, responseId } = event;
        if (this.#activeResponseId === undefined) {
            this.#activeResponseId = responseId;
            this.#captureResponseDispatchSnapshot(responseId);
        }
        let responseState = this.#outputGuardrailDeltaState.get(responseId);
        if (!responseState) {
            responseState = new Map();
            this.#outputGuardrailDeltaState.set(responseId, responseState);
        }
        const state = responseState.get(itemId) ?? {
            text: '',
            lastRunIndex: 0,
        };
        state.text += delta;
        responseState.set(itemId, state);
        if (this.#outputGuardrailSettings.debounceTextLength < 0) {
            return;
        }
        const newRunIndex = Math.floor(state.text.length / this.#outputGuardrailSettings.debounceTextLength);
        if (newRunIndex <= state.lastRunIndex) {
            return;
        }
        state.lastRunIndex = newRunIndex;
        const sourceAgent = this.#responseDispatchSnapshots.get(responseId)?.agent ??
            this.#currentAgent;
        this.#scheduleOutputGuardrails(state.text, responseId, itemId, source, sourceAgent);
    }
    #setEventListeners() {
        this.#transport.on('*', (event) => {
            this.emit('transport_event', event);
            // Handle completed user transcription events
            if (event.type === 'conversation.item.input_audio_transcription.completed') {
                try {
                    const completedEvent = event;
                    this.#history = updateRealtimeHistory(this.#history, completedEvent, this.#shouldIncludeAudioData);
                    this.#context.context.history = this.#history;
                    this.emit('history_updated', this.#history);
                }
                catch (err) {
                    this.emit('error', {
                        type: 'error',
                        error: err,
                    });
                }
            }
        });
        this.#transport.on('mcp_tools_listed', ({ serverLabel, tools }) => {
            try {
                this.#allMcpToolsByServer.set(serverLabel, tools ?? []);
                this.#updateAvailableMcpTools();
            }
            catch (err) {
                this.emit('error', { type: 'error', error: err });
            }
        });
        this.#transport.on('audio', (event) => {
            if (!this.#audioStarted) {
                this.#audioStarted = true;
                this.emit('audio_start', this.#context, this.#currentAgent);
            }
            this.emit('audio', event);
        });
        this.#transport.on('turn_started', (event) => {
            this.#audioStarted = false;
            const responseId = getStartedResponseId(event);
            this.#activeResponseId = responseId;
            this.#responseGeneration += 1;
            this.#pendingResponseDispatchSnapshot = this.#currentDispatchSnapshot;
            if (responseId) {
                this.#captureResponseDispatchSnapshot(responseId);
            }
            this.emit('agent_start', this.#context, this.#currentAgent);
            this.#currentAgent.emit('agent_start', this.#context, this.#currentAgent);
        });
        this.#transport.on('turn_done', (event) => {
            const responseId = event.response.id;
            const sourceAgent = this.#captureResponseDispatchSnapshot(responseId)?.agent ??
                this.#currentAgent;
            const responseGeneration = this.#responseGeneration;
            const connectionGeneration = this.#connectionGeneration;
            if (this.#activeResponseId === responseId) {
                this.#activeResponseId = undefined;
            }
            const outputItems = event.response.output ?? [];
            let textOutput = '';
            let itemId = '';
            const source = outputItems.some((item) => item?.type === 'message' &&
                Array.isArray(item.content) &&
                // Realtime transports retain provider-specific content tags.
                item.content.some((content) => content?.type === 'output_audio' || content?.type === 'audio'))
                ? 'audio'
                : 'text';
            for (let idx = outputItems.length - 1; idx >= 0; idx--) {
                const candidate = outputItems[idx];
                const candidateText = getLastTextFromAudioOutputMessage(candidate);
                if (typeof candidateText === 'string') {
                    textOutput = candidateText;
                    const candidateId = candidate?.id;
                    itemId = typeof candidateId === 'string' ? candidateId : '';
                    break;
                }
            }
            if (!itemId && outputItems.length > 0) {
                const lastItem = outputItems[outputItems.length - 1];
                itemId = typeof lastItem?.id === 'string' ? lastItem.id : '';
            }
            this.emit('agent_end', this.#context, sourceAgent, textOutput);
            sourceAgent.emit('agent_end', this.#context, textOutput);
            this.#scheduleOutputGuardrails(textOutput, responseId, itemId, source, sourceAgent, responseGeneration, connectionGeneration);
            this.#outputGuardrailDeltaState.delete(responseId);
            this.#responseDispatchSnapshots.delete(responseId);
        });
        this.#transport.on('audio_done', () => {
            if (this.#audioStarted) {
                this.#audioStarted = false;
            }
            this.emit('audio_stopped', this.#context, this.#currentAgent);
        });
        this.#transport.on('audio_transcript_delta', (event) => {
            try {
                this.#handleOutputGuardrailDelta(event, 'audio');
            }
            catch (err) {
                this.emit('error', {
                    type: 'error',
                    error: err,
                });
            }
        });
        this.#transport.on('output_text_delta', (event) => {
            try {
                this.#handleOutputGuardrailDelta(event, 'text');
            }
            catch (err) {
                this.emit('error', {
                    type: 'error',
                    error: err,
                });
            }
        });
        this.#transport.on('item_update', (event) => {
            try {
                const isNew = !this.#history.some((item) => item.itemId === event.itemId);
                this.#history = updateRealtimeHistory(this.#history, event, this.#shouldIncludeAudioData);
                this.#context.context.history = this.#history;
                if (isNew) {
                    const addedItem = this.#history.find((item) => item.itemId === event.itemId);
                    if (addedItem) {
                        this.emit('history_added', addedItem);
                    }
                }
                this.emit('history_updated', this.#history);
            }
            catch (err) {
                this.emit('error', {
                    type: 'error',
                    error: err,
                });
            }
        });
        this.#transport.on('item_deleted', (event) => {
            try {
                this.#history = this.#history.filter((item) => item.itemId !== event.itemId);
                this.#context.context.history = this.#history;
                this.emit('history_updated', this.#history);
            }
            catch (err) {
                this.emit('error', {
                    type: 'error',
                    error: err,
                });
            }
        });
        this.#transport.on('function_call', async (event) => {
            try {
                if (this.#connectedGeneration !== this.#connectionGeneration) {
                    return;
                }
                if (!event.responseId) {
                    throw new ModelBehaviorError('Realtime function call is missing a responseId and cannot be dispatched safely.');
                }
                const dispatchSnapshot = this.#captureResponseDispatchSnapshot(event.responseId);
                if (!dispatchSnapshot) {
                    throw new ModelBehaviorError('Realtime tool dispatch is unavailable before the session tool configuration is resolved.');
                }
                await this.#handleFunctionCall(event, dispatchSnapshot);
            }
            catch (error) {
                logToolActionError(logger, 'Error handling function call', error);
                this.emit('error', {
                    type: 'error',
                    error,
                });
            }
        });
        this.#transport.on('usage_update', (usage) => {
            this.#context.usage.add(usage);
        });
        this.#transport.on('audio_interrupted', () => {
            if (this.#audioStarted) {
                this.#audioStarted = false;
            }
            this.emit('audio_interrupted', this.#context, this.#currentAgent);
        });
        this.#transport.on('error', (error) => {
            this.emit('error', error);
        });
        this.#transport.on('mcp_tool_call_completed', (toolCall) => {
            this.emit('mcp_tool_call_completed', this.#context, this.#currentAgent, toolCall);
            if (this.#automaticallyTriggerResponseForMcpToolCalls) {
                if (this.#transport.requestResponse) {
                    this.#transport.requestResponse();
                }
                else {
                    this.#transport.sendEvent({
                        type: 'response.create',
                    });
                }
            }
        });
        this.#transport.on('mcp_approval_request', (approvalRequest) => {
            try {
                if (this.#connectedGeneration !== this.#connectionGeneration) {
                    return;
                }
                const agent = this.#currentAgent;
                const trustedApprovalItem = realtimeApprovalItemToApprovalItem(agent, approvalRequest);
                if (trustedApprovalItem.rawItem.type !== 'hosted_tool_call') {
                    throw new ModelBehaviorError('Realtime MCP approval could not be normalized safely.');
                }
                const toolName = trustedApprovalItem.rawItem.name;
                const invocation = validateToolInvocationName(this.#context, agent, toolName, trustedApprovalItem.rawItem);
                const agentInvocations = this.#getMcpApprovalInvocations(agent);
                const existing = agentInvocations.get(invocation.callId);
                if (existing) {
                    if (existing.fingerprint !== invocation.fingerprint) {
                        throw new ModelBehaviorError(`Tool call ID ${invocation.callId} was reused for a different realtime MCP approval invocation.`);
                    }
                    return;
                }
                const approvalItem = realtimeApprovalItemToApprovalItem(agent, approvalRequest);
                const issued = {
                    kind: 'mcp',
                    connectionGeneration: this.#connectionGeneration,
                    agent,
                    callId: invocation.callId,
                    fingerprint: invocation.fingerprint,
                    toolName,
                    rawName: trustedApprovalItem.rawItem.name,
                    trustedApprovalItem,
                    decisionState: 'pending',
                };
                this.#issuedApprovals.set(approvalItem, issued);
                agentInvocations.set(invocation.callId, issued);
                this.emit('tool_approval_requested', this.#context, agent, {
                    type: 'mcp_approval_request',
                    approvalItem,
                });
            }
            catch (error) {
                logToolActionError(logger, 'Error handling MCP approval request', error);
                this.emit('error', {
                    type: 'error',
                    error,
                });
            }
        });
    }
    /**
     * Recomputes the currently available MCP tools based on the current agent's active
     * MCP server configurations and the cached per-server tool listings. Emits
     * `mcp_tools_changed` if the set changed.
     */
    #updateAvailableMcpTools() {
        // Collect active MCP server labels and optional allowed filters from the current agent
        const activeMcpConfigs = this.#currentTools?.filter((t) => t.type === 'mcp');
        const allowedFromConfig = (cfg) => {
            const allowed = cfg.allowed_tools;
            if (!allowed)
                return undefined;
            if (Array.isArray(allowed))
                return allowed;
            if (allowed && Array.isArray(allowed.tool_names))
                return allowed.tool_names;
            return undefined;
        };
        const dedupByName = new Map();
        for (const cfg of activeMcpConfigs) {
            const tools = this.#allMcpToolsByServer.get(cfg.server_label) ?? [];
            const allowed = allowedFromConfig(cfg);
            for (const tool of tools) {
                if (allowed && !allowed.includes(tool.name))
                    continue;
                if (!dedupByName.has(tool.name)) {
                    dedupByName.set(tool.name, tool);
                }
            }
        }
        const next = Array.from(dedupByName.values());
        const prev = this.#availableMcpTools;
        const changed = prev.length !== next.length ||
            JSON.stringify(prev.map((t) => t.name).sort()) !==
                JSON.stringify(next.map((t) => t.name).sort());
        if (changed) {
            this.#availableMcpTools = next;
            this.emit('mcp_tools_changed', this.#availableMcpTools);
        }
    }
    /**
     * Connect to the session. This will establish the connection to the underlying transport layer
     * and start the session.
     *
     * After connecting, the session will also emit a `history_updated` event with an empty history.
     *
     * @param options - The options for the connection.
     */
    async connect(options) {
        this.#connectionGeneration += 1;
        const connectionGeneration = this.#connectionGeneration;
        this.#connectedGeneration = undefined;
        this.#resetToolInvocationState();
        this.#responseGeneration = 0;
        this.#activeResponseId = undefined;
        this.#outputGuardrailDeltaState.clear();
        this.#interruptedByGuardrail = {};
        this.#pendingResponseDispatchSnapshot = undefined;
        this.#responseDispatchSnapshots.clear();
        // makes sure the current agent is correctly set and loads the tools
        await this.#setCurrentAgent(this.initialAgent);
        if (connectionGeneration !== this.#connectionGeneration) {
            return;
        }
        if (!this.#eventListenersAttached) {
            this.#setEventListeners();
            this.#eventListenersAttached = true;
        }
        const initialSessionConfig = await this.#getSessionConfig('initial', this.options.config);
        if (connectionGeneration !== this.#connectionGeneration) {
            return;
        }
        await this.#transport.connect({
            apiKey: options.apiKey ?? this.options.apiKey,
            model: this.options.model,
            url: options.url,
            callId: options.callId,
            initialSessionConfig,
        });
        if (connectionGeneration !== this.#connectionGeneration) {
            return;
        }
        this.#connectedGeneration = connectionGeneration;
        // Ensure the cached lastSessionConfig includes everything passed as the initial session config
        // (the call above already set it via #getSessionConfig but in case additional overrides were
        // passed directly here in the future we could merge them). For now it's a no-op.
        this.#history = [];
        this.emit('history_updated', this.#history);
    }
    /**
     * Update the history of the session.
     * @param newHistory - The new history to set.
     */
    updateHistory(newHistory) {
        let updatedHistory;
        if (typeof newHistory === 'function') {
            updatedHistory = newHistory(this.#history);
        }
        else {
            updatedHistory = newHistory;
        }
        this.#transport.resetHistory(this.#history, updatedHistory);
    }
    /**
     * Send a message to the session.
     * @param message - The message to send.
     * @param otherEventData - Additional event data to send.
     */
    sendMessage(message, otherEventData = {}) {
        this.#transport.sendMessage(message, otherEventData);
    }
    /**
     * Add image to the session
     * @param image - The image to add.
     */
    addImage(image, { triggerResponse = true } = {}) {
        this.#transport.addImage(image, { triggerResponse });
    }
    /**
     * Mute the session.
     * @param muted - Whether to mute the session.
     */
    mute(muted) {
        this.#transport.mute(muted);
    }
    /**
     * Disconnect from the session.
     */
    close() {
        this.#connectedGeneration = undefined;
        this.#connectionGeneration += 1;
        this.#responseGeneration = 0;
        this.#activeResponseId = undefined;
        this.#outputGuardrailDeltaState.clear();
        this.#interruptedByGuardrail = {};
        this.#pendingResponseDispatchSnapshot = undefined;
        this.#resetToolInvocationState();
        this.#responseDispatchSnapshots.clear();
        this.#transport.close();
    }
    /**
     * Send audio to the session.
     * @param audio - The audio to send.
     * @param options - Additional options.
     * @param options.commit - Whether to finish the turn with this audio.
     */
    sendAudio(audio, options = {}) {
        this.#transport.sendAudio(audio, options);
    }
    /**
     * Interrupt the session artificially for example if you want to build a "stop talking"
     * button.
     */
    interrupt() {
        this.#transport.interrupt();
    }
    #validateIssuedApproval(approvalItem) {
        let issued = this.#issuedApprovals.get(approvalItem);
        if (!issued &&
            approvalItem.rawItem.type === 'hosted_tool_call' &&
            approvalItem.agent instanceof RealtimeAgent) {
            const agent = approvalItem.agent;
            const { callId } = validateToolInvocationName(this.#context, agent, approvalItem.rawItem.name, approvalItem.rawItem);
            issued = this.#mcpApprovalInvocations.get(agent)?.get(callId);
        }
        if (issued !== undefined &&
            (issued.connectionGeneration !== this.#connectionGeneration ||
                issued.connectionGeneration !== this.#connectedGeneration)) {
            throw new ModelBehaviorError('Tool approval belongs to a closed realtime connection.');
        }
        if (!issued) {
            return undefined;
        }
        if (approvalItem.agent !== issued.agent) {
            throw new ModelBehaviorError(`Tool call ID ${issued.callId} approval does not belong to its issuing realtime agent.`);
        }
        if (!('name' in approvalItem.rawItem) ||
            approvalItem.rawItem.name !== issued.rawName) {
            throw new ModelBehaviorError(`Tool call ID ${issued.callId} approval changed its issued realtime tool name.`);
        }
        const supplied = issued.tool
            ? validateToolInvocationApproval(this.#context, issued.agent, issued.tool, approvalItem.rawItem)
            : validateToolInvocationName(this.#context, issued.agent, issued.toolName, approvalItem.rawItem);
        if (supplied.callId !== issued.callId ||
            supplied.fingerprint !== issued.fingerprint) {
            throw new ModelBehaviorError(`Tool call ID ${issued.callId} approval does not match its issued realtime invocation.`);
        }
        return issued;
    }
    #resolvePendingFunctionCall(approvalItem) {
        if (approvalItem.rawItem.type !== 'function_call') {
            return undefined;
        }
        const rawToolCall = approvalItem.rawItem;
        if (typeof rawToolCall.responseId !== 'string') {
            return undefined;
        }
        const toolCall = normalizeRealtimeFunctionCallId(rawToolCall);
        const agent = approvalItem.agent instanceof RealtimeAgent
            ? approvalItem.agent
            : this.#currentAgent;
        const pending = this.#pendingFunctionCalls.get(agent)?.get(toolCall.callId);
        if (pending) {
            if (pending.connectionGeneration !== this.#connectionGeneration) {
                throw new ModelBehaviorError(`Tool call ID ${toolCall.callId} approval belongs to a closed realtime connection.`);
            }
            const suppliedInvocation = validateToolInvocationApproval(this.#context, agent, pending.tool, toolCall);
            if (toolCall.name !== pending.toolCall.name ||
                suppliedInvocation.fingerprint !== pending.fingerprint) {
                throw new ModelBehaviorError(`Tool call ID ${toolCall.callId} approval does not match the pending realtime invocation.`);
            }
            return pending;
        }
        const toolName = approvalItem.toolName ?? approvalItem.rawItem.name;
        const tool = agent.tools.find((candidate) => candidate.type === 'function' && candidate.name === toolName);
        if (!tool) {
            return undefined;
        }
        const dispatchSnapshot = this.#currentDispatchSnapshot?.agent === agent
            ? this.#currentDispatchSnapshot
            : { agent, functionTools: [tool], handoffs: [] };
        const invocation = {
            ...validateToolInvocationApproval(this.#context, agent, tool, toolCall),
            connectionGeneration: this.#connectionGeneration,
        };
        return {
            toolCall,
            tool,
            agent,
            dispatchSnapshot,
            fingerprint: invocation.fingerprint,
            connectionGeneration: invocation.connectionGeneration,
            approvalItem: toolCall === approvalItem.rawItem
                ? approvalItem
                : new RunToolApprovalItem(toolCall, approvalItem.agent, approvalItem.toolName),
        };
    }
    /**
     * Approve a tool call. This will also trigger the tool call to the agent.
     * @param approvalItem - The approval item to approve.
     * @param options - Additional options.
     * @param options.alwaysApprove - Whether to always approve the tool call.
     */
    async approve(approvalItem, options = { alwaysApprove: false }) {
        const issued = this.#validateIssuedApproval(approvalItem);
        if (issued && issued.decisionState !== 'pending') {
            return;
        }
        const pending = this.#resolvePendingFunctionCall(approvalItem);
        if (issued?.kind === 'function' && !pending) {
            throw new ModelBehaviorError(`Tool call ID ${issued.callId} no longer has a pending realtime invocation.`);
        }
        if (issued?.kind === 'function') {
            issued.decisionState = 'decided';
        }
        const effectiveApprovalItem = pending?.approvalItem ?? issued?.trustedApprovalItem ?? approvalItem;
        this.#context.approveTool(effectiveApprovalItem, options);
        const toolName = effectiveApprovalItem.toolName ??
            ('name' in effectiveApprovalItem.rawItem
                ? effectiveApprovalItem.rawItem.name
                : undefined);
        if (pending) {
            this.#deletePendingFunctionCall(pending.agent, pending.toolCall.callId);
            await this.#handleFunctionToolCall(pending.toolCall, pending.tool, pending.agent, pending.dispatchSnapshot, pending.preparedInput);
        }
        else if (effectiveApprovalItem.rawItem.type === 'hosted_tool_call') {
            if (options.alwaysApprove) {
                logger.warn('Always approving MCP tools is not supported. Use the allowed tools configuration instead.');
            }
            const mcpApprovalRequest = approvalItemToRealtimeApprovalItem(effectiveApprovalItem);
            if (issued) {
                issued.decisionState = 'sending';
            }
            try {
                this.#transport.sendMcpResponse(mcpApprovalRequest, true);
            }
            catch (error) {
                if (issued) {
                    issued.decisionState = 'pending';
                }
                throw error;
            }
            if (issued) {
                issued.decisionState = 'decided';
            }
        }
        else {
            throw new ModelBehaviorError(`Tool ${toolName ?? 'unknown'} not found`);
        }
    }
    /**
     * Reject a tool call. This will also trigger the tool call to the agent.
     * @param approvalItem - The approval item to reject.
     * @param options - Additional options.
     * @param options.alwaysReject - Whether to always reject the tool call.
     * @param options.message - The rejection text sent to the model.
     *   If not provided, `toolErrorFormatter` (if configured) or the SDK default is used.
     */
    async reject(approvalItem, options = {
        alwaysReject: false,
    }) {
        const issued = this.#validateIssuedApproval(approvalItem);
        if (issued && issued.decisionState !== 'pending') {
            return;
        }
        const pending = this.#resolvePendingFunctionCall(approvalItem);
        if (issued?.kind === 'function' && !pending) {
            throw new ModelBehaviorError(`Tool call ID ${issued.callId} no longer has a pending realtime invocation.`);
        }
        if (issued?.kind === 'function') {
            issued.decisionState = 'decided';
        }
        const effectiveApprovalItem = pending?.approvalItem ?? issued?.trustedApprovalItem ?? approvalItem;
        this.#context.rejectTool(effectiveApprovalItem, options);
        // we still need to simulate a tool call to the agent to let the agent know
        const toolName = effectiveApprovalItem.toolName ??
            ('name' in effectiveApprovalItem.rawItem
                ? effectiveApprovalItem.rawItem.name
                : undefined);
        if (pending) {
            this.#deletePendingFunctionCall(pending.agent, pending.toolCall.callId);
            await this.#handleFunctionToolCall(pending.toolCall, pending.tool, pending.agent, pending.dispatchSnapshot, pending.preparedInput);
        }
        else if (effectiveApprovalItem.rawItem.type === 'hosted_tool_call') {
            if (options.alwaysReject) {
                logger.warn('Always rejecting MCP tools is not supported. Use the allowed tools configuration instead.');
            }
            const mcpApprovalRequest = approvalItemToRealtimeApprovalItem(effectiveApprovalItem);
            const rejectionReason = getBoundToolInvocationRejectionMessage(this.#context, effectiveApprovalItem.agent, getHostedMcpApprovalToolName(effectiveApprovalItem.toolName ?? effectiveApprovalItem.rawItem.name, effectiveApprovalItem.rawItem), effectiveApprovalItem.rawItem);
            if (issued) {
                issued.decisionState = 'sending';
            }
            try {
                this.#transport.sendMcpResponse(mcpApprovalRequest, false, rejectionReason);
            }
            catch (error) {
                if (issued) {
                    issued.decisionState = 'pending';
                }
                throw error;
            }
            if (issued) {
                issued.decisionState = 'decided';
            }
        }
        else {
            throw new ModelBehaviorError(`Tool ${toolName ?? 'unknown'} not found`);
        }
    }
}
//# sourceMappingURL=realtimeSession.mjs.map