@mastra/livekit 0.0.0-aggregate-trace-20261015182851

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 (83) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +48 -0
  3. package/dist/bridge.d.ts +256 -0
  4. package/dist/bridge.d.ts.map +1 -0
  5. package/dist/client-entry.cjs +17 -0
  6. package/dist/client-entry.cjs.map +1 -0
  7. package/dist/client-entry.d.ts +8 -0
  8. package/dist/client-entry.d.ts.map +1 -0
  9. package/dist/client-entry.js +16 -0
  10. package/dist/client-entry.js.map +1 -0
  11. package/dist/consent.d.ts +55 -0
  12. package/dist/consent.d.ts.map +1 -0
  13. package/dist/constants.d.ts +3 -0
  14. package/dist/constants.d.ts.map +1 -0
  15. package/dist/dispatch.d.ts +26 -0
  16. package/dist/dispatch.d.ts.map +1 -0
  17. package/dist/end-call.d.ts +50 -0
  18. package/dist/end-call.d.ts.map +1 -0
  19. package/dist/index.cjs +290 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +281 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/llm-plugin.d.ts +117 -0
  26. package/dist/llm-plugin.d.ts.map +1 -0
  27. package/dist/messages.d.ts +50 -0
  28. package/dist/messages.d.ts.map +1 -0
  29. package/dist/metadata.d.ts +17 -0
  30. package/dist/metadata.d.ts.map +1 -0
  31. package/dist/observability.d.ts +49 -0
  32. package/dist/observability.d.ts.map +1 -0
  33. package/dist/plugin-entry.cjs +222 -0
  34. package/dist/plugin-entry.cjs.map +1 -0
  35. package/dist/plugin-entry.d.ts +10 -0
  36. package/dist/plugin-entry.d.ts.map +1 -0
  37. package/dist/plugin-entry.js +217 -0
  38. package/dist/plugin-entry.js.map +1 -0
  39. package/dist/recording-route.d.ts +31 -0
  40. package/dist/recording-route.d.ts.map +1 -0
  41. package/dist/recording-types.d.ts +11 -0
  42. package/dist/recording-types.d.ts.map +1 -0
  43. package/dist/recording.d.ts +21 -0
  44. package/dist/recording.d.ts.map +1 -0
  45. package/dist/remote-CIMCGicy.js +822 -0
  46. package/dist/remote-CIMCGicy.js.map +1 -0
  47. package/dist/remote-GSOxa--f.cjs +875 -0
  48. package/dist/remote-GSOxa--f.cjs.map +1 -0
  49. package/dist/remote.d.ts +68 -0
  50. package/dist/remote.d.ts.map +1 -0
  51. package/dist/routes.d.ts +66 -0
  52. package/dist/routes.d.ts.map +1 -0
  53. package/dist/run.d.ts +32 -0
  54. package/dist/run.d.ts.map +1 -0
  55. package/dist/speech.d.ts +19 -0
  56. package/dist/speech.d.ts.map +1 -0
  57. package/dist/turn-metrics-CqqzdLDe.js +53 -0
  58. package/dist/turn-metrics-CqqzdLDe.js.map +1 -0
  59. package/dist/turn-metrics-CtVHHdJj.cjs +82 -0
  60. package/dist/turn-metrics-CtVHHdJj.cjs.map +1 -0
  61. package/dist/turn-metrics.d.ts +69 -0
  62. package/dist/turn-metrics.d.ts.map +1 -0
  63. package/dist/voice-stream.d.ts +3 -0
  64. package/dist/voice-stream.d.ts.map +1 -0
  65. package/dist/voice-thread.d.ts +23 -0
  66. package/dist/voice-thread.d.ts.map +1 -0
  67. package/dist/worker-entry.cjs +727 -0
  68. package/dist/worker-entry.cjs.map +1 -0
  69. package/dist/worker-entry.d.ts +15 -0
  70. package/dist/worker-entry.d.ts.map +1 -0
  71. package/dist/worker-entry.js +711 -0
  72. package/dist/worker-entry.js.map +1 -0
  73. package/dist/worker-setup.d.ts +5 -0
  74. package/dist/worker-setup.d.ts.map +1 -0
  75. package/dist/worker.d.ts +487 -0
  76. package/dist/worker.d.ts.map +1 -0
  77. package/dist/workflow-generator-5nHqlZV7.js +210 -0
  78. package/dist/workflow-generator-5nHqlZV7.js.map +1 -0
  79. package/dist/workflow-generator-D67FvbFe.cjs +239 -0
  80. package/dist/workflow-generator-D67FvbFe.cjs.map +1 -0
  81. package/dist/workflow-generator.d.ts +92 -0
  82. package/dist/workflow-generator.d.ts.map +1 -0
  83. package/package.json +121 -0
