@mastra/livekit 0.0.0 → 0.2.0-alpha.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +270 -7
  4. package/dist/bridge.d.ts +153 -0
  5. package/dist/bridge.d.ts.map +1 -0
  6. package/dist/chunk-2E3MTAOA.js +133 -0
  7. package/dist/chunk-2E3MTAOA.js.map +1 -0
  8. package/dist/chunk-MWTEZOBS.cjs +139 -0
  9. package/dist/chunk-MWTEZOBS.cjs.map +1 -0
  10. package/dist/constants.d.ts +3 -0
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/dispatch.d.ts +20 -0
  13. package/dist/dispatch.d.ts.map +1 -0
  14. package/dist/index.cjs +105 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.ts +10 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +91 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/messages.d.ts +24 -0
  21. package/dist/messages.d.ts.map +1 -0
  22. package/dist/metadata.d.ts +17 -0
  23. package/dist/metadata.d.ts.map +1 -0
  24. package/dist/observability.d.ts +46 -0
  25. package/dist/observability.d.ts.map +1 -0
  26. package/dist/routes.d.ts +52 -0
  27. package/dist/routes.d.ts.map +1 -0
  28. package/dist/run.d.ts +32 -0
  29. package/dist/run.d.ts.map +1 -0
  30. package/dist/voice-thread.d.ts +23 -0
  31. package/dist/voice-thread.d.ts.map +1 -0
  32. package/dist/worker-entry.cjs +656 -0
  33. package/dist/worker-entry.cjs.map +1 -0
  34. package/dist/worker-entry.d.ts +8 -0
  35. package/dist/worker-entry.d.ts.map +1 -0
  36. package/dist/worker-entry.js +652 -0
  37. package/dist/worker-entry.js.map +1 -0
  38. package/dist/worker-setup.d.ts +5 -0
  39. package/dist/worker-setup.d.ts.map +1 -0
  40. package/dist/worker.d.ts +187 -0
  41. package/dist/worker.d.ts.map +1 -0
  42. package/dist/workflow-generator.d.ts +92 -0
  43. package/dist/workflow-generator.d.ts.map +1 -0
  44. package/package.json +24 -14
