@mastra/voice-openai-realtime 0.14.4-alpha.0 → 0.14.4

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.14.4-alpha.0"
6
+ version: "0.14.4"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.14.4-alpha.0",
2
+ "version": "0.14.4",
3
3
  "package": "@mastra/voice-openai-realtime",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -495,6 +495,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
495
495
  transcriber;
496
496
  requestContext;
497
497
  connectionAbort;
498
+ speakerStreams = /* @__PURE__ */ new Map();
498
499
  /**
499
500
  * Creates a new instance of OpenAIRealtimeVoice.
500
501
  *
@@ -552,6 +553,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
552
553
  if (!this.ws) return;
553
554
  this.ws.close();
554
555
  this.state = "close";
556
+ this.closeSpeakerStreams();
555
557
  }
556
558
  /**
557
559
  * Equips the voice instance with a set of instructions.
@@ -775,6 +777,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
775
777
  this.state = "close";
776
778
  this.sessionReady = false;
777
779
  this.client.removeAllListeners();
780
+ this.closeSpeakerStreams();
778
781
  const controller = new AbortController();
779
782
  this.connectionAbort = controller;
780
783
  this.setupEventListeners();
@@ -806,6 +809,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
806
809
  this.state = "close";
807
810
  this.connectionAbort?.abort(/* @__PURE__ */ new Error("OpenAI realtime connection disconnected during handshake"));
808
811
  this.ws?.close();
812
+ this.closeSpeakerStreams();
809
813
  }
810
814
  /**
811
815
  * Streams audio data in real-time to the OpenAI service.
@@ -936,8 +940,12 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
936
940
  if (!this.events[event]) return;
937
941
  for (const callback of this.events[event]) callback(...args);
938
942
  }
943
+ closeSpeakerStreams() {
944
+ for (const stream$1 of this.speakerStreams.values()) if (!stream$1.writableEnded) stream$1.end();
945
+ this.speakerStreams.clear();
946
+ }
939
947
  setupEventListeners() {
940
- const speakerStreams = /* @__PURE__ */ new Map();
948
+ const speakerStreams = this.speakerStreams;
941
949
  const userTranscriptionDeltaItems = /* @__PURE__ */ new Set();
942
950
  if (!this.ws) throw new Error("WebSocket not initialized");
943
951
  const ws$3 = this.ws;
@@ -951,6 +959,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
951
959
  if (this.ws !== ws$3) return;
952
960
  this.state = "close";
953
961
  this.sessionReady = false;
