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.

618 lines • 23.6 kB
import { snapshotTestingValue } from '@openai/agents-core/utils/internal'; export class UnexpectedRealtimeCallError extends Error { /** The zero-based position of the call in `ScriptedRealtimeTransport.calls`. */ callIndex; expectedMethod; actualMethod; constructor(expectedMethod, actualCall) { super(`ScriptedRealtimeTransport expected ${expectedMethod} but received ${actualCall.method} call #${displayIndex(actualCall.index)}.`); this.name = 'UnexpectedRealtimeCallError'; this.callIndex = actualCall.index; this.expectedMethod = expectedMethod; this.actualMethod = actualCall.method; } } export class RealtimeCallMatcherError extends Error { /** The zero-based position of the call in `ScriptedRealtimeTransport.calls`. */ callIndex; actualMethod; constructor(call) { super(`ScriptedRealtimeTransport matcher rejected ${call.method} call #${displayIndex(call.index)}.`); this.name = 'RealtimeCallMatcherError'; this.callIndex = call.index; this.actualMethod = call.method; } } export class IncompleteRealtimeScenarioError extends Error { unconsumedCalls; pendingExpectations; pendingFailures; constructor(unconsumedCalls, pendingExpectations, pendingFailures) { const pendingOrder = pendingExpectations .map((expectation) => `#${expectation.order} ${expectation.method}`) .join(', '); const pendingFailureCount = pendingFailures.reduce((total, failure) => total + failure.count, 0); super(`ScriptedRealtimeTransport scenario is incomplete: ${unconsumedCalls.length} unconsumed call${unconsumedCalls.length === 1 ? '' : 's'}, ${pendingExpectations.length} pending expectation${pendingExpectations.length === 1 ? '' : 's'}${pendingOrder ? ` (${pendingOrder})` : ''}, and ${pendingFailureCount} pending failure${pendingFailureCount === 1 ? '' : 's'}.`); this.name = 'IncompleteRealtimeScenarioError'; this.unconsumedCalls = Object.freeze([...unconsumedCalls]); this.pendingExpectations = Object.freeze([...pendingExpectations]); this.pendingFailures = Object.freeze([...pendingFailures]); } } export class ScriptedRealtimeScenarioCancelledError extends Error { pendingExpectations; constructor(pendingExpectations) { const pendingOrder = pendingExpectations .map((expectation) => `#${expectation.order} ${expectation.method}`) .join(', '); super(`ScriptedRealtimeTransport scenario was cancelled${pendingOrder ? ` with pending expectations: ${pendingOrder}` : ''}.`); this.name = 'AbortError'; this.pendingExpectations = Object.freeze([...pendingExpectations]); } } export class RealtimeTransportNotClosedError extends Error { status; constructor(status) { super(`ScriptedRealtimeTransport is not closed; current status is ${status}.`); this.name = 'RealtimeTransportNotClosedError'; this.status = status; } } export class ScriptedRealtimeConnectionSupersededError extends Error { operation = 'connect'; constructor() { super('ScriptedRealtimeTransport connection attempt was superseded by another lifecycle operation.'); this.name = 'ScriptedRealtimeConnectionSupersededError'; } } /** * An in-memory Realtime transport for deterministic session tests. */ export class ScriptedRealtimeTransport { status = 'disconnected'; muted = false; #calls = []; #unconsumedCalls = []; #expectations = []; #failures = new Map(); #listeners = new Map(); #lifecycleGeneration = 0; #provisionalConnectedGeneration; #nextExpectationOrder = 1; /** Registers a synchronous transport event listener. */ on(event, listener) { this.#addListener(event, listener, false); return this; } /** Removes the most recently registered matching listener. */ off(event, listener) { const registrations = this.#listeners.get(event); if (!registrations) { return this; } for (let index = registrations.length - 1; index >= 0; index -= 1) { if (registrations[index].listener === listener) { registrations.splice(index, 1); break; } } if (registrations.length === 0) { this.#listeners.delete(event); } return this; } /** Emits an event synchronously and propagates listener failures. */ emit(event, ...args) { const registrations = this.#listeners.get(event); if (!registrations || registrations.length === 0) { return false; } for (const registration of [...registrations]) { if (registration.once) { this.#removeListenerRegistration(event, registration); } registration.listener(...args); } return true; } /** Registers a synchronous one-time transport event listener. */ once(event, listener) { this.#addListener(event, listener, true); return this; } /** All outbound calls recorded in invocation order. */ get calls() { return Object.freeze(this.#calls.map(snapshotRecordedRealtimeCall)); } /** Registers an ordered expectation for the next outbound call. */ expectCall(method, matcher) { const order = this.#nextExpectationOrder++; const existingCall = this.#unconsumedCalls.shift(); if (existingCall) { try { this.#validateExpectation(method, matcher, snapshotRecordedRealtimeCall(existingCall)); return Promise.resolve(snapshotRecordedRealtimeCall(existingCall)); } catch (error) { return Promise.reject(error); } } return new Promise((resolve, reject) => { this.#expectations.push({ order, method, matcher: matcher, resolve: (call) => resolve(call), reject, }); }); } /** Runs an exercised scenario without relying on a wall-clock timeout. */ async runScenario(options) { let terminalError; let active = true; let exerciseCompleted = false; let resolveExpectationFailure; const expectationFailureOutcome = new Promise((resolve) => { resolveExpectationFailure = resolve; }); const abortError = () => new ScriptedRealtimeScenarioCancelledError(this.#pendingExpectationDetails()); if (options.signal?.aborted) { throw abortError(); } let removeAbortListener = () => { }; const abortOutcome = new Promise((resolve) => { if (!options.signal) { return; } const listener = () => resolve({ source: 'abort', error: abortError() }); options.signal.addEventListener('abort', listener, { once: true }); removeAbortListener = () => options.signal?.removeEventListener('abort', listener); }); const settleOwnedExpectationFailure = (error) => { if (!active) { return; } terminalError = error; active = false; this.#rejectPendingExpectations(error); resolveExpectationFailure({ source: 'expectation', error }); }; const context = { expectCall: (method, matcher) => { if (!active) { return Promise.reject(terminalError); } const expectation = this.expectCall(method, matcher); void expectation.catch(settleOwnedExpectationFailure); if (exerciseCompleted && this.#expectations.length > 0) { settleOwnedExpectationFailure(this.#createIncompleteError()); } return expectation; }, emit: this.emit.bind(this), }; const assertCompleteOrTerminate = () => { if (!active) { throw terminalError; } try { this.assertComplete(); } catch (error) { terminalError = error; active = false; this.#rejectPendingExpectations(error); throw error; } }; const scenarioOutcome = Promise.resolve() .then(() => options.scenario(context)) .then(() => ({ source: 'scenario', status: 'fulfilled' }), (error) => ({ source: 'scenario', status: 'rejected', error, })); const exerciseOutcome = Promise.resolve() .then(() => options.exercise()) .then((value) => { exerciseCompleted = true; return { source: 'exercise', status: 'fulfilled', value, }; }, (error) => ({ source: 'exercise', status: 'rejected', error, })); try { const first = await Promise.race([ scenarioOutcome, exerciseOutcome, abortOutcome, expectationFailureOutcome, ]); if (first.source === 'abort') { terminalError = first.error; active = false; this.#rejectPendingExpectations(first.error); throw first.error; } if (first.source === 'expectation') { throw first.error; } if (first.status === 'rejected') { terminalError = first.error; active = false; this.#rejectPendingExpectations(first.error); throw first.error; } if (first.source === 'exercise') { const immediateScenarioResult = await Promise.race([ scenarioOutcome, Promise.resolve({ source: 'pending' }), ]); if (immediateScenarioResult.source === 'scenario') { if (immediateScenarioResult.status === 'rejected') { terminalError = immediateScenarioResult.error; active = false; this.#rejectPendingExpectations(immediateScenarioResult.error); throw immediateScenarioResult.error; } assertCompleteOrTerminate(); return first.value; } if (this.#expectations.length > 0) { const error = this.#createIncompleteError(); terminalError = error; active = false; this.#rejectPendingExpectations(error); throw error; } const scenarioResult = await Promise.race([ scenarioOutcome, abortOutcome, expectationFailureOutcome, ]); if (scenarioResult.source === 'abort') { terminalError = scenarioResult.error; active = false; this.#rejectPendingExpectations(scenarioResult.error); throw scenarioResult.error; } if (scenarioResult.source === 'expectation') { throw scenarioResult.error; } if (scenarioResult.status === 'rejected') { terminalError = scenarioResult.error; active = false; this.#rejectPendingExpectations(scenarioResult.error); throw scenarioResult.error; } assertCompleteOrTerminate(); return first.value; } const exerciseResult = await Promise.race([ exerciseOutcome, abortOutcome, expectationFailureOutcome, ]); if (exerciseResult.source === 'abort') { terminalError = exerciseResult.error; active = false; this.#rejectPendingExpectations(exerciseResult.error); throw exerciseResult.error; } if (exerciseResult.source === 'expectation') { throw exerciseResult.error; } if (exerciseResult.status === 'rejected') { terminalError = exerciseResult.error; active = false; this.#rejectPendingExpectations(exerciseResult.error); throw exerciseResult.error; } assertCompleteOrTerminate(); return exerciseResult.value; } finally { active = false; removeAbortListener(); } } /** Makes the next call to a transport method throw the supplied error. */ failNextCall(method, error) { const failures = this.#failures.get(method) ?? []; failures.push(error); this.#failures.set(method, failures); } /** Emits a controlled terminal disconnect and optional transport error. */ disconnect(error) { this.#lifecycleGeneration += 1; let notificationFailure = { present: false }; if (this.status !== 'disconnected') { this.status = 'disconnected'; try { this.emit('connection_change', 'disconnected'); } catch (caughtError) { notificationFailure = { present: true, error: caughtError }; } } if (typeof error !== 'undefined') { const transportError = { type: 'error', error }; try { this.emit('error', transportError); } catch (caughtError) { if (!notificationFailure.present) { notificationFailure = { present: true, error: caughtError }; } } } if (notificationFailure.present) { throw notificationFailure.error; } } /** Throws when calls or expectations remain unmatched. */ assertComplete() { if (this.#unconsumedCalls.length > 0 || this.#expectations.length > 0 || this.#failures.size > 0) { throw this.#createIncompleteError(); } } /** Throws unless the transport is disconnected. */ assertClosed() { if (this.status !== 'disconnected') { throw new RealtimeTransportNotClosedError(this.status); } } async connect(options) { const generation = ++this.#lifecycleGeneration; try { this.status = 'connecting'; this.#recordAndThrowNextFailure({ method: 'connect', options: { model: options.model, url: options.url, callId: options.callId, initialSessionConfig: options.initialSessionConfig, apiKeyProvided: typeof options.apiKey !== 'undefined', }, }); this.#assertCurrentConnectionAttempt(generation, 'connecting'); const connectingNotificationFailure = this.#emitConnectionChange('connecting'); if (connectingNotificationFailure.present) { throw connectingNotificationFailure.error; } this.#assertCurrentConnectionAttempt(generation, 'connecting'); this.status = 'connected'; this.#provisionalConnectedGeneration = generation; const connectedNotificationFailure = this.#emitConnectionChange('connected'); if (connectedNotificationFailure.present) { throw connectedNotificationFailure.error; } this.#assertCurrentConnectionAttempt(generation, 'connected'); this.#provisionalConnectedGeneration = undefined; } catch (error) { if (this.#lifecycleGeneration === generation) { this.#lifecycleGeneration += 1; this.status = 'disconnected'; try { this.emit('connection_change', 'disconnected'); } catch { // Preserve the primary connection failure. } } throw error; } finally { if (this.#provisionalConnectedGeneration === generation) { this.#provisionalConnectedGeneration = undefined; } } } sendEvent(event) { this.#recordAndThrowNextFailure({ method: 'sendEvent', event }); } requestResponse(response) { this.#recordAndThrowNextFailure({ method: 'requestResponse', response }); } sendMessage(message, otherEventData, options) { this.#recordAndThrowNextFailure({ method: 'sendMessage', message, otherEventData, options, }); } addImage(image, options) { this.#recordAndThrowNextFailure({ method: 'addImage', image, options }); } sendAudio(audio, options) { this.#recordAndThrowNextFailure({ method: 'sendAudio', audio, options }); } updateSessionConfig(config) { this.#recordAndThrowNextFailure({ method: 'updateSessionConfig', config }); } close() { if (this.status === 'disconnected') { return; } const generation = ++this.#lifecycleGeneration; const previousStatus = this.status; const previousConnectionWasEstablished = previousStatus === 'connected' && typeof this.#provisionalConnectedGeneration === 'undefined'; this.status = 'disconnecting'; try { this.#recordAndThrowNextFailure({ method: 'close' }); if (this.#lifecycleGeneration !== generation || this.status !== 'disconnecting') { return; } this.status = 'disconnected'; this.emit('connection_change', 'disconnected'); } catch (error) { if (this.#lifecycleGeneration === generation && this.status === 'disconnecting') { this.status = previousConnectionWasEstablished ? 'connected' : 'disconnected'; if (this.status === 'disconnected') { try { this.emit('connection_change', 'disconnected'); } catch { // Preserve the primary close failure. } } } throw error; } } mute(muted) { this.#recordAndThrowNextFailure({ method: 'mute', muted }); this.muted = muted; } sendFunctionCallOutput(toolCall, output, startResponse) { this.#recordAndThrowNextFailure({ method: 'sendFunctionCallOutput', toolCall, output, startResponse, }); } interrupt() { this.#recordAndThrowNextFailure({ method: 'interrupt' }); } resetHistory(oldHistory, newHistory) { this.#recordAndThrowNextFailure({ method: 'resetHistory', oldHistory, newHistory, }); } sendMcpResponse(approvalRequest, approved, reason) { this.#recordAndThrowNextFailure({ method: 'sendMcpResponse', approvalRequest, approved, reason, }); } #record(call) { const callSnapshot = snapshotTestingValue(call); const recordedCall = Object.freeze({ ...callSnapshot, index: this.#calls.length, }); this.#calls.push(recordedCall); const expectation = this.#expectations.shift(); if (!expectation) { this.#unconsumedCalls.push(recordedCall); return; } try { this.#validateExpectation(expectation.method, expectation.matcher, snapshotRecordedRealtimeCall(recordedCall)); expectation.resolve(snapshotRecordedRealtimeCall(recordedCall)); } catch (error) { expectation.reject(error); throw error; } } #addListener(event, listener, once) { const registrations = this.#listeners.get(event) ?? []; registrations.push({ listener: listener, once, }); this.#listeners.set(event, registrations); } #removeListenerRegistration(event, registration) { const registrations = this.#listeners.get(event); if (!registrations) { return; } const index = registrations.indexOf(registration); if (index !== -1) { registrations.splice(index, 1); } if (registrations.length === 0) { this.#listeners.delete(event); } } #validateExpectation(method, matcher, call) { if (call.method !== method) { throw new UnexpectedRealtimeCallError(method, call); } if (matcher && matcher(call) === false) { throw new RealtimeCallMatcherError(call); } } #recordAndThrowNextFailure(call) { const failure = this.#takeNextFailure(call.method); this.#record(call); if (failure.present) { throw failure.error; } } #takeNextFailure(method) { const failures = this.#failures.get(method); if (!failures || failures.length === 0) { return { present: false }; } const error = failures.shift(); if (failures.length === 0) { this.#failures.delete(method); } return { present: true, error }; } #emitConnectionChange(status) { try { this.emit('connection_change', status); return { present: false }; } catch (error) { return { present: true, error }; } } #assertCurrentConnectionAttempt(generation, expectedStatus) { if (this.#lifecycleGeneration !== generation || this.status !== expectedStatus) { throw new ScriptedRealtimeConnectionSupersededError(); } } #pendingExpectationDetails() { return this.#expectations.map(({ order, method }) => ({ order, method })); } #pendingFailureDetails() { return Array.from(this.#failures, ([method, failures]) => ({ method, count: failures.length, })); } #createIncompleteError() { return new IncompleteRealtimeScenarioError(this.#unconsumedCalls.map(({ index, method }) => ({ index, method })), this.#pendingExpectationDetails(), this.#pendingFailureDetails()); } #rejectPendingExpectations(error) { const expectations = this.#expectations.splice(0); for (const expectation of expectations) { expectation.reject(error); } } } function snapshotRecordedRealtimeCall(call) { return Object.freeze(snapshotTestingValue(call)); } function displayIndex(index) { return index + 1; } //# sourceMappingURL=scriptedRealtimeTransport.mjs.map