@mastra/voice-openai-realtime 0.13.11-alpha.2 → 0.14.0-alpha.3
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.
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/integrations-voice-openai.md +19 -7
- package/dist/index.cjs +39 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +39 -7
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/docs/SKILL.md
CHANGED
|
@@ -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.
|
|
6
|
+
version: "0.14.0-alpha.3"
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
## When to use
|
|
@@ -232,6 +232,16 @@ Disconnects from the OpenAI Realtime session and cleans up resources. Should be
|
|
|
232
232
|
|
|
233
233
|
Returns: `void`
|
|
234
234
|
|
|
235
|
+
#### `sendEvent()`
|
|
236
|
+
|
|
237
|
+
Sends a raw client event to the OpenAI Realtime session. Use this for session control that has no dedicated method, such as adding conversation items. Events sent before the session is created are queued and sent once it is.
|
|
238
|
+
|
|
239
|
+
**type** (`string`): OpenAI Realtime client event type, such as conversation.item.create.
|
|
240
|
+
|
|
241
|
+
**data** (`Record<string, unknown>`): Event payload sent alongside the type. (Default: `{}`)
|
|
242
|
+
|
|
243
|
+
Returns: `void`
|
|
244
|
+
|
|
235
245
|
#### `getSpeakers()`
|
|
236
246
|
|
|
237
247
|
Returns a list of available voice speakers.
|
|
@@ -270,17 +280,19 @@ The OpenAIRealtimeVoice class emits the following events:
|
|
|
270
280
|
|
|
271
281
|
#### OpenAI Realtime Events
|
|
272
282
|
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
**openAIRealtime:conversation.created** (`event`): Emitted when a new conversation is created.
|
|
283
|
+
Every server event received from the OpenAI Realtime API is also emitted with the `openAIRealtime:` prefix, using the [OpenAI server event type](https://platform.openai.com/docs/api-reference/realtime-server-events) as the suffix. The callback receives the complete event payload.
|
|
276
284
|
|
|
277
|
-
|
|
285
|
+
```typescript
|
|
286
|
+
voice.on('openAIRealtime:rate_limits.updated', event => {
|
|
287
|
+
console.log(event.rate_limits)
|
|
288
|
+
})
|
|
289
|
+
```
|
|
278
290
|
|
|
279
|
-
|
|
291
|
+
#### Socket Events
|
|
280
292
|
|
|
281
|
-
**
|
|
293
|
+
**open** (`event`): Emitted when the WebSocket connection to OpenAI opens.
|
|
282
294
|
|
|
283
|
-
**
|
|
295
|
+
**close** (`event`): Emitted when the WebSocket connection closes, including when OpenAI closes it. Callback receives { code: number, reason: string }.
|
|
284
296
|
|
|
285
297
|
### Available voices
|
|
286
298
|
|
package/dist/index.cjs
CHANGED
|
@@ -495,6 +495,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
495
495
|
tools;
|
|
496
496
|
debug;
|
|
497
497
|
queue = [];
|
|
498
|
+
sessionReady = false;
|
|
498
499
|
transcriber;
|
|
499
500
|
requestContext;
|
|
500
501
|
connectionAbort;
|
|
@@ -776,6 +777,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
776
777
|
this.ws = new ws.WebSocket(url, void 0, { headers: { Authorization: "Bearer " + apiKey } });
|
|
777
778
|
const ws$2 = this.ws;
|
|
778
779
|
this.state = "close";
|
|
780
|
+
this.sessionReady = false;
|
|
779
781
|
this.client.removeAllListeners();
|
|
780
782
|
const controller = new AbortController();
|
|
781
783
|
this.connectionAbort = controller;
|
|
@@ -791,6 +793,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
791
793
|
} finally {
|
|
792
794
|
this.connectionAbort = void 0;
|
|
793
795
|
}
|
|
796
|
+
this.sessionReady = true;
|
|
794
797
|
const openaiTools = transformTools(this.tools);
|
|
795
798
|
this.updateConfig({
|
|
796
799
|
type: "realtime",
|
|
@@ -881,6 +884,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
881
884
|
* 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',
|
|
882
885
|
* and 'conversation.item.input_audio_transcription.completed'.
|
|
883
886
|
* These native events deliver the complete received payload, including transcription usage when present.
|
|
887
|
+
* Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.
|
|
884
888
|
*
|
|
885
889
|
* @param event - Name of the event to listen for
|
|
886
890
|
* @param callback - Function to call when the event occurs
|
|
@@ -944,10 +948,23 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
944
948
|
ws$3.on("error", (error) => {
|
|
945
949
|
if (this.ws === ws$3) this.emit("error", error);
|
|
946
950
|
});
|
|
951
|
+
ws$3.on("open", () => {
|
|
952
|
+
if (this.ws === ws$3) this.emit("open");
|
|
953
|
+
});
|
|
954
|
+
ws$3.on("close", (code, reason) => {
|
|
955
|
+
if (this.ws !== ws$3) return;
|
|
956
|
+
this.state = "close";
|
|
957
|
+
this.sessionReady = false;
|
|
958
|
+
this.emit("close", {
|
|
959
|
+
code,
|
|
960
|
+
reason: reason.toString()
|
|
961
|
+
});
|
|
962
|
+
});
|
|
947
963
|
ws$3.on("message", (message) => {
|
|
948
964
|
if (this.ws !== ws$3) return;
|
|
949
965
|
const data = JSON.parse(message.toString());
|
|
950
966
|
this.client.emit(data.type, data);
|
|
967
|
+
this.emit(`openAIRealtime:${data.type}`, data);
|
|
951
968
|
if (this.debug) {
|
|
952
969
|
const { delta, ...fields } = data;
|
|
953
970
|
console.info(data.type, fields, delta?.length < 100 ? delta : "");
|
|
@@ -955,6 +972,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
955
972
|
});
|
|
956
973
|
this.client.on("session.created", (ev) => {
|
|
957
974
|
this.emit("session.created", ev);
|
|
975
|
+
this.sessionReady = true;
|
|
958
976
|
const queue = this.queue.splice(0, this.queue.length);
|
|
959
977
|
for (const ev of queue) this.ws?.send(JSON.stringify(ev));
|
|
960
978
|
});
|
|
@@ -1059,7 +1077,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
1059
1077
|
}
|
|
1060
1078
|
async handleFunctionCalls(ev) {
|
|
1061
1079
|
let handledFunctionCall = false;
|
|
1062
|
-
for (const output of ev.response?.output ?? []) if (output.type === "function_call") {
|
|
1080
|
+
for (const output of ev.response?.output ?? []) if (output.type === "function_call" && Object.hasOwn(this.tools ?? {}, output.name)) {
|
|
1063
1081
|
handledFunctionCall = true;
|
|
1064
1082
|
await this.handleFunctionCall(output);
|
|
1065
1083
|
}
|
|
@@ -1115,14 +1133,28 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
1115
1133
|
for (let i = 0; i < uint8Array.length; i++) binary += String.fromCharCode(uint8Array[i]);
|
|
1116
1134
|
return btoa(binary);
|
|
1117
1135
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1136
|
+
/**
|
|
1137
|
+
* Sends a raw client event to the OpenAI Realtime session.
|
|
1138
|
+
* Events sent before the session is created are queued and flushed once it is.
|
|
1139
|
+
*
|
|
1140
|
+
* @param type - OpenAI Realtime client event type, such as 'conversation.item.create'
|
|
1141
|
+
* @param data - Event payload merged alongside the type
|
|
1142
|
+
*
|
|
1143
|
+
* @example
|
|
1144
|
+
* ```typescript
|
|
1145
|
+
* voice.sendEvent('conversation.item.create', {
|
|
1146
|
+
* item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },
|
|
1147
|
+
* });
|
|
1148
|
+
* ```
|
|
1149
|
+
*/
|
|
1150
|
+
sendEvent(type, data = {}) {
|
|
1151
|
+
if (!this.sessionReady || !this.ws || this.ws.readyState !== this.ws.OPEN) this.queue.push({
|
|
1152
|
+
...data,
|
|
1153
|
+
type
|
|
1122
1154
|
});
|
|
1123
1155
|
else this.ws?.send(JSON.stringify({
|
|
1124
|
-
|
|
1125
|
-
|
|
1156
|
+
...data,
|
|
1157
|
+
type
|
|
1126
1158
|
}));
|
|
1127
1159
|
}
|
|
1128
1160
|
};
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#adapterContext","#correlate","#export","#rawConfig","Readable","EventEmitter","ws","WebSocket","PassThrough"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Voice events include 'speaking', 'writing', and 'error'.\n * Supported native input events use their unprefixed OpenAI names:\n * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',\n * and 'conversation.item.input_audio_transcription.completed'.\n * These native events deliver the complete received payload, including transcription usage when present.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('input_audio_buffer.speech_started', ev => {\n this.emit('input_audio_buffer.speech_started', ev);\n });\n this.client.on('input_audio_buffer.speech_stopped', ev => {\n this.emit('input_audio_buffer.speech_stopped', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n this.emit('conversation.item.input_audio_transcription.completed', ev);\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;EACJ,CAAC;CACF,QAAQ,CAAC;AACV;;;;;;;AAOA,SAAS,mBAAmB,MAAM;CACjC,MAAM,aAAa,KAAK,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,KAAK,EAAE,eAAe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,UAAU,OAAO,aAAa,WAAW,EAAG;EAE9C,OAAO,KAAK,MAAM;CACpB;CAEA,UAAkB,MAAc,MAAW;EACzC,IAAI,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MAC7C,KAAK,MAAM,KAAK;GAAQ;GAAM,GAAG;EAAK,CAAC;OAEvC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#adapterContext","#correlate","#export","#rawConfig","Readable","EventEmitter","ws","WebSocket","PassThrough"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private 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),\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,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AK,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
|
@@ -45,6 +45,7 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
|
|
|
45
45
|
private tools?;
|
|
46
46
|
private debug;
|
|
47
47
|
private queue;
|
|
48
|
+
private sessionReady;
|
|
48
49
|
private transcriber;
|
|
49
50
|
private requestContext?;
|
|
50
51
|
private connectionAbort?;
|
|
@@ -275,6 +276,7 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
|
|
|
275
276
|
* 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',
|
|
276
277
|
* and 'conversation.item.input_audio_transcription.completed'.
|
|
277
278
|
* These native events deliver the complete received payload, including transcription usage when present.
|
|
279
|
+
* Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.
|
|
278
280
|
*
|
|
279
281
|
* @param event - Name of the event to listen for
|
|
280
282
|
* @param callback - Function to call when the event occurs
|
|
@@ -324,7 +326,21 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
|
|
|
324
326
|
private handleFunctionCalls;
|
|
325
327
|
private handleFunctionCall;
|
|
326
328
|
private int16ArrayToBase64;
|
|
327
|
-
|
|
329
|
+
/**
|
|
330
|
+
* Sends a raw client event to the OpenAI Realtime session.
|
|
331
|
+
* Events sent before the session is created are queued and flushed once it is.
|
|
332
|
+
*
|
|
333
|
+
* @param type - OpenAI Realtime client event type, such as 'conversation.item.create'
|
|
334
|
+
* @param data - Event payload merged alongside the type
|
|
335
|
+
*
|
|
336
|
+
* @example
|
|
337
|
+
* ```typescript
|
|
338
|
+
* voice.sendEvent('conversation.item.create', {
|
|
339
|
+
* item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },
|
|
340
|
+
* });
|
|
341
|
+
* ```
|
|
342
|
+
*/
|
|
343
|
+
sendEvent(type: string, data?: Record<string, unknown>): void;
|
|
328
344
|
}
|
|
329
345
|
export {};
|
|
330
346
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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;
|
|
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,O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CAAC,MAAM,EAAE,OAAO,CAAM,QAWzD;CACF"}
|
package/dist/index.js
CHANGED
|
@@ -494,6 +494,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
494
494
|
tools;
|
|
495
495
|
debug;
|
|
496
496
|
queue = [];
|
|
497
|
+
sessionReady = false;
|
|
497
498
|
transcriber;
|
|
498
499
|
requestContext;
|
|
499
500
|
connectionAbort;
|
|
@@ -775,6 +776,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
775
776
|
this.ws = new WebSocket(url, void 0, { headers: { Authorization: "Bearer " + apiKey } });
|
|
776
777
|
const ws = this.ws;
|
|
777
778
|
this.state = "close";
|
|
779
|
+
this.sessionReady = false;
|
|
778
780
|
this.client.removeAllListeners();
|
|
779
781
|
const controller = new AbortController();
|
|
780
782
|
this.connectionAbort = controller;
|
|
@@ -790,6 +792,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
790
792
|
} finally {
|
|
791
793
|
this.connectionAbort = void 0;
|
|
792
794
|
}
|
|
795
|
+
this.sessionReady = true;
|
|
793
796
|
const openaiTools = transformTools(this.tools);
|
|
794
797
|
this.updateConfig({
|
|
795
798
|
type: "realtime",
|
|
@@ -880,6 +883,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
880
883
|
* 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',
|
|
881
884
|
* and 'conversation.item.input_audio_transcription.completed'.
|
|
882
885
|
* These native events deliver the complete received payload, including transcription usage when present.
|
|
886
|
+
* Every server event is also emitted as 'openAIRealtime:<event.type>', and the socket emits 'open' and 'close'.
|
|
883
887
|
*
|
|
884
888
|
* @param event - Name of the event to listen for
|
|
885
889
|
* @param callback - Function to call when the event occurs
|
|
@@ -943,10 +947,23 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
943
947
|
ws.on("error", (error) => {
|
|
944
948
|
if (this.ws === ws) this.emit("error", error);
|
|
945
949
|
});
|
|
950
|
+
ws.on("open", () => {
|
|
951
|
+
if (this.ws === ws) this.emit("open");
|
|
952
|
+
});
|
|
953
|
+
ws.on("close", (code, reason) => {
|
|
954
|
+
if (this.ws !== ws) return;
|
|
955
|
+
this.state = "close";
|
|
956
|
+
this.sessionReady = false;
|
|
957
|
+
this.emit("close", {
|
|
958
|
+
code,
|
|
959
|
+
reason: reason.toString()
|
|
960
|
+
});
|
|
961
|
+
});
|
|
946
962
|
ws.on("message", (message) => {
|
|
947
963
|
if (this.ws !== ws) return;
|
|
948
964
|
const data = JSON.parse(message.toString());
|
|
949
965
|
this.client.emit(data.type, data);
|
|
966
|
+
this.emit(`openAIRealtime:${data.type}`, data);
|
|
950
967
|
if (this.debug) {
|
|
951
968
|
const { delta, ...fields } = data;
|
|
952
969
|
console.info(data.type, fields, delta?.length < 100 ? delta : "");
|
|
@@ -954,6 +971,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
954
971
|
});
|
|
955
972
|
this.client.on("session.created", (ev) => {
|
|
956
973
|
this.emit("session.created", ev);
|
|
974
|
+
this.sessionReady = true;
|
|
957
975
|
const queue = this.queue.splice(0, this.queue.length);
|
|
958
976
|
for (const ev of queue) this.ws?.send(JSON.stringify(ev));
|
|
959
977
|
});
|
|
@@ -1058,7 +1076,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
1058
1076
|
}
|
|
1059
1077
|
async handleFunctionCalls(ev) {
|
|
1060
1078
|
let handledFunctionCall = false;
|
|
1061
|
-
for (const output of ev.response?.output ?? []) if (output.type === "function_call") {
|
|
1079
|
+
for (const output of ev.response?.output ?? []) if (output.type === "function_call" && Object.hasOwn(this.tools ?? {}, output.name)) {
|
|
1062
1080
|
handledFunctionCall = true;
|
|
1063
1081
|
await this.handleFunctionCall(output);
|
|
1064
1082
|
}
|
|
@@ -1114,14 +1132,28 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
1114
1132
|
for (let i = 0; i < uint8Array.length; i++) binary += String.fromCharCode(uint8Array[i]);
|
|
1115
1133
|
return btoa(binary);
|
|
1116
1134
|
}
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1135
|
+
/**
|
|
1136
|
+
* Sends a raw client event to the OpenAI Realtime session.
|
|
1137
|
+
* Events sent before the session is created are queued and flushed once it is.
|
|
1138
|
+
*
|
|
1139
|
+
* @param type - OpenAI Realtime client event type, such as 'conversation.item.create'
|
|
1140
|
+
* @param data - Event payload merged alongside the type
|
|
1141
|
+
*
|
|
1142
|
+
* @example
|
|
1143
|
+
* ```typescript
|
|
1144
|
+
* voice.sendEvent('conversation.item.create', {
|
|
1145
|
+
* item: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Hello' }] },
|
|
1146
|
+
* });
|
|
1147
|
+
* ```
|
|
1148
|
+
*/
|
|
1149
|
+
sendEvent(type, data = {}) {
|
|
1150
|
+
if (!this.sessionReady || !this.ws || this.ws.readyState !== this.ws.OPEN) this.queue.push({
|
|
1151
|
+
...data,
|
|
1152
|
+
type
|
|
1121
1153
|
});
|
|
1122
1154
|
else this.ws?.send(JSON.stringify({
|
|
1123
|
-
|
|
1124
|
-
|
|
1155
|
+
...data,
|
|
1156
|
+
type
|
|
1125
1157
|
}));
|
|
1126
1158
|
}
|
|
1127
1159
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#adapterContext","#correlate","#export","#rawConfig"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Voice events include 'speaking', 'writing', and 'error'.\n * Supported native input events use their unprefixed OpenAI names:\n * 'input_audio_buffer.speech_started', 'input_audio_buffer.speech_stopped',\n * and 'conversation.item.input_audio_transcription.completed'.\n * These native events deliver the complete received payload, including transcription usage when present.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('input_audio_buffer.speech_started', ev => {\n this.emit('input_audio_buffer.speech_started', ev);\n });\n this.client.on('input_audio_buffer.speech_stopped', ev => {\n this.emit('input_audio_buffer.speech_stopped', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n this.emit('conversation.item.input_audio_transcription.completed', ev);\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,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IAAI,OAAO;GAChE,KAAK,UAAU,4BAA4B,EACzC,MAAM;IACJ,MAAM;IACN,SAAS,OAAO;IAChB,QAAQ,KAAK,UAAU,EAAE,OAAO,IAAI,QAAQ,CAAC;GAC/C,EACF,CAAC;EACH;CACF;CAEA,mBAA2B,YAAgC;EACzD,MAAM,yBAAS,IAAI,YAAY,WAAW,SAAS,CAAC;EACpD,MAAM,OAAO,IAAI,SAAS,MAAM;EAChC,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,KAAK,SAAS,IAAI,GAAG,WAAW,IAAK,IAAI;EAE3C,MAAM,aAAa,IAAI,WAAW,MAAM;EACxC,IAAI,SAAS;EACb,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,UAAU,OAAO,aAAa,WAAW,EAAG;EAE9C,OAAO,KAAK,MAAM;CACpB;CAEA,UAAkB,MAAc,MAAW;EACzC,IAAI,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MAC7C,KAAK,MAAM,KAAK;GAAQ;GAAM,GAAG;EAAK,CAAC;OAEvC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#adapterContext","#correlate","#export","#rawConfig"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private 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),\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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AAS,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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/voice-openai-realtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0-alpha.3",
|
|
4
4
|
"description": "Mastra OpenAI Realtime API integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
"vitest": "4.1.10",
|
|
40
40
|
"zod": "^4.4.3",
|
|
41
41
|
"@internal/lint": "0.0.132",
|
|
42
|
-
"@internal/
|
|
43
|
-
"@internal/
|
|
42
|
+
"@internal/types-builder": "0.0.107",
|
|
43
|
+
"@internal/voice": "0.0.30"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"zod": "^3.25.0 || ^4.0.0"
|