@@ -0,0 +1,652 @@
1
+ import { parseSessionMetadata, createWorkflowReplyGenerator, DEFAULT_LIVEKIT_AGENT_NAME } from './chunk-2E3MTAOA.js';
2
+ import { InferenceRunner, defineAgent, voice, cli, ServerOptions, metrics, llm } from '@livekit/agents';
3
+ import { RequestContext } from '@mastra/core/request-context';
4
+ import { ReadableStream } from 'stream/web';
5
+ import { getOrCreateSpan, SpanType } from '@mastra/core/observability';
6
+ import { randomUUID } from 'crypto';
7
+ import { fileURLToPath } from 'url';
8
+
9
+ // src/messages.ts
10
+ function textOfMessage(message) {
11
+ const parts = [];
12
+ for (const part of message.content) {
13
+ if (typeof part === "string") {
14
+ parts.push(part);
15
+ } else if (part.type === "instructions") {
16
+ parts.push(part.value);
17
+ } else if (part.type === "audio_content" && part.transcript) {
18
+ parts.push(part.transcript);
19
+ }
20
+ }
21
+ return parts.join("\n").trim();
22
+ }
23
+ function toVoiceTurnMessage(item) {
24
+ if (item.type !== "message") return void 0;
25
+ const content = textOfMessage(item);
26
+ if (!content) return void 0;
27
+ if (item.role === "user") return { role: "user", content };
28
+ if (item.role === "assistant") return { role: "assistant", content };
29
+ return { role: "system", content };
30
+ }
31
+ function extractNewTurnMessages(chatCtx) {
32
+ const items = chatCtx.items;
33
+ let lastAssistantIdx = -1;
34
+ for (let i = items.length - 1; i >= 0; i--) {
35
+ const item = items[i];
36
+ if (item?.type === "message" && item.role === "assistant") {
37
+ lastAssistantIdx = i;
38
+ break;
39
+ }
40
+ }
41
+ const messages = [];
42
+ for (const item of items.slice(lastAssistantIdx + 1)) {
43
+ const message = toVoiceTurnMessage(item);
44
+ if (message) messages.push(message);
45
+ }
46
+ return messages;
47
+ }
48
+ function chatContextToMessages(chatCtx) {
49
+ const withoutInstructions = chatCtx.copy({ excludeInstructions: true, excludeFunctionCall: true });
50
+ const messages = [];
51
+ for (const item of withoutInstructions.items) {
52
+ const message = toVoiceTurnMessage(item);
53
+ if (message) messages.push(message);
54
+ }
55
+ return messages;
56
+ }
57
+
58
+ // src/bridge.ts
59
+ var DEFAULT_INSTRUCTIONS = "You are a helpful voice assistant powered by a Mastra agent.";
60
+ function createAgentReplyGenerator(options) {
61
+ const { agent, streamOptions, toolFeedback, onTurnComplete } = options;
62
+ return (ctx) => {
63
+ if (ctx.messages.length === 0) return null;
64
+ const abortController = new AbortController();
65
+ const mergedOptions = {
66
+ ...streamOptions,
67
+ abortSignal: abortController.signal
68
+ };
69
+ if (ctx.memory) mergedOptions.memory = ctx.memory;
70
+ if (ctx.requestContext) mergedOptions.requestContext = ctx.requestContext;
71
+ let cancelled = false;
72
+ let replyText = "";
73
+ const toolCalls = [];
74
+ const emitTurnComplete = (interrupted) => {
75
+ if (!onTurnComplete) return;
76
+ const completeCtx = { ...ctx, result: { text: replyText, toolCalls, interrupted } };
77
+ Promise.resolve().then(() => onTurnComplete(completeCtx)).catch((error) => {
78
+ console.warn("@mastra/livekit: onTurnComplete hook threw", error);
79
+ });
80
+ };
81
+ return new ReadableStream({
82
+ start: async (controller) => {
83
+ try {
84
+ const result = await agent.stream(ctx.messages, mergedOptions);
85
+ for await (const chunk of result.fullStream) {
86
+ if (cancelled) break;
87
+ if (chunk.type === "text-delta") {
88
+ if (chunk.payload.text) {
89
+ replyText += chunk.payload.text;
90
+ controller.enqueue(chunk.payload.text);
91
+ }
92
+ } else if (chunk.type === "tool-call") {
93
+ const toolCall = {
94
+ toolCallId: chunk.payload.toolCallId,
95
+ toolName: chunk.payload.toolName,
96
+ args: chunk.payload.args
97
+ };
98
+ toolCalls.push(toolCall);
99
+ if (toolFeedback) {
100
+ const filler = toolFeedback(toolCall);
101
+ if (filler) controller.enqueue(filler.endsWith(" ") ? filler : `${filler} `);
102
+ }
103
+ } else if (chunk.type === "error") {
104
+ const error = chunk.payload.error;
105
+ throw error instanceof Error ? error : new Error(String(error));
106
+ }
107
+ }
108
+ if (!cancelled) controller.close();
109
+ emitTurnComplete(cancelled);
110
+ } catch (error) {
111
+ if (cancelled || abortController.signal.aborted) {
112
+ emitTurnComplete(true);
113
+ return;
114
+ }
115
+ controller.error(error);
116
+ }
117
+ },
118
+ cancel: () => {
119
+ cancelled = true;
120
+ abortController.abort();
121
+ }
122
+ });
123
+ };
124
+ }
125
+ function toRequestContext(value) {
126
+ if (!value) return void 0;
127
+ if (value instanceof RequestContext) return value;
128
+ return new RequestContext(Object.entries(value));
129
+ }
130
+ var MastraPlaceholderLLM = class extends llm.LLM {
131
+ label() {
132
+ return "mastra.MastraVoiceAgent";
133
+ }
134
+ get model() {
135
+ return "mastra-agent";
136
+ }
137
+ get provider() {
138
+ return "mastra";
139
+ }
140
+ chat() {
141
+ throw new Error(
142
+ "@mastra/livekit: reply generation runs through the Mastra agent via llmNode; the placeholder LLM cannot be used for inference."
143
+ );
144
+ }
145
+ };
146
+ var MastraVoiceAgent = class extends voice.Agent {
147
+ mastraAgent;
148
+ memory;
149
+ requestContext;
150
+ streamOptions;
151
+ replyGenerator;
152
+ constructor(options) {
153
+ if (options.agent && options.generate) {
154
+ throw new Error(
155
+ "@mastra/livekit: MastraVoiceAgent requires `agent` or `generate`, not both \u2014 they are mutually exclusive reply sources."
156
+ );
157
+ }
158
+ super({
159
+ id: options.id,
160
+ instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,
161
+ stt: options.stt,
162
+ vad: options.vad,
163
+ llm: new MastraPlaceholderLLM(),
164
+ tts: options.tts,
165
+ turnHandling: options.turnHandling
166
+ });
167
+ this.memory = options.memory ?? false;
168
+ this.requestContext = toRequestContext(options.requestContext);
169
+ this.streamOptions = options.streamOptions;
170
+ if (options.generate) {
171
+ this.replyGenerator = options.generate;
172
+ } else if (options.agent) {
173
+ this.mastraAgent = options.agent;
174
+ this.replyGenerator = createAgentReplyGenerator({
175
+ agent: options.agent,
176
+ streamOptions: options.streamOptions,
177
+ toolFeedback: options.toolFeedback,
178
+ onTurnComplete: options.onTurnComplete
179
+ });
180
+ } else {
181
+ throw new Error("@mastra/livekit: MastraVoiceAgent requires `agent` or `generate`.");
182
+ }
183
+ }
184
+ async llmNode(chatCtx, _toolCtx, _modelSettings) {
185
+ const messages = this.memory === false ? chatContextToMessages(chatCtx) : extractNewTurnMessages(chatCtx);
186
+ if (messages.length === 0) return null;
187
+ return this.replyGenerator({
188
+ messages,
189
+ chatCtx,
190
+ memory: this.memory,
191
+ requestContext: this.requestContext,
192
+ tracingContext: this.streamOptions?.tracingContext
193
+ });
194
+ }
195
+ };
196
+ function createMastraVoiceAgent(options) {
197
+ return new MastraVoiceAgent(options);
198
+ }
199
+ function modelMeta(metadata) {
200
+ const out = {};
201
+ if (metadata?.modelProvider) out.modelProvider = metadata.modelProvider;
202
+ if (metadata?.modelName) out.modelName = metadata.modelName;
203
+ return out;
204
+ }
205
+ var ms = (n) => `${Math.round(n)}ms`;
206
+ var secs = (n) => `${(n / 1e3).toFixed(1)}s`;
207
+ function describeMetric(metric) {
208
+ switch (metric.type) {
209
+ case "eou_metrics":
210
+ return {
211
+ name: `eou ${ms(metric.endOfUtteranceDelayMs)}`,
212
+ data: {
213
+ endOfUtteranceDelayMs: metric.endOfUtteranceDelayMs,
214
+ transcriptionDelayMs: metric.transcriptionDelayMs,
215
+ onUserTurnCompletedDelayMs: metric.onUserTurnCompletedDelayMs
216
+ }
217
+ };
218
+ case "stt_metrics":
219
+ return {
220
+ name: `stt ${secs(metric.audioDurationMs)}`,
221
+ data: {
222
+ audioDurationMs: metric.audioDurationMs,
223
+ durationMs: metric.durationMs,
224
+ streamed: metric.streamed,
225
+ ...modelMeta(metric.metadata)
226
+ }
227
+ };
228
+ case "llm_metrics":
229
+ return {
230
+ name: `llm ttft ${ms(metric.ttftMs)}`,
231
+ data: {
232
+ ttftMs: metric.ttftMs,
233
+ durationMs: metric.durationMs,
234
+ tokensPerSecond: metric.tokensPerSecond,
235
+ promptTokens: metric.promptTokens,
236
+ completionTokens: metric.completionTokens,
237
+ totalTokens: metric.totalTokens,
238
+ cancelled: metric.cancelled,
239
+ ...modelMeta(metric.metadata)
240
+ }
241
+ };
242
+ case "tts_metrics":
243
+ return {
244
+ name: `tts ttfb ${ms(metric.ttfbMs)}`,
245
+ data: {
246
+ ttfbMs: metric.ttfbMs,
247
+ durationMs: metric.durationMs,
248
+ audioDurationMs: metric.audioDurationMs,
249
+ charactersCount: metric.charactersCount,
250
+ cancelled: metric.cancelled,
251
+ streamed: metric.streamed,
252
+ ...modelMeta(metric.metadata)
253
+ }
254
+ };
255
+ case "vad_metrics":
256
+ return {
257
+ name: "vad",
258
+ data: {
259
+ idleTimeMs: metric.idleTimeMs,
260
+ inferenceCount: metric.inferenceCount,
261
+ inferenceDurationTotalMs: metric.inferenceDurationTotalMs
262
+ }
263
+ };
264
+ case "realtime_model_metrics":
265
+ return {
266
+ name: `realtime ttft ${ms(metric.ttftMs)}`,
267
+ data: {
268
+ ttftMs: metric.ttftMs,
269
+ durationMs: metric.durationMs,
270
+ tokensPerSecond: metric.tokensPerSecond,
271
+ promptTokens: metric.inputTokens,
272
+ completionTokens: metric.outputTokens,
273
+ totalTokens: metric.totalTokens,
274
+ ...modelMeta(metric.metadata)
275
+ }
276
+ };
277
+ default:
278
+ return void 0;
279
+ }
280
+ }
281
+ function startVoiceCallObservability(options) {
282
+ const span = getOrCreateSpan({
283
+ mastra: options.mastra,
284
+ type: SpanType.GENERIC,
285
+ name: "voice call",
286
+ requestContext: options.requestContext,
287
+ metadata: {
288
+ agentId: options.agentId,
289
+ roomName: options.roomName,
290
+ ...options.metadata.threadId ? { threadId: options.metadata.threadId } : {},
291
+ ...options.metadata.resourceId ? { resourceId: options.metadata.resourceId } : {}
292
+ }
293
+ });
294
+ if (!span) return void 0;
295
+ const usage = new metrics.ModelUsageCollector();
296
+ let finalized = false;
297
+ const finalize = (opts) => {
298
+ if (finalized) return;
299
+ finalized = true;
300
+ const summary = usage.flatten();
301
+ if (opts?.error) {
302
+ span.error({
303
+ error: opts.error instanceof Error ? opts.error : new Error(String(opts.error)),
304
+ metadata: { usage: summary }
305
+ });
306
+ } else {
307
+ span.end({ output: { usage: summary } });
308
+ }
309
+ };
310
+ return {
311
+ span,
312
+ tracingContext: { currentSpan: span },
313
+ attach(session) {
314
+ session.on(voice.AgentSessionEventTypes.MetricsCollected, (event) => {
315
+ usage.collect(event.metrics);
316
+ const described = describeMetric(event.metrics);
317
+ if (!described) return;
318
+ span.createEventSpan({ type: SpanType.GENERIC, name: described.name, output: described.data });
319
+ });
320
+ session.on(voice.AgentSessionEventTypes.Close, (event) => {
321
+ finalize({ error: event?.error ?? void 0 });
322
+ });
323
+ },
324
+ finalize
325
+ };
326
+ }
327
+ async function ensureVoiceCallThread({
328
+ memory,
329
+ threadId,
330
+ resourceId,
331
+ roomName
332
+ }) {
333
+ const existing = await memory.getThreadById({ threadId });
334
+ if (existing) return;
335
+ await memory.createThread({
336
+ threadId,
337
+ resourceId,
338
+ title: "Voice call",
339
+ metadata: { source: "livekit", roomName }
340
+ });
341
+ }
342
+ async function persistSpokenGreeting({
343
+ memory,
344
+ threadId,
345
+ resourceId,
346
+ greeting
347
+ }) {
348
+ if (!greeting.trim()) return;
349
+ const message = {
350
+ id: randomUUID(),
351
+ role: "assistant",
352
+ type: "text",
353
+ createdAt: /* @__PURE__ */ new Date(),
354
+ threadId,
355
+ resourceId,
356
+ content: {
357
+ format: 2,
358
+ parts: [{ type: "text", text: greeting }],
359
+ metadata: { source: "voice", kind: "greeting" }
360
+ }
361
+ };
362
+ await memory.saveMessages({ messages: [message] });
363
+ }
364
+
365
+ // src/worker-setup.ts
366
+ var pendingSetup = [];
367
+ var requestedEouMethods = /* @__PURE__ */ new Set();
368
+ function queueWorkerSetup(setup) {
369
+ pendingSetup.push(setup);
370
+ }
371
+ function workerSetupComplete() {
372
+ return Promise.allSettled(pendingSetup);
373
+ }
374
+ function requestEouMethod(method) {
375
+ requestedEouMethods.add(method);
376
+ }
377
+ function isEouMethodRequested(method) {
378
+ return requestedEouMethods.has(method);
379
+ }
380
+
381
+ // src/worker.ts
382
+ var EOU_METHODS = {
383
+ english: "lk_end_of_utterance_en",
384
+ multilingual: "lk_end_of_utterance_multilingual"
385
+ };
386
+ async function loadSileroVad() {
387
+ let silero;
388
+ try {
389
+ silero = await import('@livekit/agents-plugin-silero');
390
+ } catch (error) {
391
+ throw new Error(
392
+ "@mastra/livekit: voice activity detection requires '@livekit/agents-plugin-silero'. Install it, pass your own `vad` instance, or set `vad: false`.",
393
+ { cause: error }
394
+ );
395
+ }
396
+ return silero.VAD.load();
397
+ }
398
+ async function loadTurnDetector(kind) {
399
+ let plugin;
400
+ try {
401
+ plugin = await import('@livekit/agents-plugin-livekit');
402
+ } catch (error) {
403
+ throw new Error(
404
+ `@mastra/livekit: turnDetection '${kind}' requires '@livekit/agents-plugin-livekit'. Install it or use a built-in mode like 'vad' or 'stt'.`,
405
+ { cause: error }
406
+ );
407
+ }
408
+ return kind === "english" ? new plugin.turnDetector.EnglishModel() : new plugin.turnDetector.MultilingualModel();
409
+ }
410
+ async function resolveMastraAgent(options, args) {
411
+ let ref = typeof options.agent === "function" ? await options.agent(args) : options.agent;
412
+ ref ??= args.metadata.agentId;
413
+ if (!ref) {
414
+ throw new Error(
415
+ "@mastra/livekit: no Mastra agent specified. Set `agent` on createLiveKitWorker or pass `agentId` in the dispatch metadata (e.g. via liveKitConnectionRoute)."
416
+ );
417
+ }
418
+ if (typeof ref !== "string") return ref;
419
+ try {
420
+ return options.mastra.getAgentById(ref);
421
+ } catch {
422
+ return options.mastra.getAgent(ref);
423
+ }
424
+ }
425
+ async function resolveWorkflow(options, args) {
426
+ const resolver = options.workflow;
427
+ const ref = typeof resolver === "function" ? await resolver(args) : resolver ?? "";
428
+ if (!ref) {
429
+ throw new Error("@mastra/livekit: no workflow specified. Set `workflow` on createLiveKitWorker.");
430
+ }
431
+ if (typeof ref !== "string") return { workflow: ref };
432
+ return { workflow: options.mastra.getWorkflowById(ref) };
433
+ }
434
+ function resolveMemory(options, mastraAgent, args, roomName) {
435
+ if (options.memory === false) return false;
436
+ if (typeof options.memory === "function") return options.memory({ ...args, roomName });
437
+ if (mastraAgent && !mastraAgent.hasOwnMemory()) return false;
438
+ const thread = args.metadata.threadId ?? roomName;
439
+ return { thread, resource: args.metadata.resourceId ?? thread };
440
+ }
441
+ async function resolveMemoryInstance(options, mastraAgent, args, requestContext) {
442
+ if (mastraAgent) return await mastraAgent.getMemory({ requestContext }) ?? null;
443
+ const resolver = options.memoryInstance;
444
+ if (!resolver) return null;
445
+ const instance = typeof resolver === "function" ? await resolver(args) : resolver;
446
+ if (!instance) return null;
447
+ instance.__registerMastra(options.mastra);
448
+ if (!instance.hasOwnStorage) {
449
+ const storage = options.mastra.getStorage();
450
+ if (storage) instance.setStorage(storage);
451
+ }
452
+ return instance;
453
+ }
454
+ function buildTurnHandling(options, turnDetection) {
455
+ return {
456
+ ...turnDetection ? { turnDetection } : {},
457
+ // Preemptive generation re-runs the Mastra agent on interim transcripts (up to 3
458
+ // times per turn), and every run persists the user message to the memory thread —
459
+ // duplicating and even saving partial transcripts. Off by default; opt back in via
460
+ // `turnHandling.preemptiveGeneration` if the latency win matters more than exact
461
+ // thread history.
462
+ preemptiveGeneration: { enabled: false },
463
+ ...options.turnHandling
464
+ };
465
+ }
466
+ async function resolveInstructions(mastraAgent, requestContext) {
467
+ try {
468
+ const instructions = await mastraAgent.getInstructions({ requestContext });
469
+ return typeof instructions === "string" ? instructions : void 0;
470
+ } catch {
471
+ return void 0;
472
+ }
473
+ }
474
+ function createLiveKitWorker(options) {
475
+ if (options.generate && (options.agent || options.workflow)) {
476
+ throw new Error(
477
+ "@mastra/livekit: set exactly one reply generator \u2014 `generate`, `agent`, or `workflow` \u2014 not a combination."
478
+ );
479
+ }
480
+ if (options.agent && options.workflow) {
481
+ throw new Error(
482
+ "@mastra/livekit: set `agent` or `workflow`, not both \u2014 they are mutually exclusive reply generators."
483
+ );
484
+ }
485
+ if (options.workflow && !options.workflowInput) {
486
+ throw new Error(
487
+ "@mastra/livekit: `workflowInput` is required when `workflow` is set. Map the turn into the workflow inputData, e.g. workflowInput: ({ chatCtx }) => ({ history: chatContextToMessages(chatCtx) })."
488
+ );
489
+ }
490
+ const wantsSileroVad = options.vad === void 0 || options.vad === "silero";
491
+ if (options.turnDetection === "multilingual" || options.turnDetection === "english") {
492
+ requestEouMethod(EOU_METHODS[options.turnDetection]);
493
+ queueWorkerSetup(
494
+ import('@livekit/agents-plugin-livekit').then(() => {
495
+ for (const method of Object.values(EOU_METHODS)) {
496
+ if (!isEouMethodRequested(method)) {
497
+ delete InferenceRunner.registeredRunners[method];
498
+ }
499
+ }
500
+ }).catch(() => {
501
+ })
502
+ );
503
+ }
504
+ return defineAgent({
505
+ prewarm: async (proc) => {
506
+ if (wantsSileroVad) {
507
+ proc.userData.vad = await loadSileroVad();
508
+ }
509
+ },
510
+ entry: async (ctx) => {
511
+ const logger = options.mastra.getLogger();
512
+ const metadata = parseSessionMetadata(ctx.job.metadata);
513
+ const args = { metadata, ctx };
514
+ const requestContext = metadata.requestContext ? new RequestContext(Object.entries(metadata.requestContext)) : void 0;
515
+ let mastraAgent;
516
+ let replyGenerator;
517
+ let agentLabel;
518
+ if (options.generate) {
519
+ replyGenerator = options.generate;
520
+ agentLabel = "mastra-voice";
521
+ } else if (options.workflow) {
522
+ const { workflow } = await resolveWorkflow(options, args);
523
+ agentLabel = workflow.id;
524
+ const mapInput = options.workflowInput;
525
+ replyGenerator = createWorkflowReplyGenerator({
526
+ workflow,
527
+ workflowInput: (turnCtx) => mapInput({ ...turnCtx, metadata }),
528
+ replyStep: options.replyStep,
529
+ resultText: options.resultText,
530
+ toolFeedback: options.toolFeedback,
531
+ onTurnComplete: options.onTurnComplete
532
+ });
533
+ } else {
534
+ mastraAgent = await resolveMastraAgent(options, args);
535
+ agentLabel = mastraAgent.id ?? mastraAgent.name;
536
+ }
537
+ await ctx.connect();
538
+ const roomName = ctx.room.name ?? "mastra-voice";
539
+ let vad;
540
+ if (options.vad && options.vad !== "silero") {
541
+ vad = options.vad;
542
+ } else if (wantsSileroVad) {
543
+ vad = ctx.proc.userData.vad ?? await loadSileroVad();
544
+ }
545
+ let turnDetection;
546
+ if (options.turnDetection === "multilingual" || options.turnDetection === "english") {
547
+ turnDetection = await loadTurnDetector(options.turnDetection);
548
+ } else {
549
+ turnDetection = options.turnDetection;
550
+ }
551
+ const memory = resolveMemory(options, mastraAgent, args, roomName);
552
+ const memoryInstance = memory ? await resolveMemoryInstance(options, mastraAgent, args, requestContext) : null;
553
+ if (memory && memoryInstance) {
554
+ try {
555
+ await ensureVoiceCallThread({
556
+ memory: memoryInstance,
557
+ threadId: memory.thread,
558
+ resourceId: memory.resource ?? memory.thread,
559
+ roomName
560
+ });
561
+ } catch (error) {
562
+ logger.warn("@mastra/livekit: failed to create the voice call thread", error);
563
+ }
564
+ }
565
+ const voiceObs = options.observability === false ? void 0 : startVoiceCallObservability({
566
+ mastra: options.mastra,
567
+ agentId: agentLabel,
568
+ roomName,
569
+ metadata,
570
+ requestContext
571
+ });
572
+ if (voiceObs) {
573
+ ctx.addShutdownCallback(async () => {
574
+ voiceObs.finalize();
575
+ });
576
+ }
577
+ if (options.onCallEnd) {
578
+ const onCallEnd = options.onCallEnd;
579
+ ctx.addShutdownCallback(async () => {
580
+ try {
581
+ await onCallEnd({ memory, memoryInstance, metadata, requestContext, roomName, ctx });
582
+ } catch (error) {
583
+ logger.warn("@mastra/livekit: onCallEnd hook threw", error);
584
+ }
585
+ });
586
+ }
587
+ const agent = createMastraVoiceAgent({
588
+ ...replyGenerator ? { generate: replyGenerator } : { agent: mastraAgent },
589
+ instructions: mastraAgent ? await resolveInstructions(mastraAgent, requestContext) : void 0,
590
+ memory,
591
+ requestContext,
592
+ toolFeedback: options.toolFeedback,
593
+ onTurnComplete: options.onTurnComplete,
594
+ streamOptions: voiceObs ? { tracingContext: voiceObs.tracingContext } : void 0
595
+ });
596
+ const session = new voice.AgentSession({
597
+ stt: options.stt,
598
+ tts: options.tts,
599
+ vad,
600
+ turnHandling: buildTurnHandling(options, turnDetection),
601
+ ...options.sessionOptions
602
+ });
603
+ voiceObs?.attach(session);
604
+ try {
605
+ await session.start({
606
+ agent,
607
+ room: ctx.room,
608
+ inputOptions: options.inputOptions,
609
+ outputOptions: options.outputOptions
610
+ });
611
+ if (options.greeting) {
612
+ session.say(options.greeting);
613
+ if (options.persistGreeting !== false && memory && memoryInstance) {
614
+ try {
615
+ await persistSpokenGreeting({
616
+ memory: memoryInstance,
617
+ threadId: memory.thread,
618
+ resourceId: memory.resource ?? memory.thread,
619
+ greeting: options.greeting
620
+ });
621
+ } catch (error) {
622
+ logger.warn("@mastra/livekit: failed to persist the greeting", error);
623
+ }
624
+ }
625
+ }
626
+ await options.onSessionStart?.({ session, ctx, agent, metadata });
627
+ } catch (error) {
628
+ voiceObs?.finalize({ error });
629
+ throw error;
630
+ }
631
+ }
632
+ });
633
+ }
634
+ function resolveWorkerEntryPath(entry) {
635
+ if (entry instanceof URL) return fileURLToPath(entry);
636
+ return entry.startsWith("file:") ? fileURLToPath(entry) : entry;
637
+ }
638
+ function runLiveKitWorker(options) {
639
+ void workerSetupComplete().then(() => {
640
+ cli.runApp(
641
+ new ServerOptions({
642
+ agent: resolveWorkerEntryPath(options.entry),
643
+ agentName: options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME,
644
+ ...options.serverOptions
645
+ })
646
+ );
647
+ });
648
+ }
649
+
650
+ export { chatContextToMessages, createLiveKitWorker, runLiveKitWorker };
651
+ //# sourceMappingURL=worker-entry.js.map
652
+ //# sourceMappingURL=worker-entry.js.map