@mastra/voice-openai-realtime 0.13.8 → 0.13.9-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -1
- package/dist/_types/@internal_voice/dist/_types/@internal_core/dist/request-context/index.d.ts +14 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/reference-voice-overview.md +25 -0
- package/dist/index.cjs +76 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +76 -7
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ voice.updateSession({
|
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
// Connect to the realtime service
|
|
31
|
-
await voice.
|
|
31
|
+
await voice.connect();
|
|
32
32
|
|
|
33
33
|
// Audio data from voice provider
|
|
34
34
|
voice.on('speaking', (audioData: Int16Array) => {
|
|
@@ -61,6 +61,27 @@ await voice.send(microphoneStream);
|
|
|
61
61
|
voice.close();
|
|
62
62
|
```
|
|
63
63
|
|
|
64
|
+
## Connection failures
|
|
65
|
+
|
|
66
|
+
`connect()` waits for both the WebSocket to open and the server to create a session. It rejects if the connection fails, the server reports an error during the handshake, or the socket closes before the session is ready. A silent handshake times out after 15,000 milliseconds by default.
|
|
67
|
+
|
|
68
|
+
Use `connectTimeoutMs` to configure the handshake deadline. The value must be a positive, finite number no greater than 2,147,483,647 milliseconds. Catch connection failures directly; an `error` event listener does not replace handling the rejected promise.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
const voice = new OpenAIRealtimeVoice({
|
|
72
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
73
|
+
connectTimeoutMs: 30_000,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
await voice.connect();
|
|
78
|
+
} catch (error) {
|
|
79
|
+
console.error('Could not connect to the realtime service:', error);
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
A failed handshake closes its socket and clears its pending waits. You can retry with `connect()` on the same instance. The deadline only applies to connection setup, not to an established session.
|
|
84
|
+
|
|
64
85
|
## Documentation
|
|
65
86
|
|
|
66
87
|
- [@mastra/voice-openai-realtime documentation](https://mastra.ai/integrations/voice/openai)
|
package/dist/_types/@internal_voice/dist/_types/@internal_core/dist/request-context/index.d.ts
CHANGED
|
@@ -55,6 +55,19 @@ declare const MASTRA_AUTH_TOKEN_KEY = "mastra__authToken";
|
|
|
55
55
|
* nested delegated runs. Internal to delegation — do not set it yourself.
|
|
56
56
|
*/
|
|
57
57
|
declare const MASTRA_INHERITED_MEMORY_KEY = "mastra__inheritedMemory";
|
|
58
|
+
/**
|
|
59
|
+
* Reserved key naming who sent a user message: `{ id, name?, avatarUrl? }`.
|
|
60
|
+
* Set by the host that authenticated the request; the agent-controller copies
|
|
61
|
+
* it onto the sent message as `providerMetadata.mastra.author` so a shared
|
|
62
|
+
* thread can show who wrote what.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* // In your auth middleware:
|
|
67
|
+
* requestContext.setRaw(MASTRA_MESSAGE_AUTHOR_KEY, { id: user.id, name: user.name, avatarUrl: user.avatarUrl });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
declare const MASTRA_MESSAGE_AUTHOR_KEY = "mastra__messageAuthor";
|
|
58
71
|
type VersionSelector = {
|
|
59
72
|
versionId: string;
|
|
60
73
|
} | {
|
|
@@ -215,5 +228,5 @@ declare class RequestContext<Values extends Record<string, any> | unknown = unkn
|
|
|
215
228
|
get all(): Values extends Record<string, any> ? Values : Record<string, any>;
|
|
216
229
|
}
|
|
217
230
|
//#endregion
|
|
218
|
-
export { MASTRA_AUTH_TOKEN_KEY, MASTRA_INHERITED_MEMORY_KEY, MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, MASTRA_VERSIONS_KEY, RequestContext, VersionOverrides, VersionSelector, mergeVersionOverrides };
|
|
231
|
+
export { MASTRA_AUTH_TOKEN_KEY, MASTRA_INHERITED_MEMORY_KEY, MASTRA_MESSAGE_AUTHOR_KEY, MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, MASTRA_VERSIONS_KEY, RequestContext, VersionOverrides, VersionSelector, mergeVersionOverrides };
|
|
219
232
|
//# sourceMappingURL=index.d.ts.map
|
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.13.
|
|
6
|
+
version: "0.13.9-alpha.1"
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
## When to use
|
|
@@ -882,6 +882,18 @@ const voice = new DeepgramVoice({
|
|
|
882
882
|
|
|
883
883
|
Visit the [Deepgram Voice Reference](https://mastra.ai/integrations/voice/deepgram) for more information on the Deepgram voice provider.
|
|
884
884
|
|
|
885
|
+
**Gladia**:
|
|
886
|
+
|
|
887
|
+
```typescript
|
|
888
|
+
const voice = new GladiaVoice({
|
|
889
|
+
listeningModel: {
|
|
890
|
+
apiKey: process.env.GLADIA_API_KEY,
|
|
891
|
+
},
|
|
892
|
+
})
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
Visit the [Gladia Voice integration](https://mastra.ai/integrations/voice/gladia) for configuration and transcription options.
|
|
896
|
+
|
|
885
897
|
**Inworld**:
|
|
886
898
|
|
|
887
899
|
```typescript
|
|
@@ -965,6 +977,19 @@ const voice = new MurfVoice({
|
|
|
965
977
|
|
|
966
978
|
Visit the [Murf Voice Reference](https://mastra.ai/integrations/voice/murf) for more information on the Murf voice provider.
|
|
967
979
|
|
|
980
|
+
**ModelsLab**:
|
|
981
|
+
|
|
982
|
+
```typescript
|
|
983
|
+
const voice = new ModelsLabVoice({
|
|
984
|
+
speechModel: {
|
|
985
|
+
apiKey: process.env.MODELSLAB_API_KEY,
|
|
986
|
+
},
|
|
987
|
+
speaker: '5',
|
|
988
|
+
})
|
|
989
|
+
```
|
|
990
|
+
|
|
991
|
+
Visit the [ModelsLab Voice integration](https://mastra.ai/integrations/voice/modelslab) for configuration and synthesis options.
|
|
992
|
+
|
|
968
993
|
**OpenAI Realtime**:
|
|
969
994
|
|
|
970
995
|
```typescript
|
package/dist/index.cjs
CHANGED
|
@@ -497,6 +497,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
497
497
|
queue = [];
|
|
498
498
|
transcriber;
|
|
499
499
|
requestContext;
|
|
500
|
+
connectionAbort;
|
|
500
501
|
/**
|
|
501
502
|
* Creates a new instance of OpenAIRealtimeVoice.
|
|
502
503
|
*
|
|
@@ -519,6 +520,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
519
520
|
constructor(options = {}) {
|
|
520
521
|
super();
|
|
521
522
|
this.options = options;
|
|
523
|
+
if (options.connectTimeoutMs !== void 0 && (!Number.isFinite(options.connectTimeoutMs) || options.connectTimeoutMs <= 0 || options.connectTimeoutMs > 2147483647)) throw new Error("connectTimeoutMs must be a positive finite number no greater than 2147483647");
|
|
522
524
|
this.client = new events.EventEmitter();
|
|
523
525
|
this.state = "close";
|
|
524
526
|
this.events = {};
|
|
@@ -700,13 +702,59 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
700
702
|
} else this.emit("error", /* @__PURE__ */ new Error("Unsupported audio data format"));
|
|
701
703
|
}
|
|
702
704
|
waitForOpen() {
|
|
703
|
-
return
|
|
704
|
-
this.ws?.on("open", resolve);
|
|
705
|
-
});
|
|
705
|
+
return this.waitForHandshake("open");
|
|
706
706
|
}
|
|
707
707
|
waitForSessionCreated() {
|
|
708
|
-
return
|
|
709
|
-
|
|
708
|
+
return this.waitForHandshake("session.created");
|
|
709
|
+
}
|
|
710
|
+
waitForHandshake(event) {
|
|
711
|
+
const ws$1 = this.ws;
|
|
712
|
+
const signal = this.connectionAbort?.signal;
|
|
713
|
+
return new Promise((resolve, reject) => {
|
|
714
|
+
if (!ws$1) {
|
|
715
|
+
reject(/* @__PURE__ */ new Error("WebSocket not initialized"));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (signal?.aborted) {
|
|
719
|
+
reject(signal.reason);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (ws$1.readyState === ws.WebSocket.CLOSED || ws$1.readyState === ws.WebSocket.CLOSING) {
|
|
723
|
+
reject(/* @__PURE__ */ new Error("OpenAI realtime WebSocket is closed"));
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (event === "open" && ws$1.readyState === ws.WebSocket.OPEN) {
|
|
727
|
+
resolve();
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
const cleanup = () => {
|
|
731
|
+
clearTimeout(timer);
|
|
732
|
+
ws$1.removeListener("open", onReady);
|
|
733
|
+
ws$1.removeListener("error", onError);
|
|
734
|
+
ws$1.removeListener("close", onClose);
|
|
735
|
+
this.client.removeListener("session.created", onReady);
|
|
736
|
+
this.client.removeListener("error", onProtocolError);
|
|
737
|
+
signal?.removeEventListener("abort", onAbort);
|
|
738
|
+
};
|
|
739
|
+
const onReady = () => {
|
|
740
|
+
cleanup();
|
|
741
|
+
resolve();
|
|
742
|
+
};
|
|
743
|
+
const onError = (error) => {
|
|
744
|
+
cleanup();
|
|
745
|
+
reject(error);
|
|
746
|
+
};
|
|
747
|
+
const onClose = (code, reason) => onError(/* @__PURE__ */ new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));
|
|
748
|
+
const onProtocolError = (event) => onError(new Error(event.error.message, { cause: event.error }));
|
|
749
|
+
const onAbort = () => onError(signal.reason);
|
|
750
|
+
const timeoutMs = this.options.connectTimeoutMs ?? 15e3;
|
|
751
|
+
const timer = setTimeout(() => onError(/* @__PURE__ */ new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
752
|
+
if (event === "open") ws$1.once("open", onReady);
|
|
753
|
+
else this.client.once("session.created", onReady);
|
|
754
|
+
ws$1.once("error", onError);
|
|
755
|
+
ws$1.once("close", onClose);
|
|
756
|
+
this.client.once("error", onProtocolError);
|
|
757
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
710
758
|
});
|
|
711
759
|
}
|
|
712
760
|
/**
|
|
@@ -726,8 +774,23 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
726
774
|
const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;
|
|
727
775
|
this.requestContext = requestContext;
|
|
728
776
|
this.ws = new ws.WebSocket(url, void 0, { headers: { Authorization: "Bearer " + apiKey } });
|
|
777
|
+
const ws$2 = this.ws;
|
|
778
|
+
this.state = "close";
|
|
779
|
+
this.client.removeAllListeners();
|
|
780
|
+
const controller = new AbortController();
|
|
781
|
+
this.connectionAbort = controller;
|
|
729
782
|
this.setupEventListeners();
|
|
730
|
-
|
|
783
|
+
try {
|
|
784
|
+
await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);
|
|
785
|
+
} catch (error) {
|
|
786
|
+
controller.abort(error);
|
|
787
|
+
this.state = "close";
|
|
788
|
+
this.ws = void 0;
|
|
789
|
+
ws$2.close();
|
|
790
|
+
throw error;
|
|
791
|
+
} finally {
|
|
792
|
+
this.connectionAbort = void 0;
|
|
793
|
+
}
|
|
731
794
|
const openaiTools = transformTools(this.tools);
|
|
732
795
|
this.updateConfig({
|
|
733
796
|
type: "realtime",
|
|
@@ -742,6 +805,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
742
805
|
}
|
|
743
806
|
disconnect() {
|
|
744
807
|
this.state = "close";
|
|
808
|
+
this.connectionAbort?.abort(/* @__PURE__ */ new Error("OpenAI realtime connection disconnected during handshake"));
|
|
745
809
|
this.ws?.close();
|
|
746
810
|
}
|
|
747
811
|
/**
|
|
@@ -874,7 +938,12 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
874
938
|
const speakerStreams = /* @__PURE__ */ new Map();
|
|
875
939
|
const userTranscriptionDeltaItems = /* @__PURE__ */ new Set();
|
|
876
940
|
if (!this.ws) throw new Error("WebSocket not initialized");
|
|
877
|
-
this.ws
|
|
941
|
+
const ws$3 = this.ws;
|
|
942
|
+
ws$3.on("error", (error) => {
|
|
943
|
+
if (this.ws === ws$3) this.emit("error", error);
|
|
944
|
+
});
|
|
945
|
+
ws$3.on("message", (message) => {
|
|
946
|
+
if (this.ws !== ws$3) return;
|
|
878
947
|
const data = JSON.parse(message.toString());
|
|
879
948
|
this.client.emit(data.type, data);
|
|
880
949
|
if (this.debug) {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#adapterContext","#correlate","#export","#rawConfig","Readable","EventEmitter","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 /**\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 } = {},\n ) {\n super();\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() {\n return new Promise(resolve => {\n this.ws?.on('open', resolve);\n });\n }\n\n waitForSessionCreated() {\n return new Promise(resolve => {\n this.client.on('session.created', resolve);\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 this.setupEventListeners();\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\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.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Available events: 'speaking', 'writing, 'error'\n * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'\n * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n this.ws.on('message', message => {\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;EACJ,CAAC;CACF,QAAQ,CAAC;AACV;;;;;;;AAOA,SAAS,mBAAmB,MAAM;CACjC,MAAM,aAAa,KAAK,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,KAAK,EAAE,eAAe,MAAM;CAC/H,MAAM,WAAW,KAAK,MAAM,QAAQ,eAAe,KAAK;CACxD,MAAM,YAAY,KAAK,QAAQ,QAAQ,QAAQ,cAAc,QAAQ,QAAQ;CA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AAK,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.cjs","names":["#adapterContext","#correlate","#export","#rawConfig","Readable","EventEmitter","ws","WebSocket","PassThrough"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Available events: 'speaking', 'writing, 'error'\n * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'\n * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;EACJ,CAAC;CACF,QAAQ,CAAC;AACV;;;;;;;AAOA,SAAS,mBAAmB,MAAM;CACjC,MAAM,aAAa,KAAK,MAAM,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ,GAAG,KAAK,EAAE,eAAe,MAAM;CA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vC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -47,6 +47,7 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
|
|
|
47
47
|
private queue;
|
|
48
48
|
private transcriber;
|
|
49
49
|
private requestContext?;
|
|
50
|
+
private connectionAbort?;
|
|
50
51
|
/**
|
|
51
52
|
* Creates a new instance of OpenAIRealtimeVoice.
|
|
52
53
|
*
|
|
@@ -73,6 +74,8 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
|
|
|
73
74
|
speaker?: Realtime.Voice;
|
|
74
75
|
transcriber?: Realtime.AudioTranscriptionModel;
|
|
75
76
|
debug?: boolean;
|
|
77
|
+
/** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */
|
|
78
|
+
connectTimeoutMs?: number;
|
|
76
79
|
});
|
|
77
80
|
/**
|
|
78
81
|
* Returns a list of available voice speakers.
|
|
@@ -206,8 +209,9 @@ export declare class OpenAIRealtimeVoice extends MastraVoice {
|
|
|
206
209
|
* ```
|
|
207
210
|
*/
|
|
208
211
|
listen(audioData: NodeJS.ReadableStream): Promise<void>;
|
|
209
|
-
waitForOpen(): Promise<
|
|
210
|
-
waitForSessionCreated(): Promise<
|
|
212
|
+
waitForOpen(): Promise<void>;
|
|
213
|
+
waitForSessionCreated(): Promise<void>;
|
|
214
|
+
private waitForHandshake;
|
|
211
215
|
/**
|
|
212
216
|
* Establishes a connection to the OpenAI realtime service.
|
|
213
217
|
* Must be called before using speak, listen, or relay functions.
|
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,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E,cAAc,EAAE,GAAE;QAAE,cAAc,CAAC,EAAE,cAAc,CAAA;KAAO,iBA8CzE;IAED,UAAU,SAIT;IAED;;;;;;;;;;;;;;;;;OAiBG;IACG,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,cAAc,GAAG,UAAU,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BzF;IAED;;;;;;;;;;;;;;;;;OAiBG;IACG,MAAM,CAAC,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,cAAc,CAAA;KAAE,iBAE9D;IAED;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAK/C;IAED;;;;;;;;;;;;;;;;;;;OAmBG;IACH,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,GAAG,IAAI,CAOhD;IAED;;;;OAIG;IACH,OAAO,CAAC,IAAI;IAQZ,OAAO,CAAC,mBAAmB;YAsGb,mBAAmB;YAanB,kBAAkB;IAoDhC,OAAO,CAAC,kBAAkB;IAc1B,OAAO,CAAC,SAAS;CAYlB"}
|
package/dist/index.js
CHANGED
|
@@ -496,6 +496,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
496
496
|
queue = [];
|
|
497
497
|
transcriber;
|
|
498
498
|
requestContext;
|
|
499
|
+
connectionAbort;
|
|
499
500
|
/**
|
|
500
501
|
* Creates a new instance of OpenAIRealtimeVoice.
|
|
501
502
|
*
|
|
@@ -518,6 +519,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
518
519
|
constructor(options = {}) {
|
|
519
520
|
super();
|
|
520
521
|
this.options = options;
|
|
522
|
+
if (options.connectTimeoutMs !== void 0 && (!Number.isFinite(options.connectTimeoutMs) || options.connectTimeoutMs <= 0 || options.connectTimeoutMs > 2147483647)) throw new Error("connectTimeoutMs must be a positive finite number no greater than 2147483647");
|
|
521
523
|
this.client = new EventEmitter();
|
|
522
524
|
this.state = "close";
|
|
523
525
|
this.events = {};
|
|
@@ -699,13 +701,59 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
699
701
|
} else this.emit("error", /* @__PURE__ */ new Error("Unsupported audio data format"));
|
|
700
702
|
}
|
|
701
703
|
waitForOpen() {
|
|
702
|
-
return
|
|
703
|
-
this.ws?.on("open", resolve);
|
|
704
|
-
});
|
|
704
|
+
return this.waitForHandshake("open");
|
|
705
705
|
}
|
|
706
706
|
waitForSessionCreated() {
|
|
707
|
-
return
|
|
708
|
-
|
|
707
|
+
return this.waitForHandshake("session.created");
|
|
708
|
+
}
|
|
709
|
+
waitForHandshake(event) {
|
|
710
|
+
const ws = this.ws;
|
|
711
|
+
const signal = this.connectionAbort?.signal;
|
|
712
|
+
return new Promise((resolve, reject) => {
|
|
713
|
+
if (!ws) {
|
|
714
|
+
reject(/* @__PURE__ */ new Error("WebSocket not initialized"));
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
if (signal?.aborted) {
|
|
718
|
+
reject(signal.reason);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
|
|
722
|
+
reject(/* @__PURE__ */ new Error("OpenAI realtime WebSocket is closed"));
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (event === "open" && ws.readyState === WebSocket.OPEN) {
|
|
726
|
+
resolve();
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const cleanup = () => {
|
|
730
|
+
clearTimeout(timer);
|
|
731
|
+
ws.removeListener("open", onReady);
|
|
732
|
+
ws.removeListener("error", onError);
|
|
733
|
+
ws.removeListener("close", onClose);
|
|
734
|
+
this.client.removeListener("session.created", onReady);
|
|
735
|
+
this.client.removeListener("error", onProtocolError);
|
|
736
|
+
signal?.removeEventListener("abort", onAbort);
|
|
737
|
+
};
|
|
738
|
+
const onReady = () => {
|
|
739
|
+
cleanup();
|
|
740
|
+
resolve();
|
|
741
|
+
};
|
|
742
|
+
const onError = (error) => {
|
|
743
|
+
cleanup();
|
|
744
|
+
reject(error);
|
|
745
|
+
};
|
|
746
|
+
const onClose = (code, reason) => onError(/* @__PURE__ */ new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));
|
|
747
|
+
const onProtocolError = (event) => onError(new Error(event.error.message, { cause: event.error }));
|
|
748
|
+
const onAbort = () => onError(signal.reason);
|
|
749
|
+
const timeoutMs = this.options.connectTimeoutMs ?? 15e3;
|
|
750
|
+
const timer = setTimeout(() => onError(/* @__PURE__ */ new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
751
|
+
if (event === "open") ws.once("open", onReady);
|
|
752
|
+
else this.client.once("session.created", onReady);
|
|
753
|
+
ws.once("error", onError);
|
|
754
|
+
ws.once("close", onClose);
|
|
755
|
+
this.client.once("error", onProtocolError);
|
|
756
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
709
757
|
});
|
|
710
758
|
}
|
|
711
759
|
/**
|
|
@@ -725,8 +773,23 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
725
773
|
const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;
|
|
726
774
|
this.requestContext = requestContext;
|
|
727
775
|
this.ws = new WebSocket(url, void 0, { headers: { Authorization: "Bearer " + apiKey } });
|
|
776
|
+
const ws = this.ws;
|
|
777
|
+
this.state = "close";
|
|
778
|
+
this.client.removeAllListeners();
|
|
779
|
+
const controller = new AbortController();
|
|
780
|
+
this.connectionAbort = controller;
|
|
728
781
|
this.setupEventListeners();
|
|
729
|
-
|
|
782
|
+
try {
|
|
783
|
+
await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);
|
|
784
|
+
} catch (error) {
|
|
785
|
+
controller.abort(error);
|
|
786
|
+
this.state = "close";
|
|
787
|
+
this.ws = void 0;
|
|
788
|
+
ws.close();
|
|
789
|
+
throw error;
|
|
790
|
+
} finally {
|
|
791
|
+
this.connectionAbort = void 0;
|
|
792
|
+
}
|
|
730
793
|
const openaiTools = transformTools(this.tools);
|
|
731
794
|
this.updateConfig({
|
|
732
795
|
type: "realtime",
|
|
@@ -741,6 +804,7 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
741
804
|
}
|
|
742
805
|
disconnect() {
|
|
743
806
|
this.state = "close";
|
|
807
|
+
this.connectionAbort?.abort(/* @__PURE__ */ new Error("OpenAI realtime connection disconnected during handshake"));
|
|
744
808
|
this.ws?.close();
|
|
745
809
|
}
|
|
746
810
|
/**
|
|
@@ -873,7 +937,12 @@ var OpenAIRealtimeVoice = class extends MastraVoice {
|
|
|
873
937
|
const speakerStreams = /* @__PURE__ */ new Map();
|
|
874
938
|
const userTranscriptionDeltaItems = /* @__PURE__ */ new Set();
|
|
875
939
|
if (!this.ws) throw new Error("WebSocket not initialized");
|
|
876
|
-
this.ws
|
|
940
|
+
const ws = this.ws;
|
|
941
|
+
ws.on("error", (error) => {
|
|
942
|
+
if (this.ws === ws) this.emit("error", error);
|
|
943
|
+
});
|
|
944
|
+
ws.on("message", (message) => {
|
|
945
|
+
if (this.ws !== ws) return;
|
|
877
946
|
const data = JSON.parse(message.toString());
|
|
878
947
|
this.client.emit(data.type, data);
|
|
879
948
|
if (this.debug) {
|
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 /**\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 } = {},\n ) {\n super();\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() {\n return new Promise(resolve => {\n this.ws?.on('open', resolve);\n });\n }\n\n waitForSessionCreated() {\n return new Promise(resolve => {\n this.client.on('session.created', resolve);\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 this.setupEventListeners();\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\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.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Available events: 'speaking', 'writing, 'error'\n * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'\n * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n this.ws.on('message', message => {\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;GACpE,GAAG;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,KAAK,UAAU,EAAE,OAAO,IAAI,QAAQ,CAAC;GAC/C,EACF,CAAC;EACH;CACF;CAEA,mBAA2B,YAAgC;EACzD,MAAM,yBAAS,IAAI,YAAY,WAAW,SAAS,CAAC;EACpD,MAAM,OAAO,IAAI,SAAS,MAAM;EAChC,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,KAAK,SAAS,IAAI,GAAG,WAAW,IAAK,IAAI;EAE3C,MAAM,aAAa,IAAI,WAAW,MAAM;EACxC,IAAI,SAAS;EACb,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KACrC,UAAU,OAAO,aAAa,WAAW,EAAG;EAE9C,OAAO,KAAK,MAAM;CACpB;CAEA,UAAkB,MAAc,MAAW;EACzC,IAAI,CAAC,KAAK,MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MAC7C,KAAK,MAAM,KAAK;GAAQ;GAAM,GAAG;EAAK,CAAC;OAEvC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#adapterContext","#correlate","#export","#rawConfig"],"sources":["../../../packages/_internal-core/dist/logger/index.js","../../../packages/_internal-core/dist/base/index.js","../../../packages/_internals/voice/dist/aisdk-C_K-VCwq.js","../src/utils.ts","../src/index.ts"],"sourcesContent":["import { Transform } from \"stream\";\n//#region src/logger/adapter.ts\nfunction isAdaptableLogger(logger) {\n\treturn typeof logger.__attachObservability === \"function\";\n}\n/**\n* Export a tracked exception through the adapter sink, mirroring the\n* DualLogger dual-write shape (`errorId`/`domain`/`category`/`details`/`cause`\n* when present on a MastraError-like value). Never throws into the caller.\n*/\nfunction exportTrackedException(ctx, error, metadata) {\n\tif (!ctx?.options.export) return;\n\ttry {\n\t\tconst mastraError = error;\n\t\tctx.getLogSink()?.error(error.message, {\n\t\t\t...mastraError.id !== void 0 ? { errorId: mastraError.id } : {},\n\t\t\t...mastraError.domain !== void 0 ? { domain: mastraError.domain } : {},\n\t\t\t...mastraError.category !== void 0 ? { category: mastraError.category } : {},\n\t\t\t...mastraError.details !== void 0 ? { details: mastraError.details } : {},\n\t\t\t...error.cause instanceof Error ? { cause: error.cause.message } : {},\n\t\t\t...metadata\n\t\t});\n\t} catch {}\n}\n/**\n* Adapt IMastraLogger's variadic args into the structured `data` payload of\n* an exported log record. Extracts the first plain object as data,\n* serializes an Error arg, and collects remaining primitives under `args`\n* so the derived record preserves all context from the native call.\n*/\nfunction buildLogRecordData(args) {\n\tconst objectData = args.find((arg) => arg !== null && typeof arg === \"object\" && !Array.isArray(arg) && !(arg instanceof Error));\n\tconst errorArg = args.find((arg) => arg instanceof Error);\n\tconst extraArgs = args.filter((arg) => arg !== objectData && arg !== errorArg);\n\tif (!objectData && !errorArg && extraArgs.length === 0) return void 0;\n\treturn {\n\t\t...objectData ?? {},\n\t\t...errorArg ? { error: {\n\t\t\tname: errorArg.name,\n\t\t\tmessage: errorArg.message,\n\t\t\tstack: errorArg.stack\n\t\t} } : {},\n\t\t...extraArgs.length > 0 ? { args: extraArgs } : {}\n\t};\n}\n//#endregion\n//#region src/logger/index.ts\nconst RegisteredLogger = {\n\tAGENT: \"AGENT\",\n\tOBSERVABILITY: \"OBSERVABILITY\",\n\tAUTH: \"AUTH\",\n\tBROWSER: \"BROWSER\",\n\tNETWORK: \"NETWORK\",\n\tWORKFLOW: \"WORKFLOW\",\n\tLLM: \"LLM\",\n\tTTS: \"TTS\",\n\tVOICE: \"VOICE\",\n\tVECTOR: \"VECTOR\",\n\tBUNDLER: \"BUNDLER\",\n\tDEPLOYER: \"DEPLOYER\",\n\tMEMORY: \"MEMORY\",\n\tSTORAGE: \"STORAGE\",\n\tEMBEDDINGS: \"EMBEDDINGS\",\n\tMCP_SERVER: \"MCP_SERVER\",\n\tSERVER_CACHE: \"SERVER_CACHE\",\n\tSERVER: \"SERVER\",\n\tWORKSPACE: \"WORKSPACE\",\n\tCHANNEL: \"CHANNEL\"\n};\nconst LogLevel = {\n\tDEBUG: \"debug\",\n\tINFO: \"info\",\n\tWARN: \"warn\",\n\tERROR: \"error\",\n\tNONE: \"silent\"\n};\nvar LoggerTransport = class extends Transform {\n\tconstructor(opts = {}) {\n\t\tsuper({\n\t\t\t...opts,\n\t\t\tobjectMode: true\n\t\t});\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogs(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args?.page ?? 1,\n\t\t\tperPage: _args?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nconst createCustomTransport = (stream, listLogs, listLogsByRunId) => {\n\tlet transport = stream;\n\tif (listLogs) transport.listLogs = listLogs;\n\tif (listLogsByRunId) transport.listLogsByRunId = listLogsByRunId;\n\treturn transport;\n};\nvar MastraLogger = class {\n\tname;\n\tlevel;\n\ttransports;\n\tconstructor(options = {}) {\n\t\tthis.name = options.name || \"Mastra\";\n\t\tthis.level = options.level || LogLevel.ERROR;\n\t\tthis.transports = new Map(Object.entries(options.transports || {}));\n\t}\n\tgetTransports() {\n\t\treturn this.transports;\n\t}\n\ttrackException(_error, _metadata) {}\n\tasync listLogs(transportId, params) {\n\t\tif (!transportId || !this.transports.has(transportId)) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogs?.(params) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: params?.page ?? 1,\n\t\t\tperPage: params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId({ transportId, runId, fromDate, toDate, logLevel, filters, page, perPage }) {\n\t\tif (!transportId || !this.transports.has(transportId) || !runId) return {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t\treturn this.transports.get(transportId).listLogsByRunId?.({\n\t\t\trunId,\n\t\t\tfromDate,\n\t\t\ttoDate,\n\t\t\tlogLevel,\n\t\t\tfilters,\n\t\t\tpage,\n\t\t\tperPage\n\t\t}) ?? {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: page ?? 1,\n\t\t\tperPage: perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\nvar ConsoleLogger = class ConsoleLogger extends MastraLogger {\n\tcomponent;\n\tfilter;\n\t#adapterContext;\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t\tthis.component = options.component;\n\t\tthis.filter = options.filter;\n\t}\n\t/**\n\t* Adapter hook (see `AdaptableLogger`): enables native trace correlation\n\t* (trace_id/span_id appended to console output) and observability export\n\t* derived from the same record. Called by Mastra during setup.\n\t*/\n\t__attachObservability(ctx) {\n\t\tthis.#adapterContext = ctx;\n\t}\n\tchild(componentOrBindings) {\n\t\tconst component = typeof componentOrBindings === \"string\" ? componentOrBindings : componentOrBindings?.component ?? this.component;\n\t\tconst child = new ConsoleLogger({\n\t\t\tname: this.name,\n\t\t\tlevel: this.level,\n\t\t\tcomponent,\n\t\t\tfilter: this.filter\n\t\t});\n\t\tif (this.#adapterContext) child.__attachObservability(this.#adapterContext);\n\t\treturn child;\n\t}\n\t/**\n\t* Native-record correlation: when a span is active, append the trace\n\t* fields object to the console args so every destination sees them.\n\t*/\n\t#correlate(args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.correlation) return args;\n\t\ttry {\n\t\t\tconst fields = ctx.resolveTraceFields();\n\t\t\treturn fields ? [...args, fields] : args;\n\t\t} catch {\n\t\t\treturn args;\n\t\t}\n\t}\n\t/**\n\t* Export the record derived from the same native call to observability.\n\t* Mirrors DualLogger semantics: export is independent of the console\n\t* level filter, and never throws into the caller.\n\t*/\n\t#export(level, message, args) {\n\t\tconst ctx = this.#adapterContext;\n\t\tif (!ctx?.options.export) return;\n\t\ttry {\n\t\t\tctx.getLogSink()?.[level](message, buildLogRecordData(args));\n\t\t} catch {}\n\t}\n\tshouldLog(level, message, args) {\n\t\tif (!this.filter) return true;\n\t\ttry {\n\t\t\treturn this.filter({\n\t\t\t\tcomponent: this.component,\n\t\t\t\tlevel,\n\t\t\t\tmessage,\n\t\t\t\targs\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tconsole.error(`[Logger] Filter error for component=${this.component} level=${level}:`, e);\n\t\t\treturn true;\n\t\t}\n\t}\n\tprefix() {\n\t\treturn this.component ? `[${this.component}] ` : \"\";\n\t}\n\tdebug(message, ...args) {\n\t\tif (this.level === LogLevel.DEBUG && this.shouldLog(LogLevel.DEBUG, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"debug\", message, args);\n\t}\n\tinfo(message, ...args) {\n\t\tif ((this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.INFO, message, args)) console.info(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"info\", message, args);\n\t}\n\twarn(message, ...args) {\n\t\tif ((this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.WARN, message, args)) console.warn(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"warn\", message, args);\n\t}\n\terror(message, ...args) {\n\t\tif ((this.level === LogLevel.ERROR || this.level === LogLevel.WARN || this.level === LogLevel.INFO || this.level === LogLevel.DEBUG) && this.shouldLog(LogLevel.ERROR, message, args)) console.error(`${this.prefix()}${message}`, ...this.#correlate(args));\n\t\tthis.#export(\"error\", message, args);\n\t}\n\ttrackException(error, metadata) {\n\t\texportTrackedException(this.#adapterContext, error, metadata);\n\t}\n\tasync listLogs(_transportId, _params) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _params?.page ?? 1,\n\t\t\tperPage: _params?.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n\tasync listLogsByRunId(_args) {\n\t\treturn {\n\t\t\tlogs: [],\n\t\t\ttotal: 0,\n\t\t\tpage: _args.page ?? 1,\n\t\t\tperPage: _args.perPage ?? 100,\n\t\t\thasMore: false\n\t\t};\n\t}\n};\n//#endregion\nexport { ConsoleLogger, LogLevel, LoggerTransport, MastraLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, exportTrackedException, isAdaptableLogger };\n\n//# sourceMappingURL=index.js.map","import { ConsoleLogger, RegisteredLogger } from \"../logger/index.js\";\n//#region src/base/MastraBase.ts\nvar MastraBase = class {\n\tcomponent = RegisteredLogger.LLM;\n\tlogger;\n\tname;\n\t#rawConfig;\n\tconstructor({ component, name, rawConfig }) {\n\t\tthis.component = component || RegisteredLogger.LLM;\n\t\tthis.name = name;\n\t\tthis.#rawConfig = rawConfig;\n\t\tthis.logger = new ConsoleLogger({ name: `${this.component} - ${this.name}` });\n\t}\n\t/**\n\t* Returns the raw storage configuration this primitive was created from,\n\t* or undefined if it was created from code.\n\t*/\n\ttoRawConfig() {\n\t\treturn this.#rawConfig;\n\t}\n\t/**\n\t* Sets the raw storage configuration for this primitive.\n\t* @internal\n\t*/\n\t__setRawConfig(rawConfig) {\n\t\tthis.#rawConfig = rawConfig;\n\t}\n\t/**\n\t* Set the logger for the agent\n\t* @param logger\n\t*/\n\t__setLogger(logger) {\n\t\tthis.logger = \"child\" in logger && typeof logger.child === \"function\" ? logger.child({ component: this.component }) : logger;\n\t}\n};\n//#endregion\nexport { MastraBase };\n\n//# sourceMappingURL=index.js.map","import { MastraBase } from \"@internal/core/base\";\nimport { PassThrough } from \"stream\";\nimport { experimental_generateSpeech, experimental_transcribe } from \"@internal/ai-sdk-v5\";\n//#region src/voice/voice.ts\nvar MastraVoice = class extends MastraBase {\n\tlisteningModel;\n\tspeechModel;\n\tspeaker;\n\trealtimeConfig;\n\tconstructor({ listeningModel, speechModel, speaker, realtimeConfig, name } = {}) {\n\t\tsuper({\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname\n\t\t});\n\t\tthis.listeningModel = listeningModel;\n\t\tthis.speechModel = speechModel;\n\t\tthis.speaker = speaker;\n\t\tthis.realtimeConfig = realtimeConfig;\n\t}\n\t/**\n\t* Custom serialization for tracing/observability spans.\n\t* Excludes `apiKey` from listeningModel / speechModel / realtimeConfig\n\t* and any provider-specific state held by subclasses. Subclasses that\n\t* need to expose additional non-sensitive fields can override.\n\t*/\n\tserializeForSpan() {\n\t\treturn {\n\t\t\tcomponent: \"VOICE\",\n\t\t\tname: this.name,\n\t\t\tspeaker: this.speaker,\n\t\t\tlisteningModel: this.listeningModel ? { name: this.listeningModel.name } : void 0,\n\t\t\tspeechModel: this.speechModel ? { name: this.speechModel.name } : void 0,\n\t\t\trealtimeModel: this.realtimeConfig?.model\n\t\t};\n\t}\n\tupdateConfig(_options) {\n\t\tthis.logger.debug(\"updateConfig not implemented by this voice provider\");\n\t}\n\t/**\n\t* Initializes a WebSocket or WebRTC connection for real-time communication\n\t* @returns Promise that resolves when the connection is established\n\t*/\n\tasync connect(_options) {\n\t\tthis.logger.debug(\"connect not implemented by this voice provider\");\n\t}\n\t/**\n\t* Relay audio data to the voice provider for real-time processing\n\t* @param audioData Audio data to relay\n\t*/\n\tasync send(_audioData) {\n\t\tthis.logger.debug(\"relay not implemented by this voice provider\");\n\t}\n\t/**\n\t* Trigger voice providers to respond\n\t*/\n\tasync answer(_options) {\n\t\tthis.logger.debug(\"answer not implemented by this voice provider\");\n\t}\n\t/**\n\t* Equip the voice provider with instructions\n\t* @param instructions Instructions to add\n\t*/\n\taddInstructions(_instructions) {}\n\t/**\n\t* Equip the voice provider with tools\n\t* @param tools Array of tools to add\n\t*/\n\taddTools(_tools) {}\n\t/**\n\t* Disconnect from the WebSocket or WebRTC connection\n\t*/\n\tclose() {\n\t\tthis.logger.debug(\"close not implemented by this voice provider\");\n\t}\n\t/**\n\t* Register an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function that receives event data\n\t*/\n\ton(_event, _callback) {\n\t\tthis.logger.debug(\"on not implemented by this voice provider\");\n\t}\n\t/**\n\t* Remove an event listener\n\t* @param event Event name (e.g., 'speaking', 'writing', 'error')\n\t* @param callback Callback function to remove\n\t*/\n\toff(_event, _callback) {\n\t\tthis.logger.debug(\"off not implemented by this voice provider\");\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetSpeakers() {\n\t\tthis.logger.debug(\"getSpeakers not implemented by this voice provider\");\n\t\treturn Promise.resolve([]);\n\t}\n\t/**\n\t* Get available speakers/voices\n\t* @returns Array of available voice IDs and their metadata\n\t*/\n\tgetListener() {\n\t\tthis.logger.debug(\"getListener not implemented by this voice provider\");\n\t\treturn Promise.resolve({ enabled: false });\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/speech.ts\nvar AISDKSpeech = class extends MastraVoice {\n\tmodel;\n\tdefaultVoice;\n\tconstructor(model, options) {\n\t\tsuper({ name: \"ai-sdk-speech\" });\n\t\tthis.model = model;\n\t\tthis.defaultVoice = options?.voice;\n\t}\n\tasync speak(input, options) {\n\t\tconst text = typeof input === \"string\" ? input : await this.streamToText(input);\n\t\tconst result = await experimental_generateSpeech({\n\t\t\tmodel: this.model,\n\t\t\ttext,\n\t\t\tvoice: options?.speaker || this.defaultVoice,\n\t\t\tlanguage: options?.language,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t});\n\t\tconst stream = new PassThrough();\n\t\tstream.end(Buffer.from(result.audio.uint8Array));\n\t\treturn stream;\n\t}\n\tasync listen() {\n\t\tthrow new Error(\"AI SDK speech models do not support transcription. Use AISDKTranscription instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: false };\n\t}\n\tasync streamToText(stream) {\n\t\tconst chunks = [];\n\t\tfor await (const chunk of stream) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks).toString(\"utf-8\");\n\t}\n};\n//#endregion\n//#region src/voice/aisdk/transcription.ts\nvar AISDKTranscription = class extends MastraVoice {\n\tmodel;\n\tconstructor(model) {\n\t\tsuper({ name: \"ai-sdk-transcription\" });\n\t\tthis.model = model;\n\t}\n\tasync speak() {\n\t\tthrow new Error(\"AI SDK transcription models do not support text-to-speech. Use AISDKSpeech instead.\");\n\t}\n\tasync getSpeakers() {\n\t\treturn [];\n\t}\n\tasync getListener() {\n\t\treturn { enabled: true };\n\t}\n\t/**\n\t* Transcribe audio to text\n\t* For enhanced metadata (segments, language, duration), use AI SDK's transcribe() directly\n\t*/\n\tasync listen(audioStream, options) {\n\t\tconst audioBuffer = await this.convertToBuffer(audioStream);\n\t\treturn (await experimental_transcribe({\n\t\t\tmodel: this.model,\n\t\t\taudio: audioBuffer,\n\t\t\tproviderOptions: options?.providerOptions,\n\t\t\tabortSignal: options?.abortSignal,\n\t\t\theaders: options?.headers\n\t\t})).text;\n\t}\n\tasync convertToBuffer(audio) {\n\t\tif (Buffer.isBuffer(audio)) return audio;\n\t\tif (audio instanceof Uint8Array) return Buffer.from(audio);\n\t\tif (typeof audio === \"string\") return Buffer.from(audio, \"base64\");\n\t\tconst chunks = [];\n\t\tfor await (const chunk of audio) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n\t\treturn Buffer.concat(chunks);\n\t}\n};\n//#endregion\nexport { AISDKSpeech as n, MastraVoice as r, AISDKTranscription as t };\n\n//# sourceMappingURL=aisdk-C_K-VCwq.js.map","import { Readable } from 'node:stream';\nimport type { ToolsInput } from '@internal/voice';\nimport { standardSchemaToJSONSchema, toStandardSchema } from '@mastra/schema-compat/schema';\n\nexport type OpenAIExecuteFunction = (args: any) => Promise<any>;\ntype ToolDefinition = {\n type: 'function';\n name: string;\n description: string;\n parameters: {\n [key: string]: any;\n };\n};\n\ntype TTools = ToolsInput;\nexport const transformTools = (tools?: TTools) => {\n const openaiTools: { openaiTool: ToolDefinition; execute: OpenAIExecuteFunction }[] = [];\n for (const [name, tool] of Object.entries(tools || {})) {\n let parameters: { [key: string]: any };\n\n if ('inputSchema' in tool && tool.inputSchema) {\n parameters = toToolParameters(tool.inputSchema);\n } else if ('parameters' in tool) {\n parameters = toToolParameters(tool.parameters);\n } else {\n console.warn(`Tool ${name} has neither inputSchema nor parameters, skipping`);\n continue;\n }\n const openaiTool: ToolDefinition = {\n type: 'function',\n name,\n description: tool.description || `Tool: ${name}`,\n parameters,\n };\n\n if (tool.execute) {\n // Create an adapter function that works with both ToolAction and VercelTool execute functions\n const executeAdapter = async (args: any) => {\n try {\n if (!tool.execute) {\n throw new Error(`Tool ${name} has no execute function`);\n }\n\n // For ToolAction, the first argument is a context object with the args in a 'context' property\n if ('inputSchema' in tool) {\n return await tool.execute(\n { context: args },\n {\n toolCallId: 'unknown',\n messages: [],\n },\n );\n }\n // For VercelTool, pass args directly\n else {\n // Create a minimal ToolExecutionOptions object with required properties\n const options = {\n toolCallId: 'unknown',\n messages: [],\n };\n return await tool.execute(args, options);\n }\n } catch (error) {\n console.error(`Error executing tool ${name}:`, error);\n throw error;\n }\n };\n openaiTools.push({ openaiTool, execute: executeAdapter });\n } else {\n console.warn(`Tool ${name} has no execute function, skipping`);\n }\n }\n return openaiTools;\n};\n\nexport const isReadableStream = (obj: unknown) => {\n return (\n obj &&\n obj instanceof Readable &&\n typeof obj.read === 'function' &&\n typeof obj.pipe === 'function' &&\n obj.readable === true\n );\n};\n\nfunction toToolParameters(schema: unknown): { [key: string]: any } {\n const parameters = standardSchemaToJSONSchema(toStandardSchema(schema as never), { io: 'input' }) as {\n [key: string]: any;\n };\n delete parameters.$schema;\n return parameters;\n}\n","import { EventEmitter } from 'node:events';\nimport { PassThrough } from 'node:stream';\nimport type { ToolsInput, RequestContext } from '@internal/voice';\nimport { MastraVoice } from '@internal/voice';\nimport type { Realtime, RealtimeServerEvents } from 'openai-realtime-api';\nimport { WebSocket } from 'ws';\nimport { isReadableStream, transformTools } from './utils';\n\n/**\n * Event callback function type\n */\ntype EventCallback = (...args: any[]) => void;\n\ntype StreamWithId = PassThrough & { id: string };\n\n/**\n * Map of event types to their callback arrays\n */\ntype EventMap = {\n transcribing: [{ text: string }];\n writing: [{ text: string }];\n speaking: [{ audio: string }];\n speaker: [StreamWithId];\n error: [Error];\n} & {\n [key: string]: EventCallback[];\n};\n\n/** Default voice for text-to-speech. 'alloy' provides a neutral, balanced voice suitable for most use cases */\nconst DEFAULT_VOICE: Realtime.Voice = 'alloy';\n\nconst DEFAULT_TRANSCRIBER: Realtime.AudioTranscriptionModel = 'whisper-1';\n\nconst DEFAULT_URL = 'wss://api.openai.com/v1/realtime';\n\n/**\n * Default model for real-time voice interactions.\n * This model is optimized for low-latency responses while maintaining high quality output.\n */\nconst DEFAULT_MODEL = 'gpt-4o-mini-realtime-preview-2024-12-17';\n\n// /**\n// * Default Voice Activity Detection (VAD) configuration.\n// * These settings control how the system detects speech segments.\n// *\n// * @property {string} type - Uses server-side VAD for better accuracy\n// * @property {number} threshold - Speech detection sensitivity (0.5 = balanced)\n// * @property {number} prefix_padding_ms - Includes 1 second of audio before speech\n// * @property {number} silence_duration_ms - Waits 1 second of silence before ending turn\n// */\n// const DEFAULT_VAD_CONFIG = {\n// type: 'server_vad',\n// threshold: 0.5,\n// prefix_padding_ms: 1000,\n// silence_duration_ms: 1000,\n// } as Realtime.TurnDetection;\n\ntype TTools = ToolsInput;\n\n/**\n * Available voice options for text-to-speech.\n * Each voice has unique characteristics suitable for different use cases:\n * - alloy: Neutral and balanced\n * - echo: Warm and natural\n * - shimmer: Clear and expressive\n * - And more...\n */\nconst VOICES = ['alloy', 'ash', 'ballad', 'coral', 'echo', 'sage', 'shimmer', 'verse'];\n\ntype RealtimeClientServerEventMap = {\n [K in RealtimeServerEvents.EventType]: [RealtimeServerEvents.EventMap[K]];\n} & {\n ['conversation.item.input_audio_transcription.delta']: [{ delta: string; item_id: string; content_index: number }];\n ['conversation.item.input_audio_transcription.completed']: [\n { transcript: string; item_id: string; content_index: number; usage?: unknown },\n ];\n ['response.output_audio.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio.done']: [{ response_id: string }];\n ['response.output_audio_transcript.delta']: [{ delta: string; response_id: string }];\n ['response.output_audio_transcript.done']: [{ response_id: string }];\n ['response.output_text.delta']: [{ delta: string; response_id: string }];\n ['response.output_text.done']: [{ response_id: string }];\n};\n\n/**\n * OpenAIRealtimeVoice provides real-time voice interaction capabilities using OpenAI's\n * WebSocket-based API. It supports:\n * - Real-time text-to-speech\n * - Speech-to-text (transcription)\n * - Voice activity detection\n * - Multiple voice options\n * - Event-based audio streaming\n *\n * The class manages WebSocket connections, audio streaming, and event handling\n * for seamless voice interactions.\n *\n * @extends MastraVoice\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: process.env.OPENAI_API_KEY,\n * model: 'gpt-4o-mini-realtime'\n * });\n *\n * await voice.open();\n * voice.on('speaking', (audioData) => {\n * // Handle audio data\n * });\n *\n * await voice.speak('Hello, how can I help you today?');\n * ```\n */\nexport class OpenAIRealtimeVoice extends MastraVoice {\n private ws?: WebSocket;\n private state: 'close' | 'open';\n private client: EventEmitter<RealtimeClientServerEventMap>;\n private events: EventMap;\n private instructions?: string;\n private tools?: TTools;\n private debug: boolean;\n private queue: unknown[] = [];\n private transcriber: Realtime.AudioTranscriptionModel;\n private requestContext?: RequestContext;\n private connectionAbort?: AbortController;\n /**\n * Creates a new instance of OpenAIRealtimeVoice.\n *\n * @param options - Configuration options for the voice instance\n * @param options.url - The base URL for the OpenAI Realtime API\n * @param options.model - The model ID to use (defaults to GPT-4 Mini Realtime)\n * @param options.apiKey - OpenAI API key. Falls back to process.env.OPENAI_API_KEY\n * @param options.speaker - Voice ID to use (defaults to 'alloy')\n * @param options.debug - Enable debug mode\n *\n * @example\n * ```typescript\n * const voice = new OpenAIRealtimeVoice({\n * apiKey: 'your-api-key',\n * model: 'gpt-4o-mini-realtime',\n * speaker: 'alloy'\n * });\n * ```\n */\n constructor(\n private options: {\n model?: string;\n url?: string;\n apiKey?: string;\n speaker?: Realtime.Voice;\n transcriber?: Realtime.AudioTranscriptionModel;\n debug?: boolean;\n /** Maximum connection handshake duration in milliseconds. Defaults to 15,000. */\n connectTimeoutMs?: number;\n } = {},\n ) {\n super();\n\n if (\n options.connectTimeoutMs !== undefined &&\n (!Number.isFinite(options.connectTimeoutMs) ||\n options.connectTimeoutMs <= 0 ||\n options.connectTimeoutMs > 2_147_483_647)\n ) {\n throw new Error('connectTimeoutMs must be a positive finite number no greater than 2147483647');\n }\n\n this.client = new EventEmitter();\n this.state = 'close';\n this.events = {} as EventMap;\n this.speaker = options.speaker || DEFAULT_VOICE;\n this.transcriber = options.transcriber || DEFAULT_TRANSCRIBER;\n this.debug = options.debug || false;\n }\n\n /**\n * Returns a list of available voice speakers.\n *\n * @returns Promise resolving to an array of voice objects, each containing at least a voiceId\n *\n * @example\n * ```typescript\n * const speakers = await voice.getSpeakers();\n * // speakers = [{ voiceId: 'alloy' }, { voiceId: 'echo' }, ...]\n * ```\n */\n getSpeakers(): Promise<Array<{ voiceId: string; [key: string]: any }>> {\n return Promise.resolve(VOICES.map(v => ({ voiceId: v })));\n }\n\n /**\n * Disconnects from the OpenAI realtime session and cleans up resources.\n * Should be called when you're done with the voice instance.\n *\n * @example\n * ```typescript\n * voice.close(); // Disconnects and cleans up\n * ```\n */\n close() {\n if (!this.ws) return;\n this.ws.close();\n this.state = 'close';\n }\n\n /**\n * Equips the voice instance with a set of instructions.\n * Instructions allow the model to perform additional actions during conversations.\n *\n * @param instructions - Optional instructions to addInstructions\n * @returns Transformed instructions ready for use with the model\n *\n * @example\n * ```typescript\n * voice.addInstructions('You are a helpful assistant.');\n * ```\n */\n addInstructions(instructions?: string) {\n this.instructions = instructions;\n }\n\n /**\n * Equips the voice instance with a set of tools.\n * Tools allow the model to perform additional actions during conversations.\n *\n * @param tools - Optional tools configuration to addTools\n * @returns Transformed tools configuration ready for use with the model\n *\n * @example\n * ```typescript\n * const tools = {\n * search: async (query: string) => { ... },\n * calculate: (expression: string) => { ... }\n * };\n * voice.addTools(tools);\n * ```\n */\n addTools(tools?: TTools) {\n this.tools = tools || {};\n }\n\n /**\n * Emits a speaking event using the configured voice model.\n * Can accept either a string or a readable stream as input.\n *\n * @param input - The text to convert to speech, or a readable stream containing the text\n * @param options - Optional configuration for this specific speech request\n * @param options.speaker - Override the voice to use for this specific request\n *\n * @throws {Error} If the input text is empty\n *\n * @example\n * ```typescript\n * // Simple text to speech\n * await voice.speak('Hello world');\n *\n * // With custom voice\n * await voice.speak('Hello world', { speaker: 'echo' });\n *\n * // Using a stream\n * const stream = fs.createReadStream('text.txt');\n * await voice.speak(stream);\n * ```\n */\n async speak(input: string | NodeJS.ReadableStream, options?: { speaker?: Realtime.Voice }): Promise<void> {\n if (typeof input !== 'string') {\n const chunks: Buffer[] = [];\n for await (const chunk of input) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n input = Buffer.concat(chunks).toString('utf-8');\n }\n\n if (input.trim().length === 0) {\n throw new Error('Input text is empty');\n }\n\n this.sendEvent('response.create', {\n response: {\n instructions: `Repeat the following text: ${input}`,\n voice: options?.speaker ? options.speaker : undefined,\n },\n });\n }\n\n /**\n * Updates the session configuration for the voice instance.\n * This can be used to modify voice settings, turn detection, and other parameters.\n *\n * @param sessionConfig - New session configuration to apply\n *\n * @example\n * ```typescript\n * voice.updateConfig({\n * voice: 'echo',\n * turn_detection: {\n * type: 'server_vad',\n * threshold: 0.5,\n * silence_duration_ms: 1000\n * }\n * });\n * ```\n */\n updateConfig(sessionConfig: unknown): void {\n this.sendEvent('session.update', { session: sessionConfig });\n }\n\n /**\n * Checks if listening capabilities are enabled.\n *\n * @returns {Promise<{ enabled: boolean }>}\n */\n async getListener() {\n return { enabled: true };\n }\n\n /**\n * Processes audio input for speech recognition.\n * Takes a readable stream of audio data and emits a writing event.\n * The output of the writing event is int16 audio data.\n *\n * @param audioData - Readable stream containing the audio data to process\n * @param options - Optional configuration for audio processing\n *\n * @throws {Error} If the audio data format is not supported\n *\n * @example\n * ```typescript\n * // Process audio from a file\n * const audioStream = fs.createReadStream('audio.raw');\n * await voice.listen(audioStream);\n *\n * // Process audio with options\n * await voice.listen(microphoneStream, {\n * format: 'int16',\n * sampleRate: 24000\n * });\n * ```\n */\n async listen(audioData: NodeJS.ReadableStream): Promise<void> {\n if (isReadableStream(audioData)) {\n const chunks: Buffer[] = [];\n for await (const chunk of audioData) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n chunks.push(buffer);\n }\n\n const buffer = Buffer.concat(chunks);\n const int16Array = new Int16Array(buffer.buffer, buffer.byteOffset ?? 0, (buffer.byteLength ?? 0) / 2);\n const base64Audio = this.int16ArrayToBase64(int16Array);\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'message',\n role: 'user',\n content: [{ type: 'input_audio', audio: base64Audio }],\n },\n });\n\n this.sendEvent('response.create', {\n response: {\n modalities: ['text'],\n instructions: `ONLY repeat the input and DO NOT say anything else`,\n },\n });\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n waitForOpen(): Promise<void> {\n return this.waitForHandshake('open');\n }\n\n waitForSessionCreated(): Promise<void> {\n return this.waitForHandshake('session.created');\n }\n\n private waitForHandshake(event: 'open' | 'session.created'): Promise<void> {\n const ws = this.ws;\n const signal = this.connectionAbort?.signal;\n return new Promise((resolve, reject) => {\n if (!ws) {\n reject(new Error('WebSocket not initialized'));\n return;\n }\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n if (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {\n reject(new Error('OpenAI realtime WebSocket is closed'));\n return;\n }\n if (event === 'open' && ws.readyState === WebSocket.OPEN) {\n resolve();\n return;\n }\n\n const cleanup = () => {\n clearTimeout(timer);\n ws.removeListener('open', onReady);\n ws.removeListener('error', onError);\n ws.removeListener('close', onClose);\n this.client.removeListener('session.created', onReady);\n this.client.removeListener('error', onProtocolError);\n signal?.removeEventListener('abort', onAbort);\n };\n const onReady = () => {\n cleanup();\n resolve();\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onClose = (code: number, reason: Buffer) =>\n onError(new Error(`OpenAI realtime WebSocket closed during handshake (${code}: ${reason.toString()})`));\n const onProtocolError = (event: RealtimeServerEvents.EventMap['error']) =>\n onError(new Error(event.error.message, { cause: event.error }));\n const onAbort = () => onError(signal!.reason);\n const timeoutMs = this.options.connectTimeoutMs ?? 15_000;\n const timer = setTimeout(\n () => onError(new Error(`OpenAI realtime connection timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n\n if (event === 'open') ws.once('open', onReady);\n else this.client.once('session.created', onReady);\n ws.once('error', onError);\n ws.once('close', onClose);\n this.client.once('error', onProtocolError);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /**\n * Establishes a connection to the OpenAI realtime service.\n * Must be called before using speak, listen, or relay functions.\n *\n * @throws {Error} If connection fails or session creation times out\n *\n * @example\n * ```typescript\n * await voice.open();\n * // Now ready for voice interactions\n * ```\n */\n async connect({ requestContext }: { requestContext?: RequestContext } = {}) {\n const url = `${this.options.url || DEFAULT_URL}?model=${this.options.model || DEFAULT_MODEL}`;\n const apiKey = this.options.apiKey || process.env.OPENAI_API_KEY;\n this.requestContext = requestContext;\n\n this.ws = new WebSocket(url, undefined, {\n headers: {\n Authorization: 'Bearer ' + apiKey,\n },\n });\n\n const ws = this.ws;\n this.state = 'close';\n this.client.removeAllListeners();\n const controller = new AbortController();\n this.connectionAbort = controller;\n this.setupEventListeners();\n try {\n await Promise.all([this.waitForOpen(), this.waitForSessionCreated()]);\n } catch (error) {\n controller.abort(error);\n this.state = 'close';\n this.ws = undefined;\n ws.close();\n throw error;\n } finally {\n this.connectionAbort = undefined;\n }\n\n const openaiTools = transformTools(this.tools);\n this.updateConfig({\n type: 'realtime',\n instructions: this.instructions,\n tools: openaiTools.map(t => t.openaiTool),\n audio: {\n input: {\n transcription: {\n model: this.transcriber,\n },\n },\n output: {\n voice: this.speaker,\n },\n },\n });\n this.state = 'open';\n }\n\n disconnect() {\n this.state = 'close';\n this.connectionAbort?.abort(new Error('OpenAI realtime connection disconnected during handshake'));\n this.ws?.close();\n }\n\n /**\n * Streams audio data in real-time to the OpenAI service.\n * Useful for continuous audio streaming scenarios like live microphone input.\n * Must be in 'open' state before calling this method.\n *\n * @param audioData - Readable stream of audio data to relay\n * @throws {Error} If audio format is not supported\n *\n * @example\n * ```typescript\n * // First connect\n * await voice.open();\n *\n * // Then relay audio\n * const micStream = getMicrophoneStream();\n * await voice.relay(micStream);\n * ```\n */\n async send(audioData: NodeJS.ReadableStream | Int16Array, eventId?: string): Promise<void> {\n if (!this.state || this.state !== 'open') {\n console.warn('Cannot relay audio when not open. Call open() first.');\n return;\n }\n\n if (isReadableStream(audioData)) {\n const stream = audioData as NodeJS.ReadableStream;\n stream.on('data', chunk => {\n try {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n this.sendEvent('input_audio_buffer.append', { audio: buffer.toString('base64'), event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n });\n } else if (audioData instanceof Int16Array) {\n try {\n const base64Audio = this.int16ArrayToBase64(audioData);\n this.sendEvent('input_audio_buffer.append', { audio: base64Audio, event_id: eventId });\n } catch (err) {\n this.emit('error', err);\n }\n } else {\n this.emit('error', new Error('Unsupported audio data format'));\n }\n }\n\n /**\n * Sends a response to the OpenAI Realtime API.\n *\n * Trigger a response to the real-time session.\n *\n * @param {Object} params - The parameters object\n * @param {Realtime.ResponseConfig} params.options - Configuration options for the response\n * @returns {Promise<void>} A promise that resolves when the response has been sent\n *\n * @example\n * // Send a simple text response\n * await realtimeVoice.answer({\n * options: {\n * content: \"Hello, how can I help you today?\",\n * voice: \"alloy\"\n * }\n * });\n */\n async answer({ options }: { options?: Realtime.ResponseConfig }) {\n this.sendEvent('response.create', { response: options ?? {} });\n }\n\n /**\n * Registers an event listener for voice events.\n * Available events: 'speaking', 'writing, 'error'\n * Can listen to OpenAI Realtime events by prefixing with 'openAIRealtime:'\n * Such as 'openAIRealtime:conversation.item.completed', 'openAIRealtime:conversation.updated', etc.\n *\n * @param event - Name of the event to listen for\n * @param callback - Function to call when the event occurs\n *\n * @example\n * ```typescript\n * // Listen for speech events\n * voice.on('speaking', (audioData: Int16Array) => {\n * // Handle audio data\n * });\n *\n * // Handle errors\n * voice.on('error', (error: Error) => {\n * console.error('Voice error:', error);\n * });\n * ```\n */\n on(event: string, callback: EventCallback): void {\n if (!this.events[event]) {\n this.events[event] = [];\n }\n this.events[event].push(callback);\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param event - Name of the event to stop listening to\n * @param callback - The specific callback function to remove\n *\n * @example\n * ```typescript\n * // Create event handler\n * const handleSpeech = (audioData: Int16Array) => {\n * // Handle audio data\n * };\n *\n * // Add listener\n * voice.on('speaking', handleSpeech);\n *\n * // Later, remove the listener\n * voice.off('speaking', handleSpeech);\n * ```\n */\n off(event: string, callback: EventCallback): void {\n if (!this.events[event]) return;\n\n const index = this.events[event].indexOf(callback);\n if (index !== -1) {\n this.events[event].splice(index, 1);\n }\n }\n\n /**\n * Emit an event with arguments\n * @param event Event name\n * @param args Arguments to pass to the callbacks\n */\n private emit(event: string, ...args: any[]): void {\n if (!this.events[event]) return;\n\n for (const callback of this.events[event]) {\n callback(...args);\n }\n }\n\n private setupEventListeners(): void {\n const speakerStreams = new Map<string, StreamWithId>();\n const userTranscriptionDeltaItems = new Set<string>();\n\n if (!this.ws) {\n throw new Error('WebSocket not initialized');\n }\n\n const ws = this.ws;\n ws.on('error', error => {\n if (this.ws === ws) this.emit('error', error);\n });\n ws.on('message', message => {\n if (this.ws !== ws) return;\n const data = JSON.parse(message.toString());\n this.client.emit(data.type, data);\n\n if (this.debug) {\n const { delta, ...fields } = data;\n console.info(data.type, fields, delta?.length < 100 ? delta : '');\n }\n });\n\n this.client.on('session.created', ev => {\n this.emit('session.created', ev);\n\n const queue = this.queue.splice(0, this.queue.length);\n for (const ev of queue) {\n this.ws?.send(JSON.stringify(ev));\n }\n });\n this.client.on('session.updated', ev => {\n this.emit('session.updated', ev);\n });\n this.client.on('response.created', ev => {\n this.emit('response.created', ev);\n\n const speakerStream = new PassThrough() as StreamWithId;\n\n speakerStream.id = ev.response.id;\n\n speakerStreams.set(ev.response.id, speakerStream);\n this.emit('speaker', speakerStream);\n });\n this.client.on('conversation.item.input_audio_transcription.delta', ev => {\n userTranscriptionDeltaItems.add(ev.item_id);\n this.emit('writing', { text: ev.delta, response_id: ev.item_id, role: 'user' });\n });\n this.client.on('conversation.item.input_audio_transcription.completed', ev => {\n if (!userTranscriptionDeltaItems.has(ev.item_id) && ev.transcript) {\n this.emit('writing', { text: ev.transcript, response_id: ev.item_id, role: 'user' });\n }\n userTranscriptionDeltaItems.delete(ev.item_id);\n this.emit('writing', { text: '\\n', response_id: ev.item_id, role: 'user' });\n });\n const handleAudioDelta = (ev: { delta: string; response_id: string }) => {\n const audio = Buffer.from(ev.delta, 'base64');\n this.emit('speaking', { audio, response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.write(audio);\n };\n const handleAudioDone = (ev: { response_id: string }) => {\n this.emit('speaking.done', { response_id: ev.response_id });\n\n const stream = speakerStreams.get(ev.response_id);\n stream?.end();\n };\n const handleAudioTranscriptDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleAudioTranscriptDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDelta = (ev: { delta: string; response_id: string }) => {\n this.emit('writing', { text: ev.delta, response_id: ev.response_id, role: 'assistant' });\n };\n const handleTextDone = (ev: { response_id: string }) => {\n this.emit('writing', { text: '\\n', response_id: ev.response_id, role: 'assistant' });\n };\n this.client.on('response.audio.delta', handleAudioDelta);\n this.client.on('response.output_audio.delta', handleAudioDelta);\n this.client.on('response.audio.done', handleAudioDone);\n this.client.on('response.output_audio.done', handleAudioDone);\n this.client.on('response.audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.output_audio_transcript.delta', handleAudioTranscriptDelta);\n this.client.on('response.audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.output_audio_transcript.done', handleAudioTranscriptDone);\n this.client.on('response.text.delta', handleTextDelta);\n this.client.on('response.output_text.delta', handleTextDelta);\n this.client.on('response.text.done', handleTextDone);\n this.client.on('response.output_text.done', handleTextDone);\n this.client.on('response.done', async ev => {\n await this.handleFunctionCalls(ev);\n this.emit('response.done', ev);\n speakerStreams.delete(ev.response.id);\n });\n this.client.on('error', async ev => {\n this.emit('error', ev);\n });\n }\n\n private async handleFunctionCalls(ev: any) {\n let handledFunctionCall = false;\n for (const output of ev.response?.output ?? []) {\n if (output.type === 'function_call') {\n handledFunctionCall = true;\n await this.handleFunctionCall(output);\n }\n }\n if (handledFunctionCall) {\n this.sendEvent('response.create', {});\n }\n }\n\n private async handleFunctionCall(output: any) {\n try {\n const context = JSON.parse(output.arguments);\n const tool = this.tools?.[output.name];\n if (!tool) {\n console.warn(`Tool \"${output.name}\" not found`);\n return;\n }\n\n if (tool?.execute) {\n this.emit('tool-call-start', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n });\n }\n\n const result = await tool?.execute?.(context, {\n toolCallId: output.call_id,\n messages: [],\n requestContext: this.requestContext,\n });\n\n this.emit('tool-call-result', {\n toolCallId: output.call_id,\n toolName: output.name,\n toolDescription: tool.description,\n args: context,\n result,\n });\n\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify(result),\n },\n });\n } catch (e) {\n const err = e as Error;\n console.warn(`Error calling tool \"${output.name}\":`, err.message);\n this.sendEvent('conversation.item.create', {\n item: {\n type: 'function_call_output',\n call_id: output.call_id,\n output: JSON.stringify({ error: err.message }),\n },\n });\n }\n }\n\n private int16ArrayToBase64(int16Array: Int16Array): string {\n const buffer = new ArrayBuffer(int16Array.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < int16Array.length; i++) {\n view.setInt16(i * 2, int16Array[i]!, true);\n }\n const uint8Array = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]!);\n }\n return btoa(binary);\n }\n\n private sendEvent(type: string, data: any) {\n if (!this.ws || this.ws.readyState !== this.ws.OPEN) {\n this.queue.push({ type: type, ...data });\n } else {\n this.ws?.send(\n JSON.stringify({\n type: type,\n ...data,\n }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAS,uBAAuB,KAAK,OAAO,UAAU;CACrD,IAAI,CAAC,KAAK,QAAQ,QAAQ;CAC1B,IAAI;EACH,MAAM,cAAc;EACpB,IAAI,WAAW,CAAC,EAAE,MAAM,MAAM,SAAS;GACtC,GAAG,YAAY,OAAO,KAAK,IAAI,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;GAC9D,GAAG,YAAY,WAAW,KAAK,IAAI,EAAE,QAAQ,YAAY,OAAO,IAAI,CAAC;GACrE,GAAG,YAAY,aAAa,KAAK,IAAI,EAAE,UAAU,YAAY,SAAS,IAAI,CAAC;GAC3E,GAAG,YAAY,YAAY,KAAK,IAAI,EAAE,SAAS,YAAY,QAAQ,IAAI,CAAC;GACxE,GAAG,MAAM,iBAAiB,QAAQ,EAAE,OAAO,MAAM,MAAM,QAAQ,IAAI,CAAC;G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MAAM,KAAK,GAAG,eAAe,KAAK,GAAG,MAC7C,KAAK,MAAM,KAAK;GAAQ;GAAM,GAAG;EAAK,CAAC;OAEvC,KAAK,IAAI,KACP,KAAK,UAAU;GACP;GACN,GAAG;EACL,CAAC,CACH;CAEJ;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/voice-openai-realtime",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.9-alpha.1",
|
|
4
4
|
"description": "Mastra OpenAI Realtime API integration",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"openai-realtime-api": "^1.0.8",
|
|
27
27
|
"ws": "^8.21.0",
|
|
28
|
-
"@mastra/schema-compat": "1.3.
|
|
28
|
+
"@mastra/schema-compat": "1.3.9-alpha.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "22.20.1",
|
|
@@ -38,9 +38,9 @@
|
|
|
38
38
|
"typescript": "^7.0.2",
|
|
39
39
|
"vitest": "4.1.10",
|
|
40
40
|
"zod": "^4.4.3",
|
|
41
|
-
"@internal/
|
|
41
|
+
"@internal/lint": "0.0.130",
|
|
42
42
|
"@internal/types-builder": "0.0.105",
|
|
43
|
-
"@internal/
|
|
43
|
+
"@internal/voice": "0.0.28"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"zod": "^3.25.0 || ^4.0.0"
|