@mastra/voice-openai-realtime 0.13.10 → 0.13.11-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ name: mastra-voice-openai-realtime
3
3
  description: Documentation for @mastra/voice-openai-realtime. Use when working with @mastra/voice-openai-realtime APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/voice-openai-realtime"
6
- version: "0.13.10"
6
+ version: "0.13.11-alpha.1"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.13.10",
2
+ "version": "0.13.11-alpha.1",
3
3
  "package": "@mastra/voice-openai-realtime",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -876,9 +876,11 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
876
876
  }
877
877
  /**
878
878
  * Registers an event listener for voice events.
879
- * Available events: 'speaking', 'writing, 'error'
880
- * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'
881
- * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.
879
+ * Voice events include 'speaking', 'writing', and 'error'.
880
+ * Supported native input events use their unprefixed OpenAI names:
881
+ * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',
882
+ * and 'conversation.item.input_audio_transcription.completed'.
883
+ * These native events deliver the complete received payload, including transcription usage when present.
882
884
  *
883
885
  * @param event - Name of the event to listen for
884
886
  * @param callback - Function to call when the event occurs
@@ -959,6 +961,12 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
959
961
  this.client.on("session.updated", (ev) => {
960
962
  this.emit("session.updated", ev);
961
963
  });
964
+ this.client.on("input_audio_buffer.speech_started", (ev) => {
965
+ this.emit("input_audio_buffer.speech_started", ev);
966
+ });
967
+ this.client.on("input_audio_buffer.speech_stopped", (ev) => {
968
+ this.emit("input_audio_buffer.speech_stopped", ev);
969
+ });
962
970
  this.client.on("response.created", (ev) => {
963
971
  this.emit("response.created", ev);
964
972
  const speakerStream = new stream.PassThrough();
@@ -975,6 +983,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
975
983
  });
976
984
  });
977
985
  this.client.on("conversation.item.input_audio_transcription.completed", (ev) => {
986
+ this.emit("conversation.item.input_audio_transcription.completed", ev);
978
987
  if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) this.emit("writing", {
979
988
  text: ev.transcript,
980
989
  response_id: ev.item_id,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#adapterContext","#correlate","#export","#rawConfig","Readable","EventEmitter","ws","WebSocket","PassThrough"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Available events: 'speaking', 'writing, 'error'\n * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'\n * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;EACJ,CAAC;CACF,QAAQ,CAAC;AACV;;;;;;;AAOA,SAAS,mBAAmB,MAAM;CACjC,MAAM,aAAa,KAAK,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,KAAK,EAAE,eAAe,MAAM;CAC/H,MAAM,WAAW,KAAK,MAAM,QAAQ,eAAe,KAAK;CACxD,MAAM,YAAY,KAAK,QAAQ,QAAQ,QAAQ,cAAc,QAAQ,QAAQ;CA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late","#export","#rawConfig","Readable","EventEmitter","ws","WebSocket","PassThrough"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Voice events include 'speaking', 'writing', and 'error'.\n * Supported native input events use their unprefixed OpenAI names:\n * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',\n * and 'conversation.item.input_audio_transcription.completed'.\n * These native events deliver the complete received payload, including transcription usage when present.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('input_audio_buffer.speech_started', ev => {\n this.emit('input_audio_buffer.speech_started', ev);\n });\n this.client.on('input_audio_buffer.speech_stopped', ev => {\n this.emit('input_audio_buffer.speech_stopped', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n this.emit('conversation.item.input_audio_transcription.completed', ev);\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;EACJ,CAAC;CACF,QAAQ,CAAC;AACV;;;;;;;AAOA,SAAS,mBAAmB,MAAM;CACjC,MAAM,aAAa,KAAK,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,KAAK,EAAE,eAAe,MAAM;CAC/H,MAAM,WAAW,KAAK,MAAM,QAAQ,eAAe,KAAK;CACxD,MAAM,YAAY,KAAK,QAAQ,QAAQ,QAAQ,cAAc,QAAQ,QAAQ;CAC7E,IAAI,CAAC,cAAc,CAAC,YAAY,UAAU,WAAW,GAAG,OAAO,KAAK;CACpE,OAAO;EACN,GAAG,cAAc,CAAC;EAClB,GAAG,WAAW,EAAE,OAAO;GACtB,MAAM,SAAS;GACf,SAAS,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
package/dist/index.d.ts CHANGED
@@ -270,9 +270,11 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
270
270
  }): Promise<void>;
271
271
  /**
272
272
  * Registers an event listener for voice events.
273
- * Available events: 'speaking', 'writing, 'error'
274
- * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'
275
- * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.
273
+ * Voice events include 'speaking', 'writing', and 'error'.
274
+ * Supported native input events use their unprefixed OpenAI names:
275
+ * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',
276
+ * and 'conversation.item.input_audio_transcription.completed'.
277
+ * These native events deliver the complete received payload, including transcription usage when present.
276
278
  *
277
279
  * @param event - Name of the event to listen for
278
280
  * @param callback - Function to call when the event occurs
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,EAAE,QAAQ,EAAwB,MAAM,qBAAqB,CAAC;AAI1E;;GAEG;AACH,KAAK,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;AA8C9C,KAAK,MAAM,GAAG,UAAU,CAAC;AA2BzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,qBAAa,mBAAoB,SAAQ,WAAW;IAgChD,OAAO,CAAC,OAAO;IA/BjB,OAAO,CAAC,EAAE,CAAC,CAAY;IACvB,OAAO,CAAC,KAAK,CAAmB;IAChC,OAAO,CAAC,MAAM,CAA6C;IAC3D,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,KAAK,CAAC,CAAS;IACvB,OAAO,CAAC,KAAK,CAAU;IACvB,OA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IAAI,CAK/C;IAED;;;;;;;;;;;;;;;;;;;OAmBG;IACH,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAOhD;IAED;;;;OAIG;IACH,OAAO,CAAC,IAAI;IAQZ,OAAO,CAAC,mBAAmB;YA6Gb,mBAAmB;YAanB,kBAAkB;IAoDhC,OAAO,CAAC,kBAAkB;IAc1B,OAAO,CAAC,SAAS;CAYlB"}
package/dist/index.js CHANGED
@@ -875,9 +875,11 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
875
875
  }
876
876
  /**
877
877
  * Registers an event listener for voice events.
878
- * Available events: 'speaking', 'writing, 'error'
879
- * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'
880
- * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.
878
+ * Voice events include 'speaking', 'writing', and 'error'.
879
+ * Supported native input events use their unprefixed OpenAI names:
880
+ * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',
881
+ * and 'conversation.item.input_audio_transcription.completed'.
882
+ * These native events deliver the complete received payload, including transcription usage when present.
881
883
  *
882
884
  * @param event - Name of the event to listen for
883
885
  * @param callback - Function to call when the event occurs
@@ -958,6 +960,12 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
958
960
  this.client.on("session.updated", (ev) => {
959
961
  this.emit("session.updated", ev);
960
962
  });
963
+ this.client.on("input_audio_buffer.speech_started", (ev) => {
964
+ this.emit("input_audio_buffer.speech_started", ev);
965
+ });
966
+ this.client.on("input_audio_buffer.speech_stopped", (ev) => {
967
+ this.emit("input_audio_buffer.speech_stopped", ev);
968
+ });
961
969
  this.client.on("response.created", (ev) => {
962
970
  this.emit("response.created", ev);
963
971
  const speakerStream = new PassThrough();
@@ -974,6 +982,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
974
982
  });
975
983
  });
976
984
  this.client.on("conversation.item.input_audio_transcription.completed", (ev) => {
985
+ this.emit("conversation.item.input_audio_transcription.completed", ev);
977
986
  if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) this.emit("writing", {
978
987
  text: ev.transcript,
979
988
  response_id: ev.item_id,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#adapterContext","#correlate","#export","#rawConfig"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Available events: 'speaking', 'writing, 'error'\n * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'\n * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;EACJ,CAAC;CACF,QAAQ,CAAC;AACV;;;;;;;AAOA,SAAS,mBAAmB,MAAM;CACjC,MAAM,aAAa,KAAK,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,KAAK,EAAE,eAAe,MAAM;CAC/H,MAAM,WAAW,KAAK,MAAM,QAAQ,eAAe,KAAK;CACxD,MAAM,YAAY,KAAK,QAAQ,QAAQ,QAAQ,cAAc,QAAQ,QAAQ;CAC7E,IAAI,CAAC,cAAc,CAAC,YAAY,UAAU,WAAW,GAAG,OAAO,KAAK;CACpE,OAAO;EACN,GAAG,cAAc,CAAC;EAClB,GAAG,WAAW,EAAE,OAAO;GACtB,MAAM,SAAS;GACf,SAAS,SAAS;GAClB,OAAO,SAAS;EACjB,EAAE,IAAI,CAAC;EACP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AAK,UAAU,MAAM;GAC/B,EACF,CAAC;EACH,SAAS,GAAG;GACV,MAAM,MAAM;GACZ,QAAQ,KAAK,uBAAuB,OAAO,KAAK,KAAK,IAAI,OAAO;GAChE,KAAK,UAAU,4BAA4B,EACzC,MAAM;IACJ,MAAM;IACN,SAAS,OAAO;IAChB,QAAQ,KAAK,UAAU,EAAE,OAAO,IAAI,QAAQ,CAAC;GAC/C,EACF,CAAC;EACH;CACF;CAEA,mBAA2B,YAAgC;EACzD,MAAM,yBAAS,IAAI,YAAY,WAAW,SAAS,CAAC;EACpD,MAAM,OAAO,IAAI,SAAS,MAAM;EAChC,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,KAAK,SAAS,IAAI,GAAG,WAAW,IAAK,IAAI;EAE3C,MAAM,aAAa,IAAI,WAAW,MAAM;EACxC,IAAI,SAAS;EACb,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,UAAU,OAAO,aAAa,WAAW,EAAG;EAE9C,OAAO,KAAK,MAAM;CACpB;CAEA,UAAkB,MAAc,MAAW;EACzC,IAAI,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MAC7C,KAAK,MAAM,KAAK;GAAQ;GAAM,GAAG;EAAK,CAAC;OAEvC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
1
+ {"version":3,"file":"index.js","names":["#adapterContext","#correlate","#export","#rawConfig"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Voice events include 'speaking', 'writing', and 'error'.\n * Supported native input events use their unprefixed OpenAI names:\n * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',\n * and 'conversation.item.input_audio_transcription.completed'.\n * These native events deliver the complete received payload, including transcription usage when present.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('input_audio_buffer.speech_started', ev => {\n this.emit('input_audio_buffer.speech_started', ev);\n });\n this.client.on('input_audio_buffer.speech_stopped', ev => {\n this.emit('input_audio_buffer.speech_stopped', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n this.emit('conversation.item.input_audio_transcription.completed', ev);\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW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,KAAK,KAAK,IAAI,OAAO;GAChE,KAAK,UAAU,4BAA4B,EACzC,MAAM;IACJ,MAAM;IACN,SAAS,OAAO;IAChB,QAAQ,KAAK,UAAU,EAAE,OAAO,IAAI,QAAQ,CAAC;GAC/C,EACF,CAAC;EACH;CACF;CAEA,mBAA2B,YAAgC;EACzD,MAAM,yBAAS,IAAI,YAAY,WAAW,SAAS,CAAC;EACpD,MAAM,OAAO,IAAI,SAAS,MAAM;EAChC,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,KAAK,SAAS,IAAI,GAAG,WAAW,IAAK,IAAI;EAE3C,MAAM,aAAa,IAAI,WAAW,MAAM;EACxC,IAAI,SAAS;EACb,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,UAAU,OAAO,aAAa,WAAW,EAAG;EAE9C,OAAO,KAAK,MAAM;CACpB;CAEA,UAAkB,MAAc,MAAW;EACzC,IAAI,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MAC7C,KAAK,MAAM,KAAK;GAAQ;GAAM,GAAG;EAAK,CAAC;OAEvC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/voice-openai-realtime",
3
- "version": "0.13.10",
3
+ "version": "0.13.11-alpha.1",
4
4
  "description": "Mastra OpenAI Realtime API integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -25,7 +25,7 @@
25
25
  "dependencies": {
26
26
  "openai-realtime-api": "^1.0.8",
27
27
  "ws": "^8.21.0",
28
- "@mastra/schema-compat": "1.3.9"
28
+ "@mastra/schema-compat": "1.3.10-alpha.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "22.20.1",
@@ -39,8 +39,8 @@
39
39
  "vitest": "4.1.10",
40
40
  "zod": "^4.4.3",
41
41
  "@internal/lint": "0.0.132",
42
- "@internal/types-builder": "0.0.107",
43
- "@internal/voice": "0.0.30"
42
+ "@internal/voice": "0.0.30",
43
+ "@internal/types-builder": "0.0.107"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "zod": "^3.25.0 || ^4.0.0"