@@ -0,0 +1,711 @@
1
+ import { r as parseSessionMetadata, t as createWorkflowReplyGenerator } from "./workflow-generator-5nHqlZV7.js";
2
+ import { a as notifyVoiceObserver, n as VOICE_TEXT_FLUSH } from "./turn-metrics-CqqzdLDe.js";
3
+ import { c as chatContextToMessages, i as MastraVoiceAgent, n as mastraLLMNode, o as createMastraVoiceAgent, r as observeVoiceSession, t as createRemoteAgentReplyGenerator } from "./remote-CIMCGicy.js";
4
+ import { InferenceRunner, ServerOptions, cli, defineAgent, metrics, voice } from "@livekit/agents";
5
+ import { RequestContext } from "@mastra/core/request-context";
6
+ import { SpanType, getOrCreateSpan } from "@mastra/core/observability";
7
+ import { fileURLToPath } from "url";
8
+ //#region src/observability.ts
9
+ function modelMeta(metadata) {
10
+ const out = {};
11
+ if (metadata?.modelProvider) out.modelProvider = metadata.modelProvider;
12
+ if (metadata?.modelName) out.modelName = metadata.modelName;
13
+ return out;
14
+ }
15
+ const ms = (n) => `${Math.round(n)}ms`;
16
+ const secs = (n) => `${(n / 1e3).toFixed(1)}s`;
17
+ /**
18
+ * Maps a LiveKit pipeline metric to an event-span name and the latency/usage fields worth
19
+ * recording. The name carries the headline number so it reads in the trace timeline without
20
+ * opening the span. Metrics this release does not surface (interruption, EOT inference, avatar)
21
+ * return `undefined` — they still feed the session usage roll-up via the ModelUsageCollector.
22
+ */
23
+ function describeMetric(metric) {
24
+ switch (metric.type) {
25
+ case "eou_metrics": return {
26
+ name: `eou ${ms(metric.endOfUtteranceDelayMs)}`,
27
+ data: {
28
+ endOfUtteranceDelayMs: metric.endOfUtteranceDelayMs,
29
+ transcriptionDelayMs: metric.transcriptionDelayMs,
30
+ onUserTurnCompletedDelayMs: metric.onUserTurnCompletedDelayMs
31
+ }
32
+ };
33
+ case "stt_metrics": return {
34
+ name: `stt ${secs(metric.audioDurationMs)}`,
35
+ data: {
36
+ audioDurationMs: metric.audioDurationMs,
37
+ durationMs: metric.durationMs,
38
+ streamed: metric.streamed,
39
+ ...modelMeta(metric.metadata)
40
+ }
41
+ };
42
+ case "llm_metrics": return {
43
+ name: `llm ttft ${ms(metric.ttftMs)}`,
44
+ data: {
45
+ ttftMs: metric.ttftMs,
46
+ durationMs: metric.durationMs,
47
+ tokensPerSecond: metric.tokensPerSecond,
48
+ promptTokens: metric.promptTokens,
49
+ completionTokens: metric.completionTokens,
50
+ totalTokens: metric.totalTokens,
51
+ cancelled: metric.cancelled,
52
+ ...modelMeta(metric.metadata)
53
+ }
54
+ };
55
+ case "tts_metrics": return {
56
+ name: `tts ttfb ${ms(metric.ttfbMs)}`,
57
+ data: {
58
+ ttfbMs: metric.ttfbMs,
59
+ durationMs: metric.durationMs,
60
+ audioDurationMs: metric.audioDurationMs,
61
+ charactersCount: metric.charactersCount,
62
+ cancelled: metric.cancelled,
63
+ streamed: metric.streamed,
64
+ ...modelMeta(metric.metadata)
65
+ }
66
+ };
67
+ case "vad_metrics": return {
68
+ name: "vad",
69
+ data: {
70
+ idleTimeMs: metric.idleTimeMs,
71
+ inferenceCount: metric.inferenceCount,
72
+ inferenceDurationTotalMs: metric.inferenceDurationTotalMs
73
+ }
74
+ };
75
+ case "realtime_model_metrics": return {
76
+ name: `realtime ttft ${ms(metric.ttftMs)}`,
77
+ data: {
78
+ ttftMs: metric.ttftMs,
79
+ durationMs: metric.durationMs,
80
+ tokensPerSecond: metric.tokensPerSecond,
81
+ promptTokens: metric.inputTokens,
82
+ completionTokens: metric.outputTokens,
83
+ totalTokens: metric.totalTokens,
84
+ ...modelMeta(metric.metadata)
85
+ }
86
+ };
87
+ default: return;
88
+ }
89
+ }
90
+ /**
91
+ * Opens a `voice call` trace for one LiveKit session and bridges LiveKit's voice-pipeline
92
+ * metrics into Mastra observability.
93
+ *
94
+ * The returned root span groups everything about the call: each conversation turn's Mastra
95
+ * agent run (nested via {@link VoiceCallObservability.tracingContext}) plus an event span for
96
+ * every STT, TTS, end-of-utterance, VAD, and LLM-latency metric LiveKit emits. Metrics are
97
+ * point-in-time, so they're recorded as event spans (no duration) with the value in the name.
98
+ * The root closes on the session `close` event with a per-model usage roll-up (token, character,
99
+ * and audio totals for the whole call) from a `ModelUsageCollector`.
100
+ *
101
+ * Returns `undefined` when the Mastra instance has no observability configured, so callers
102
+ * can treat instrumentation as a no-op without branching on config.
103
+ */
104
+ function startVoiceCallObservability(options) {
105
+ const span = getOrCreateSpan({
106
+ mastra: options.mastra,
107
+ type: SpanType.GENERIC,
108
+ name: "voice call",
109
+ requestContext: options.requestContext,
110
+ metadata: {
111
+ agentId: options.agentId,
112
+ roomName: options.roomName,
113
+ ...options.metadata.threadId ? { threadId: options.metadata.threadId } : {},
114
+ ...options.metadata.resourceId ? { resourceId: options.metadata.resourceId } : {}
115
+ }
116
+ });
117
+ if (!span) return void 0;
118
+ const usage = new metrics.ModelUsageCollector();
119
+ let finalized = false;
120
+ const finalize = (opts) => {
121
+ if (finalized) return;
122
+ finalized = true;
123
+ const summary = usage.flatten();
124
+ if (opts?.error) span.error({
125
+ error: opts.error instanceof Error ? opts.error : new Error(String(opts.error)),
126
+ metadata: { usage: summary }
127
+ });
128
+ else span.end({ output: { usage: summary } });
129
+ };
130
+ return {
131
+ span,
132
+ tracingContext: { currentSpan: span },
133
+ recordTurn(metric) {
134
+ span.createEventSpan({
135
+ type: SpanType.GENERIC,
136
+ name: `voice ${metric.phase} ${metric.outcome}`,
137
+ output: metric
138
+ });
139
+ },
140
+ attach(session) {
141
+ session.on(voice.AgentSessionEventTypes.MetricsCollected, (event) => {
142
+ usage.collect(event.metrics);
143
+ const described = describeMetric(event.metrics);
144
+ if (!described) return;
145
+ span.createEventSpan({
146
+ type: SpanType.GENERIC,
147
+ name: described.name,
148
+ output: {
149
+ ...described.data,
150
+ ..."speechId" in event.metrics ? { speechId: event.metrics.speechId } : {}
151
+ }
152
+ });
153
+ });
154
+ session.on(voice.AgentSessionEventTypes.Close, (event) => {
155
+ finalize({ error: event?.error ?? void 0 });
156
+ });
157
+ },
158
+ finalize
159
+ };
160
+ }
161
+ //#endregion
162
+ //#region src/voice-thread.ts
163
+ /**
164
+ * Creates the call's memory thread up front when it doesn't exist yet, titled and tagged
165
+ * so it reads as a voice call in Studio's thread list instead of an untitled thread that
166
+ * only appears after the first exchange.
167
+ */
168
+ async function ensureVoiceCallThread({ memory, threadId, resourceId, roomName }) {
169
+ if (await memory.getThreadById({ threadId })) return;
170
+ await memory.createThread({
171
+ threadId,
172
+ resourceId,
173
+ title: "Voice call",
174
+ metadata: {
175
+ source: "livekit",
176
+ roomName
177
+ }
178
+ });
179
+ }
180
+ /**
181
+ * Persists the spoken greeting as an assistant message. The greeting is spoken via TTS
182
+ * without going through the Mastra agent, so without this the saved thread would start
183
+ * at the caller's first words instead of being a faithful call transcript.
184
+ */
185
+ async function persistSpokenGreeting({ memory, threadId, resourceId, greeting }) {
186
+ if (!greeting.trim()) return;
187
+ const message = {
188
+ id: globalThis.crypto.randomUUID(),
189
+ role: "assistant",
190
+ type: "text",
191
+ createdAt: /* @__PURE__ */ new Date(),
192
+ threadId,
193
+ resourceId,
194
+ content: {
195
+ format: 2,
196
+ parts: [{
197
+ type: "text",
198
+ text: greeting
199
+ }],
200
+ metadata: {
201
+ source: "voice",
202
+ kind: "greeting"
203
+ }
204
+ }
205
+ };
206
+ await memory.saveMessages({ messages: [message] });
207
+ }
208
+ //#endregion
209
+ //#region src/worker-setup.ts
210
+ /**
211
+ * Coordination between worker definition and worker startup. LiveKit plugins register
212
+ * their inference runners at module-import time, and the AgentServer only spawns the
213
+ * inference process for runners registered before it starts — so plugin imports kicked
214
+ * off by `createLiveKitWorker()` must complete before `runLiveKitWorker()` boots the
215
+ * server.
216
+ */
217
+ const pendingSetup = [];
218
+ const requestedEouMethods = /* @__PURE__ */ new Set();
219
+ function queueWorkerSetup(setup) {
220
+ pendingSetup.push(setup);
221
+ }
222
+ function workerSetupComplete() {
223
+ return Promise.allSettled(pendingSetup);
224
+ }
225
+ function requestEouMethod(method) {
226
+ requestedEouMethods.add(method);
227
+ }
228
+ function isEouMethodRequested(method) {
229
+ return requestedEouMethods.has(method);
230
+ }
231
+ //#endregion
232
+ //#region src/worker.ts
233
+ const EOU_METHODS = {
234
+ english: "lk_end_of_utterance_en",
235
+ multilingual: "lk_end_of_utterance_multilingual"
236
+ };
237
+ async function loadSileroVad() {
238
+ let silero;
239
+ try {
240
+ silero = await import("@livekit/agents-plugin-silero");
241
+ } catch (error) {
242
+ throw new Error("@mastra/livekit: voice activity detection requires '@livekit/agents-plugin-silero'. Install it, pass your own `vad` instance, or set `vad: false`.", { cause: error });
243
+ }
244
+ return silero.VAD.load();
245
+ }
246
+ async function loadTurnDetector(kind) {
247
+ let plugin;
248
+ try {
249
+ plugin = await import("@livekit/agents-plugin-livekit");
250
+ } catch (error) {
251
+ throw new Error(`@mastra/livekit: turnDetection '${kind}' requires '@livekit/agents-plugin-livekit'. Install it or use a built-in mode like 'vad' or 'stt'.`, { cause: error });
252
+ }
253
+ return kind === "english" ? new plugin.turnDetector.EnglishModel() : new plugin.turnDetector.MultilingualModel();
254
+ }
255
+ async function resolveMastraAgent(options, args) {
256
+ let ref = typeof options.agent === "function" ? await options.agent(args) : options.agent;
257
+ ref ??= args.metadata.agentId;
258
+ if (!ref) throw new Error("@mastra/livekit: no Mastra agent specified. Set `agent` on createLiveKitWorker or pass `agentId` in the dispatch metadata (e.g. via liveKitConnectionRoute).");
259
+ if (typeof ref !== "string") return ref;
260
+ try {
261
+ return options.mastra.getAgentById(ref);
262
+ } catch {
263
+ return options.mastra.getAgent(ref);
264
+ }
265
+ }
266
+ async function resolveWorkflow(options, args) {
267
+ const resolver = options.workflow;
268
+ const ref = typeof resolver === "function" ? await resolver(args) : resolver ?? "";
269
+ if (!ref) throw new Error("@mastra/livekit: no workflow specified. Set `workflow` on createLiveKitWorker.");
270
+ if (typeof ref !== "string") return { workflow: ref };
271
+ return { workflow: options.mastra.getWorkflowById(ref) };
272
+ }
273
+ function resolveMemory(options, mastraAgent, args, roomName) {
274
+ if (options.memory === false) return false;
275
+ if (typeof options.memory === "function") return options.memory({
276
+ ...args,
277
+ roomName
278
+ });
279
+ if (mastraAgent && !mastraAgent.hasOwnMemory()) return false;
280
+ const thread = args.metadata.threadId ?? roomName;
281
+ return {
282
+ thread,
283
+ resource: args.metadata.resourceId ?? thread
284
+ };
285
+ }
286
+ async function resolveMemoryInstance(options, mastraAgent, args, requestContext) {
287
+ if (mastraAgent) return await mastraAgent.getMemory({ requestContext }) ?? null;
288
+ const resolver = options.memoryInstance;
289
+ if (!resolver) return null;
290
+ const instance = typeof resolver === "function" ? await resolver(args) : resolver;
291
+ if (!instance) return null;
292
+ instance.__registerMastra(options.mastra);
293
+ if (!instance.hasOwnStorage) {
294
+ const storage = options.mastra.getStorage();
295
+ if (storage) instance.setStorage(storage);
296
+ }
297
+ return instance;
298
+ }
299
+ function buildTurnHandling(options, turnDetection) {
300
+ return {
301
+ ...turnDetection ? { turnDetection } : {},
302
+ preemptiveGeneration: { enabled: false },
303
+ ...options.turnHandling
304
+ };
305
+ }
306
+ async function resolveInstructions(mastraAgent, requestContext) {
307
+ try {
308
+ const instructions = await mastraAgent.getInstructions({ requestContext });
309
+ return typeof instructions === "string" ? instructions : void 0;
310
+ } catch {
311
+ return;
312
+ }
313
+ }
314
+ /**
315
+ * Resolves the effective greeting from the canonical `configuration.greeting` and the deprecated
316
+ * top-level `greeting` / `persistGreeting` options. The legacy options are the base so existing
317
+ * worker configs keep working unchanged; `configuration.greeting` overrides field-by-field. Exported
318
+ * for unit testing.
319
+ */
320
+ function resolveGreetingConfig(options) {
321
+ return {
322
+ text: options.greeting,
323
+ persist: options.persistGreeting,
324
+ ...options.configuration?.greeting
325
+ };
326
+ }
327
+ /**
328
+ * Resolves the greeting text for a call: returns a fixed string as-is, or invokes the resolver form
329
+ * with the call context to produce a per-tenant greeting. Empty / whitespace-nothing results
330
+ * normalize to `undefined` (no greeting). Exported for unit testing.
331
+ */
332
+ async function resolveGreetingText(text, context) {
333
+ return (typeof text === "function" ? await text(context) : text) || void 0;
334
+ }
335
+ /**
336
+ * Resolves a per-call session component (STT / TTS): invokes the `configuration` resolver with the
337
+ * call context, falling back to the static top-level option when there is no resolver or it
338
+ * resolves to `undefined`. Exported for unit testing.
339
+ */
340
+ async function resolveSessionComponent(resolver, fallback, context) {
341
+ return (resolver ? await resolver(context) : void 0) ?? fallback;
342
+ }
343
+ /**
344
+ * Resolves this call's end-of-turn detection: the `configuration.turnDetection` resolver first,
345
+ * then the static `turnDetection` option (loading the LiveKit semantic model for the
346
+ * `'multilingual'` / `'english'` shorthands). Must run inside the job — LiveKit's turn detectors
347
+ * read the job's inference executor when constructed. Exported for unit testing.
348
+ */
349
+ async function resolveTurnDetection(options, context) {
350
+ const resolved = await options.configuration?.turnDetection?.(context);
351
+ if (resolved) return resolved;
352
+ if (options.turnDetection === "multilingual" || options.turnDetection === "english") return loadTurnDetector(options.turnDetection);
353
+ return options.turnDetection;
354
+ }
355
+ /**
356
+ * Speaks the session's opening greeting, honoring the interruption / playout options. Takes the
357
+ * already-resolved greeting (see {@link resolveGreetingText}) and returns the LiveKit `SpeechHandle`,
358
+ * or `undefined` when there is no greeting text. Extracted and exported so the greeting behavior is
359
+ * unit-testable without a live room.
360
+ */
361
+ async function speakGreeting(session, greeting) {
362
+ if (!greeting.text) return void 0;
363
+ const handle = session.say(greeting.text, greeting.allowInterruptions === void 0 ? void 0 : { allowInterruptions: greeting.allowInterruptions });
364
+ if (greeting.awaitPlayout) await handle.waitForPlayout().catch(() => {});
365
+ return handle;
366
+ }
367
+ /** Default tool name the worker watches for to end the call. Matches `createEndCallTool`'s default. */
368
+ const DEFAULT_END_CALL_TOOL = "endCall";
369
+ /** Default shutdown reason recorded when the agent ends the call. */
370
+ const DEFAULT_END_CALL_REASON = "agent ended call";
371
+ /** Default safety cap on waiting for the agent's closing words to finish before hanging up. */
372
+ const DEFAULT_END_CALL_MAX_WAIT_MS = 3e4;
373
+ /**
374
+ * Default post-playout drain before the room is deleted. LiveKit's "playout completed" is
375
+ * worker-local; the caller's client still holds network + jitter-buffer audio, so hanging up the
376
+ * instant the state clears clips the tail of the goodbye.
377
+ */
378
+ const DEFAULT_END_CALL_DRAIN_MS = 800;
379
+ /** Agent states where the agent is still busy producing / playing a reply (not done speaking). */
380
+ const AGENT_BUSY_STATES = /* @__PURE__ */ new Set(["thinking", "speaking"]);
381
+ /**
382
+ * Resolves once the agent is no longer producing or playing a reply — i.e. its state has left
383
+ * `thinking`/`speaking` for `listening`/`idle`. Returns immediately when it's already idle. A
384
+ * `maxWaitMs` safety cap guarantees it resolves even if the speaking state never clears. Used before
385
+ * an agent-initiated hang-up so the closing words play out fully instead of being cut off by the
386
+ * session close. Exported for unit testing.
387
+ */
388
+ function waitForAgentDoneSpeaking(session, maxWaitMs = DEFAULT_END_CALL_MAX_WAIT_MS) {
389
+ if (!AGENT_BUSY_STATES.has(session.agentState)) return Promise.resolve();
390
+ return new Promise((resolve) => {
391
+ let timer;
392
+ const onChange = (ev) => {
393
+ if (AGENT_BUSY_STATES.has(ev.newState)) return;
394
+ cleanup();
395
+ resolve();
396
+ };
397
+ const cleanup = () => {
398
+ session.off(voice.AgentSessionEventTypes.AgentStateChanged, onChange);
399
+ if (timer) clearTimeout(timer);
400
+ };
401
+ session.on(voice.AgentSessionEventTypes.AgentStateChanged, onChange);
402
+ timer = setTimeout(() => {
403
+ cleanup();
404
+ resolve();
405
+ }, maxWaitMs);
406
+ timer.unref?.();
407
+ });
408
+ }
409
+ /**
410
+ * Ends the call after the agent asked to (via its end-call tool): wait for the agent's closing words
411
+ * to finish, speak an optional final `message`, hold a short drain (`drainMs`) so audio buffered at
412
+ * the caller finishes playing, then disconnect. The teardown's session close
413
+ * force-interrupts any playing speech, so the waits here MUST complete before we disconnect — that's
414
+ * the whole point of the sequence. `ctx.deleteRoom()` hangs up the caller (SIP-safe); `ctx.shutdown()`
415
+ * ends the job and runs the registered shutdown callbacks (`onCallEnd`), so end-of-call work happens
416
+ * exactly as it does on a caller hang-up. Both run in a `finally` so a hiccup while waiting still ends
417
+ * the call. Never rejects — every step is guarded and failures are logged, so callers can safely
418
+ * fire-and-forget it (`void runEndCall(...)`) from hooks. Exported for unit testing.
419
+ */
420
+ async function runEndCall(session, ctx, config, logger) {
421
+ try {
422
+ await waitForAgentDoneSpeaking(session, config.maxWaitMs ?? 3e4);
423
+ if (config.message) await session.say(config.message, { allowInterruptions: false }).waitForPlayout().catch(() => {});
424
+ const drainMs = config.drainMs ?? 800;
425
+ if (drainMs > 0) await new Promise((resolve) => setTimeout(resolve, drainMs));
426
+ } catch (error) {
427
+ logger.warn("@mastra/livekit: waiting for the agent to finish before ending the call failed", error);
428
+ } finally {
429
+ try {
430
+ await ctx.deleteRoom();
431
+ } catch (error) {
432
+ logger.warn("@mastra/livekit: deleteRoom while ending the call failed", error);
433
+ }
434
+ try {
435
+ ctx.shutdown(config.reason ?? "agent ended call");
436
+ } catch (error) {
437
+ logger.warn("@mastra/livekit: shutdown while ending the call failed", error);
438
+ }
439
+ }
440
+ }
441
+ /**
442
+ * Builds the per-turn hook that detects the agent's end-call tool and kicks off the hang-up once, or
443
+ * `undefined` when end-call isn't configured. The detector fires the teardown fire-and-forget (the
444
+ * turn never waits on it) and de-dupes so a repeated tool call can't start two hang-ups.
445
+ */
446
+ function buildEndCallDetector(config, getSession, ctx, logger) {
447
+ if (!config) return void 0;
448
+ const toolName = config.tool ?? "endCall";
449
+ let triggered = false;
450
+ return (turnCtx) => {
451
+ if (triggered) return;
452
+ if (!turnCtx.result.toolCalls.some((call) => call.toolName === toolName)) return;
453
+ const session = getSession();
454
+ if (!session) return;
455
+ triggered = true;
456
+ runEndCall(session, ctx, config, logger);
457
+ };
458
+ }
459
+ /** Runs the worker's own turn-complete detector alongside the user's `onTurnComplete`, if any. */
460
+ function composeTurnComplete(user, detector) {
461
+ if (!detector) return user;
462
+ return (ctx) => {
463
+ detector(ctx);
464
+ return user?.(ctx);
465
+ };
466
+ }
467
+ /**
468
+ * Builds a LiveKit agent worker definition that answers voice sessions with Mastra agents.
469
+ *
470
+ * Use as the default export of your worker entry file, then run it with the LiveKit
471
+ * agents CLI:
472
+ *
473
+ * ```ts
474
+ * // src/mastra/voice-worker.ts
475
+ * import { fileURLToPath } from 'node:url';
476
+ * import { createLiveKitWorker, runLiveKitWorker } from '@mastra/livekit/worker';
477
+ * import { mastra } from './index';
478
+ *
479
+ * export default createLiveKitWorker({
480
+ * mastra,
481
+ * stt: 'deepgram/nova-3',
482
+ * tts: 'cartesia/sonic-3',
483
+ * turnDetection: 'multilingual',
484
+ * });
485
+ *
486
+ * if (process.argv[1] === fileURLToPath(import.meta.url)) {
487
+ * runLiveKitWorker({ entry: import.meta.url, agentName: 'mastra-voice' });
488
+ * }
489
+ * ```
490
+ */
491
+ function createLiveKitWorker(options) {
492
+ if (options.generate && (options.agent || options.workflow)) throw new Error("@mastra/livekit: set exactly one reply generator — `generate`, `agent`, or `workflow` — not a combination.");
493
+ if (options.agent && options.workflow) throw new Error("@mastra/livekit: set `agent` or `workflow`, not both — they are mutually exclusive reply generators.");
494
+ if (options.workflow && !options.workflowInput) throw new Error("@mastra/livekit: `workflowInput` is required when `workflow` is set. Map the turn into the workflow inputData, e.g. workflowInput: ({ chatCtx }) => ({ history: chatContextToMessages(chatCtx) }).");
495
+ if (options.generate && options.configuration?.endCall) throw new Error("@mastra/livekit: `configuration.endCall` has no effect with `generate` — the worker cannot observe tool calls from a custom reply generator. Detect the end-call tool inside your generator and call `runEndCall` directly instead.");
496
+ const wantsSileroVad = options.vad === void 0 || options.vad === "silero";
497
+ const hasTurnDetectionResolver = options.configuration?.turnDetection !== void 0;
498
+ if (options.turnDetection === "multilingual" || options.turnDetection === "english") requestEouMethod(EOU_METHODS[options.turnDetection]);
499
+ else if (hasTurnDetectionResolver) for (const method of Object.values(EOU_METHODS)) requestEouMethod(method);
500
+ if (options.turnDetection === "multilingual" || options.turnDetection === "english" || hasTurnDetectionResolver) queueWorkerSetup(import("@livekit/agents-plugin-livekit").then(() => {
501
+ for (const method of Object.values(EOU_METHODS)) if (!isEouMethodRequested(method)) delete InferenceRunner.registeredRunners[method];
502
+ }).catch(() => {}));
503
+ return defineAgent({
504
+ prewarm: async (proc) => {
505
+ if (wantsSileroVad) proc.userData.vad = await loadSileroVad();
506
+ },
507
+ entry: async (ctx) => {
508
+ const logger = options.mastra.getLogger();
509
+ const metadata = parseSessionMetadata(ctx.job.metadata);
510
+ const args = {
511
+ metadata,
512
+ ctx
513
+ };
514
+ const requestContext = metadata.requestContext ? new RequestContext(Object.entries(metadata.requestContext)) : void 0;
515
+ const endCallDetector = buildEndCallDetector(options.configuration?.endCall, () => session, ctx, logger);
516
+ const onTurnComplete = composeTurnComplete(options.onTurnComplete, endCallDetector);
517
+ let mastraAgent;
518
+ let replyGenerator;
519
+ let agentLabel;
520
+ if (options.generate) {
521
+ replyGenerator = options.generate;
522
+ agentLabel = "mastra-voice";
523
+ } else if (options.workflow) {
524
+ const { workflow } = await resolveWorkflow(options, args);
525
+ agentLabel = workflow.id;
526
+ const mapInput = options.workflowInput;
527
+ replyGenerator = createWorkflowReplyGenerator({
528
+ workflow,
529
+ workflowInput: (turnCtx) => mapInput({
530
+ ...turnCtx,
531
+ metadata
532
+ }),
533
+ replyStep: options.replyStep,
534
+ resultText: options.resultText,
535
+ toolFeedback: options.toolFeedback,
536
+ onTurnComplete
537
+ });
538
+ } else {
539
+ mastraAgent = await resolveMastraAgent(options, args);
540
+ agentLabel = mastraAgent.id ?? mastraAgent.name;
541
+ }
542
+ await ctx.connect();
543
+ const roomName = ctx.room.name ?? "mastra-voice";
544
+ let vad = null;
545
+ if (options.vad && options.vad !== "silero") vad = options.vad;
546
+ else if (wantsSileroVad) vad = ctx.proc.userData.vad ?? await loadSileroVad();
547
+ const memory = resolveMemory(options, mastraAgent, args, roomName);
548
+ const memoryInstance = memory ? await resolveMemoryInstance(options, mastraAgent, args, requestContext) : null;
549
+ if (memory && memoryInstance) try {
550
+ await ensureVoiceCallThread({
551
+ memory: memoryInstance,
552
+ threadId: memory.thread,
553
+ resourceId: memory.resource ?? memory.thread,
554
+ roomName
555
+ });
556
+ } catch (error) {
557
+ logger.warn("@mastra/livekit: failed to create the voice call thread", error);
558
+ }
559
+ const voiceObs = options.observability === false ? void 0 : startVoiceCallObservability({
560
+ mastra: options.mastra,
561
+ agentId: agentLabel,
562
+ roomName,
563
+ metadata,
564
+ requestContext
565
+ });
566
+ if (voiceObs) ctx.addShutdownCallback(async () => {
567
+ voiceObs.finalize();
568
+ });
569
+ if (options.onCallEnd) {
570
+ const onCallEnd = options.onCallEnd;
571
+ ctx.addShutdownCallback(async () => {
572
+ try {
573
+ await onCallEnd({
574
+ memory,
575
+ memoryInstance,
576
+ metadata,
577
+ requestContext,
578
+ configuration: options.configuration,
579
+ roomName,
580
+ ctx
581
+ });
582
+ } catch (error) {
583
+ logger.warn("@mastra/livekit: onCallEnd hook threw", error);
584
+ }
585
+ });
586
+ }
587
+ const greetingConfig = resolveGreetingConfig(options);
588
+ const greetingReminder = greetingConfig.repeatEvery && greetingConfig.repeatEvery > 0 ? {
589
+ everyMs: greetingConfig.repeatEvery,
590
+ text: greetingConfig.repeatText
591
+ } : void 0;
592
+ const onTurnMetrics = (metric) => {
593
+ voiceObs?.recordTurn(metric);
594
+ notifyVoiceObserver(options.onTurnMetrics, metric);
595
+ };
596
+ const agent = createMastraVoiceAgent({
597
+ onTurnMetrics,
598
+ ...replyGenerator ? { generate: replyGenerator } : { agent: mastraAgent },
599
+ instructions: mastraAgent ? await resolveInstructions(mastraAgent, requestContext) : void 0,
600
+ memory,
601
+ requestContext,
602
+ toolFeedback: options.toolFeedback,
603
+ onTurnComplete,
604
+ greetingReminder,
605
+ streamOptions: voiceObs ? { tracingContext: voiceObs.tracingContext } : void 0
606
+ });
607
+ const callContext = {
608
+ metadata,
609
+ requestContext,
610
+ roomName,
611
+ ctx
612
+ };
613
+ const [stt, tts, turnDetection] = await Promise.all([
614
+ resolveSessionComponent(options.configuration?.stt, options.stt, callContext),
615
+ resolveSessionComponent(options.configuration?.tts, options.tts, callContext),
616
+ resolveTurnDetection(options, callContext)
617
+ ]);
618
+ const session = new voice.AgentSession({
619
+ stt,
620
+ tts,
621
+ vad,
622
+ turnHandling: buildTurnHandling(options, turnDetection),
623
+ ...options.sessionOptions
624
+ });
625
+ voiceObs?.attach(session);
626
+ const detachSpeechObserver = observeVoiceSession(session, {
627
+ onTurnMetrics,
628
+ onSpeechComplete: options.onSpeechComplete
629
+ });
630
+ ctx.addShutdownCallback(async () => {
631
+ detachSpeechObserver();
632
+ });
633
+ try {
634
+ await session.start({
635
+ agent,
636
+ room: ctx.room,
637
+ inputOptions: options.inputOptions,
638
+ outputOptions: options.outputOptions
639
+ });
640
+ if (greetingConfig.text) {
641
+ const greetingText = await resolveGreetingText(greetingConfig.text, callContext);
642
+ if (greetingText) {
643
+ await speakGreeting(session, {
644
+ ...greetingConfig,
645
+ text: greetingText
646
+ });
647
+ if (greetingConfig.persist !== false && memory && memoryInstance) try {
648
+ await persistSpokenGreeting({
649
+ memory: memoryInstance,
650
+ threadId: memory.thread,
651
+ resourceId: memory.resource ?? memory.thread,
652
+ greeting: greetingText
653
+ });
654
+ } catch (error) {
655
+ logger.warn("@mastra/livekit: failed to persist the greeting", error);
656
+ }
657
+ }
658
+ }
659
+ await options.onSessionStart?.({
660
+ session,
661
+ ctx,
662
+ agent,
663
+ metadata
664
+ });
665
+ } catch (error) {
666
+ detachSpeechObserver();
667
+ voiceObs?.finalize({ error });
668
+ throw error;
669
+ }
670
+ }
671
+ });
672
+ }
673
+ //#endregion
674
+ //#region src/run.ts
675
+ function resolveWorkerEntryPath(entry) {
676
+ if (entry instanceof URL) return fileURLToPath(entry);
677
+ return entry.startsWith("file:") ? fileURLToPath(entry) : entry;
678
+ }
679
+ /**
680
+ * Starts the LiveKit agent worker CLI (`dev` / `start` / `connect` subcommands) for a
681
+ * worker entry file. Call it from the same file that default-exports
682
+ * {@link createLiveKitWorker}, guarded so it only runs when executed directly:
683
+ *
684
+ * ```ts
685
+ * import { fileURLToPath } from 'node:url';
686
+ * import { createLiveKitWorker, runLiveKitWorker } from '@mastra/livekit/worker';
687
+ * import { mastra } from './index';
688
+ *
689
+ * export default createLiveKitWorker({ mastra, agent: 'support' });
690
+ *
691
+ * if (process.argv[1] === fileURLToPath(import.meta.url)) {
692
+ * runLiveKitWorker({ entry: import.meta.url, agentName: 'mastra-voice' });
693
+ * }
694
+ * ```
695
+ *
696
+ * Using this helper (instead of `cli.runApp` from `@livekit/agents`) guarantees the worker
697
+ * runtime and the bridge share one copy of the LiveKit SDK.
698
+ */
699
+ function runLiveKitWorker(options) {
700
+ workerSetupComplete().then(() => {
701
+ cli.runApp(new ServerOptions({
702
+ agent: resolveWorkerEntryPath(options.entry),
703
+ agentName: options.agentName ?? "mastra-voice",
704
+ ...options.serverOptions
705
+ }));
706
+ });
707
+ }
708
+ //#endregion
709
+ export { DEFAULT_END_CALL_DRAIN_MS, DEFAULT_END_CALL_MAX_WAIT_MS, DEFAULT_END_CALL_REASON, DEFAULT_END_CALL_TOOL, MastraVoiceAgent, VOICE_TEXT_FLUSH, chatContextToMessages, createLiveKitWorker, createMastraVoiceAgent, createRemoteAgentReplyGenerator, mastraLLMNode, observeVoiceSession, runEndCall, runLiveKitWorker, speakGreeting, waitForAgentDoneSpeaking };
710
+
711
+ //# sourceMappingURL=worker-entry.js.map