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