962
+ this.closeSpeakerStreams();
954
963
  this.emit("close", {
955
964
  code,
956
965
  reason: reason.toString()
@@ -1063,9 +1072,11 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
1063
1072
  this.client.on("response.text.done", handleTextDone);
1064
1073
  this.client.on("response.output_text.done", handleTextDone);
1065
1074
  this.client.on("response.done", async (ev) => {
1075
+ const stream$2 = speakerStreams.get(ev.response.id);
1076
+ if (stream$2 && !stream$2.writableEnded) stream$2.end();
1077
+ speakerStreams.delete(ev.response.id);
1066
1078
  await this.handleFunctionCalls(ev);
1067
1079
  this.emit("response.done", ev);
1068
- speakerStreams.delete(ev.response.id);
1069
1080
  });
1070
1081
  this.client.on("error", async (ev) => {
1071
1082
  this.emit("error", ev);
@@ -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 // Both ToolAction (createTool) and VercelTool take the input data as the\n // first argument, matching @mastra/core's ToolExecuteFunction(inputData, context).\n return await tool.execute(args, {\n toolCallId: 'unknown',\n messages: [],\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 sessionReady = false;\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.sessionReady = false;\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 this.sessionReady = true;\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 * Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.\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('open', () => {\n if (this.ws === ws) this.emit('open');\n });\n ws.on('close', (code, reason) => {\n if (this.ws !== ws) return;\n this.state = 'close';\n this.sessionReady = false;\n this.emit('close', { code, reason: reason.toString() });\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 this.emit(`openAIRealtime:${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 this.sessionReady = true;\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' && Object.hasOwn(this.tools ?? {}, output.name)) {\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 ?? null),\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 /**\n * Sends a raw client event to the OpenAI Realtime session.\n * Events sent before the session is created are queued and flushed once it is.\n *\n * @param type - OpenAI Realtime client event type, such as 'conversation.item.create'\n * @param data - Event payload merged alongside the type\n *\n * @example\n * ```typescript\n * voice.sendEvent('conversation.item.create', {\n * item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },\n * });\n * ```\n */\n sendEvent(type: string, data: Record<string, unknown> = {}) {\n if (!this.sessionReady || !this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ ...data, type });\n } else {\n this.ws?.send(\n JSON.stringify({\n ...data,\n type,\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,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AAgC;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;;;;;;;;;;;;;;;CAgBA,UAAU,MAAc,OAAgC,CAAC,GAAG;EAC1D,IAAI,CAAC,KAAK,gBAAgB,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MACnE,KAAK,MAAM,KAAK;GAAE,GAAG;GAAM;EAAK,CAAC;OAEjC,KAAK,IAAI,KACP,KAAK,UAAU;GACb,GAAG;GACH;EACF,CAAC,CACH;CAEJ;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["#adapterContext","#correlate","#export","#rawConfig","Readable","EventEmitter","ws","WebSocket","stream","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 // Both ToolAction (createTool) and VercelTool take the input data as the\n // first argument, matching @mastra/core's ToolExecuteFunction(inputData, context).\n return await tool.execute(args, {\n toolCallId: 'unknown',\n messages: [],\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 sessionReady = false;\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n private speakerStreams = new Map<string, StreamWithId>();\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 this.closeSpeakerStreams();\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.sessionReady = false;\n this.client.removeAllListeners();\n this.closeSpeakerStreams();\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 this.sessionReady = true;\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 this.closeSpeakerStreams();\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 * Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.\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 closeSpeakerStreams(): void {\n for (const stream of this.speakerStreams.values()) {\n if (!stream.writableEnded) stream.end();\n }\n this.speakerStreams.clear();\n }\n\n private setupEventListeners(): void {\n const speakerStreams = this.speakerStreams;\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('open', () => {\n if (this.ws === ws) this.emit('open');\n });\n ws.on('close', (code, reason) => {\n if (this.ws !== ws) return;\n this.state = 'close';\n this.sessionReady = false;\n this.closeSpeakerStreams();\n this.emit('close', { code, reason: reason.toString() });\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 this.emit(`openAIRealtime:${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 this.sessionReady = true;\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 // Responses without audio (tool-call-only turns, text modality, or cancelled before any audio)\n // never send output_audio.done, so end the stream here. Do it before running tools so a slow\n // or failing tool cannot hold the stream open.\n const stream = speakerStreams.get(ev.response.id);\n if (stream && !stream.writableEnded) stream.end();\n speakerStreams.delete(ev.response.id);\n\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\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' && Object.hasOwn(this.tools ?? {}, output.name)) {\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 ?? null),\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 /**\n * Sends a raw client event to the OpenAI Realtime session.\n * Events sent before the session is created are queued and flushed once it is.\n *\n * @param type - OpenAI Realtime client event type, such as 'conversation.item.create'\n * @param data - Event payload merged alongside the type\n *\n * @example\n * ```typescript\n * voice.sendEvent('conversation.item.create', {\n * item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },\n * });\n * ```\n */\n sendEvent(type: string, data: Record<string, unknown> = {}) {\n if (!this.sessionReady || !this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ ...data, type });\n } else {\n this.ws?.send(\n JSON.stringify({\n ...data,\n type,\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,Q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AS,OAAO;IAChB,QAAQ,KAAK,UAAU,UAAU,IAAI;GACvC,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;;;;;;;;;;;;;;;CAgBA,UAAU,MAAc,OAAgC,CAAC,GAAG;EAC1D,IAAI,CAAC,KAAK,gBAAgB,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MACnE,KAAK,MAAM,KAAK;GAAE,GAAG;GAAM;EAAK,CAAC;OAEjC,KAAK,IAAI,KACP,KAAK,UAAU;GACb,GAAG;GACH;EACF,CAAC,CACH;CAEJ;AACF"}
package/dist/index.d.ts CHANGED
@@ -49,6 +49,7 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
49
49
  private transcriber;
50
50
  private requestContext?;
51
51
  private connectionAbort?;
52
+ private speakerStreams;
52
53
  /**
53
54
  * Creates a new instance of OpenAIRealtimeVoice.
54
55
  *
@@ -322,6 +323,7 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
322
323
  * @param args Arguments to pass to the callbacks
323
324
  */
324
325
  private emit;
326
+ private closeSpeakerStreams;
325
327
  private setupEventListeners;
326
328
  private handleFunctionCalls;
327
329
  private handleFunctionCall;
@@ -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;IAiChD,OAAO,CAAC,OAAO;IAhCjB,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,OAAO,CAAC,KAAK,CAAiB;IAC9B,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,WAAW,CAAmC;IACtD,OAAO,CAAC,cAAc,CAAC,CAAiB;IACxC,OAAO,CAAC,eAAe,CAAC,CAAkB;IAC1C;;;;;;;;;;;;;;;;;;OAkBG;IACH,YACU,OAAO,GAAE;QACf,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,GAAG,CAAC,EAAE,MAAM,CAAC;QACb,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC;QACzB,WAAW,CAAC,EAAE,QAAQ,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C,mBAAmB;YA+Hb,mBAAmB;YAanB,kBAAkB;IAoDhC,OAAO,CAAC,kBAAkB;IAc1B;;;;;;;;;;;;;OAaG;IACH,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,QAWzD;CACF"}
package/dist/index.js CHANGED
@@ -494,6 +494,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
494
494
  transcriber;
495
495
  requestContext;
496
496
  connectionAbort;
497
+ speakerStreams = /* @__PURE__ */ new Map();
497
498
  /**
498
499
  * Creates a new instance of OpenAIRealtimeVoice.
499
500
  *
@@ -551,6 +552,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
551
552
  if (!this.ws) return;
552
553
  this.ws.close();
553
554
  this.state = "close";
555
+ this.closeSpeakerStreams();
554
556
  }
555
557
  /**
556
558
  * Equips the voice instance with a set of instructions.
@@ -774,6 +776,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
774
776
  this.state = "close";
775
777
  this.sessionReady = false;
776
778
  this.client.removeAllListeners();
779
+ this.closeSpeakerStreams();
777
780
  const controller = new AbortController();
778
781
  this.connectionAbort = controller;
779
782
  this.setupEventListeners();
@@ -805,6 +808,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
805
808
  this.state = "close";
806
809
  this.connectionAbort?.abort(/* @__PURE__ */ new Error("OpenAI realtime connection disconnected during handshake"));
807
810
  this.ws?.close();
811
+ this.closeSpeakerStreams();
808
812
  }
809
813
  /**
810
814
  * Streams audio data in real-time to the OpenAI service.
@@ -935,8 +939,12 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
935
939
  if (!this.events[event]) return;
936
940
  for (const callback of this.events[event]) callback(...args);
937
941
  }
942
+ closeSpeakerStreams() {
943
+ for (const stream of this.speakerStreams.values()) if (!stream.writableEnded) stream.end();
944
+ this.speakerStreams.clear();
945
+ }
938
946
  setupEventListeners() {
939
- const speakerStreams = /* @__PURE__ */ new Map();
947
+ const speakerStreams = this.speakerStreams;
940
948
  const userTranscriptionDeltaItems = /* @__PURE__ */ new Set();
941
949
  if (!this.ws) throw new Error("WebSocket not initialized");
942
950
  const ws = this.ws;
@@ -950,6 +958,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
950
958
  if (this.ws !== ws) return;
951
959
  this.state = "close";
952
960
  this.sessionReady = false;
961
+ this.closeSpeakerStreams();
953
962
  this.emit("close", {
954
963
  code,
955
964
  reason: reason.toString()
@@ -1062,9 +1071,11 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
1062
1071
  this.client.on("response.text.done", handleTextDone);
1063
1072
  this.client.on("response.output_text.done", handleTextDone);
1064
1073
  this.client.on("response.done", async (ev) => {
1074
+ const stream = speakerStreams.get(ev.response.id);
1075
+ if (stream && !stream.writableEnded) stream.end();
1076
+ speakerStreams.delete(ev.response.id);
1065
1077
  await this.handleFunctionCalls(ev);
1066
1078
  this.emit("response.done", ev);
1067
- speakerStreams.delete(ev.response.id);
1068
1079
  });
1069
1080
  this.client.on("error", async (ev) => {
1070
1081
  this.emit("error", ev);
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 // Both ToolAction (createTool) and VercelTool take the input data as the\n // first argument, matching @mastra/core's ToolExecuteFunction(inputData, context).\n return await tool.execute(args, {\n toolCallId: 'unknown',\n messages: [],\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 sessionReady = false;\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.sessionReady = false;\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 this.sessionReady = true;\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 * Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.\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('open', () => {\n if (this.ws === ws) this.emit('open');\n });\n ws.on('close', (code, reason) => {\n if (this.ws !== ws) return;\n this.state = 'close';\n this.sessionReady = false;\n this.emit('close', { code, reason: reason.toString() });\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 this.emit(`openAIRealtime:${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 this.sessionReady = true;\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' && Object.hasOwn(this.tools ?? {}, output.name)) {\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 ?? null),\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 /**\n * Sends a raw client event to the OpenAI Realtime session.\n * Events sent before the session is created are queued and flushed once it is.\n *\n * @param type - OpenAI Realtime client event type, such as 'conversation.item.create'\n * @param data - Event payload merged alongside the type\n *\n * @example\n * ```typescript\n * voice.sendEvent('conversation.item.create', {\n * item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },\n * });\n * ```\n */\n sendEvent(type: string, data: Record<string, unknown> = {}) {\n if (!this.sessionReady || !this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ ...data, type });\n } else {\n this.ws?.send(\n JSON.stringify({\n ...data,\n type,\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,GAAG,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I,CAAC,KAAK,gBAAgB,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MACnE,KAAK,MAAM,KAAK;GAAE,GAAG;GAAM;EAAK,CAAC;OAEjC,KAAK,IAAI,KACP,KAAK,UAAU;GACb,GAAG;GACH;EACF,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 // Both ToolAction (createTool) and VercelTool take the input data as the\n // first argument, matching @mastra/core's ToolExecuteFunction(inputData, context).\n return await tool.execute(args, {\n toolCallId: 'unknown',\n messages: [],\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 sessionReady = false;\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n private speakerStreams = new Map<string, StreamWithId>();\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 this.closeSpeakerStreams();\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.sessionReady = false;\n this.client.removeAllListeners();\n this.closeSpeakerStreams();\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 this.sessionReady = true;\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 this.closeSpeakerStreams();\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 * Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.\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 closeSpeakerStreams(): void {\n for (const stream of this.speakerStreams.values()) {\n if (!stream.writableEnded) stream.end();\n }\n this.speakerStreams.clear();\n }\n\n private setupEventListeners(): void {\n const speakerStreams = this.speakerStreams;\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('open', () => {\n if (this.ws === ws) this.emit('open');\n });\n ws.on('close', (code, reason) => {\n if (this.ws !== ws) return;\n this.state = 'close';\n this.sessionReady = false;\n this.closeSpeakerStreams();\n this.emit('close', { code, reason: reason.toString() });\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 this.emit(`openAIRealtime:${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 this.sessionReady = true;\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 // Responses without audio (tool-call-only turns, text modality, or cancelled before any audio)\n // never send output_audio.done, so end the stream here. Do it before running tools so a slow\n // or failing tool cannot hold the stream open.\n const stream = speakerStreams.get(ev.response.id);\n if (stream && !stream.writableEnded) stream.end();\n speakerStreams.delete(ev.response.id);\n\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\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' && Object.hasOwn(this.tools ?? {}, output.name)) {\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 ?? null),\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 /**\n * Sends a raw client event to the OpenAI Realtime session.\n * Events sent before the session is created are queued and flushed once it is.\n *\n * @param type - OpenAI Realtime client event type, such as 'conversation.item.create'\n * @param data - Event payload merged alongside the type\n *\n * @example\n * ```typescript\n * voice.sendEvent('conversation.item.create', {\n * item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },\n * });\n * ```\n */\n sendEvent(type: string, data: Record<string, unknown> = {}) {\n if (!this.sessionReady || !this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ ...data, type });\n } else {\n this.ws?.send(\n JSON.stringify({\n ...data,\n type,\n }),\n );\n }\n }\n}\n"],"mappings":";;;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K,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,UAAU,OAAO,aAAa,WAAW,EAAG;EAE9C,OAAO,KAAK,MAAM;CACpB;;;;;;;;;;;;;;;CAgBA,UAAU,MAAc,OAAgC,CAAC,GAAG;EAC1D,IAAI,CAAC,KAAK,gBAAgB,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MACnE,KAAK,MAAM,KAAK;GAAE,GAAG;GAAM;EAAK,CAAC;OAEjC,KAAK,IAAI,KACP,KAAK,UAAU;GACb,GAAG;GACH;EACF,CAAC,CACH;CAEJ;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/voice-openai-realtime",
3
- "version": "0.14.4-alpha.0",
3
+ "version": "0.14.4",
4
4
  "description": "Mastra OpenAI Realtime API integration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -38,9 +38,9 @@
38
38
  "typescript": "^7.0.2",
39
39
  "vitest": "4.1.11",
40
40
  "zod": "^4.6.4",
41
- "@internal/types-builder": "0.0.116",
42
- "@internal/lint": "0.0.141",
43
- "@internal/voice": "0.0.39"
41
+ "@internal/lint": "0.0.142",
42
+ "@internal/voice": "0.0.40",
43
+ "@internal/types-builder": "0.0.117"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "zod": "^3.25.0 || ^4.0.0"