@mastra/livekit 0.0.0-esbuild-bundle-worker-20260807173433

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