@mastra/livekit 0.3.0 → 0.3.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,586 +1,675 @@
1
- import { parseSessionMetadata, createWorkflowReplyGenerator, DEFAULT_LIVEKIT_AGENT_NAME } from './chunk-2E3MTAOA.js';
2
- import { createMastraVoiceAgent } from './chunk-4O7IN74Y.js';
3
- export { chatContextToMessages, createRemoteAgentReplyGenerator } from './chunk-4O7IN74Y.js';
4
- import { voice, InferenceRunner, defineAgent, cli, ServerOptions, metrics } from '@livekit/agents';
5
- import { RequestContext } from '@mastra/core/request-context';
6
- import { getOrCreateSpan, SpanType } from '@mastra/core/observability';
7
- import { randomUUID } from 'crypto';
8
- import { fileURLToPath } from 'url';
9
-
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
10
9
  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;
10
+ const out = {};
11
+ if (metadata?.modelProvider) out.modelProvider = metadata.modelProvider;
12
+ if (metadata?.modelName) out.modelName = metadata.modelName;
13
+ return out;
15
14
  }
16
- var ms = (n) => `${Math.round(n)}ms`;
17
- var secs = (n) => `${(n / 1e3).toFixed(1)}s`;
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
+ */
18
23
  function describeMetric(metric) {
19
- switch (metric.type) {
20
- case "eou_metrics":
21
- return {
22
- name: `eou ${ms(metric.endOfUtteranceDelayMs)}`,
23
- data: {
24
- endOfUtteranceDelayMs: metric.endOfUtteranceDelayMs,
25
- transcriptionDelayMs: metric.transcriptionDelayMs,
26
- onUserTurnCompletedDelayMs: metric.onUserTurnCompletedDelayMs
27
- }
28
- };
29
- case "stt_metrics":
30
- return {
31
- name: `stt ${secs(metric.audioDurationMs)}`,
32
- data: {
33
- audioDurationMs: metric.audioDurationMs,
34
- durationMs: metric.durationMs,
35
- streamed: metric.streamed,
36
- ...modelMeta(metric.metadata)
37
- }
38
- };
39
- case "llm_metrics":
40
- return {
41
- name: `llm ttft ${ms(metric.ttftMs)}`,
42
- data: {
43
- ttftMs: metric.ttftMs,
44
- durationMs: metric.durationMs,
45
- tokensPerSecond: metric.tokensPerSecond,
46
- promptTokens: metric.promptTokens,
47
- completionTokens: metric.completionTokens,
48
- totalTokens: metric.totalTokens,
49
- cancelled: metric.cancelled,
50
- ...modelMeta(metric.metadata)
51
- }
52
- };
53
- case "tts_metrics":
54
- return {
55
- name: `tts ttfb ${ms(metric.ttfbMs)}`,
56
- data: {
57
- ttfbMs: metric.ttfbMs,
58
- durationMs: metric.durationMs,
59
- audioDurationMs: metric.audioDurationMs,
60
- charactersCount: metric.charactersCount,
61
- cancelled: metric.cancelled,
62
- streamed: metric.streamed,
63
- ...modelMeta(metric.metadata)
64
- }
65
- };
66
- case "vad_metrics":
67
- 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":
76
- 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:
89
- return void 0;
90
- }
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
+ }
91
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
+ */
92
104
  function startVoiceCallObservability(options) {
93
- const span = getOrCreateSpan({
94
- mastra: options.mastra,
95
- type: SpanType.GENERIC,
96
- name: "voice call",
97
- requestContext: options.requestContext,
98
- metadata: {
99
- agentId: options.agentId,
100
- roomName: options.roomName,
101
- ...options.metadata.threadId ? { threadId: options.metadata.threadId } : {},
102
- ...options.metadata.resourceId ? { resourceId: options.metadata.resourceId } : {}
103
- }
104
- });
105
- if (!span) return void 0;
106
- const usage = new metrics.ModelUsageCollector();
107
- let finalized = false;
108
- const finalize = (opts) => {
109
- if (finalized) return;
110
- finalized = true;
111
- const summary = usage.flatten();
112
- if (opts?.error) {
113
- span.error({
114
- error: opts.error instanceof Error ? opts.error : new Error(String(opts.error)),
115
- metadata: { usage: summary }
116
- });
117
- } else {
118
- span.end({ output: { usage: summary } });
119
- }
120
- };
121
- return {
122
- span,
123
- tracingContext: { currentSpan: span },
124
- attach(session) {
125
- session.on(voice.AgentSessionEventTypes.MetricsCollected, (event) => {
126
- usage.collect(event.metrics);
127
- const described = describeMetric(event.metrics);
128
- if (!described) return;
129
- span.createEventSpan({ type: SpanType.GENERIC, name: described.name, output: described.data });
130
- });
131
- session.on(voice.AgentSessionEventTypes.Close, (event) => {
132
- finalize({ error: event?.error ?? void 0 });
133
- });
134
- },
135
- finalize
136
- };
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
+ };
137
150
  }
138
- async function ensureVoiceCallThread({
139
- memory,
140
- threadId,
141
- resourceId,
142
- roomName
143
- }) {
144
- const existing = await memory.getThreadById({ threadId });
145
- if (existing) return;
146
- await memory.createThread({
147
- threadId,
148
- resourceId,
149
- title: "Voice call",
150
- metadata: { source: "livekit", roomName }
151
- });
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
+ });
152
169
  }
153
- async function persistSpokenGreeting({
154
- memory,
155
- threadId,
156
- resourceId,
157
- greeting
158
- }) {
159
- if (!greeting.trim()) return;
160
- const message = {
161
- id: randomUUID(),
162
- role: "assistant",
163
- type: "text",
164
- createdAt: /* @__PURE__ */ new Date(),
165
- threadId,
166
- resourceId,
167
- content: {
168
- format: 2,
169
- parts: [{ type: "text", text: greeting }],
170
- metadata: { source: "voice", kind: "greeting" }
171
- }
172
- };
173
- await memory.saveMessages({ messages: [message] });
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] });
174
197
  }
175
-
176
- // src/worker-setup.ts
177
- var pendingSetup = [];
178
- var requestedEouMethods = /* @__PURE__ */ new Set();
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();
179
209
  function queueWorkerSetup(setup) {
180
- pendingSetup.push(setup);
210
+ pendingSetup.push(setup);
181
211
  }
182
212
  function workerSetupComplete() {
183
- return Promise.allSettled(pendingSetup);
213
+ return Promise.allSettled(pendingSetup);
184
214
  }
185
215
  function requestEouMethod(method) {
186
- requestedEouMethods.add(method);
216
+ requestedEouMethods.add(method);
187
217
  }
188
218
  function isEouMethodRequested(method) {
189
- return requestedEouMethods.has(method);
219
+ return requestedEouMethods.has(method);
190
220
  }
191
-
192
- // src/worker.ts
193
- var EOU_METHODS = {
194
- english: "lk_end_of_utterance_en",
195
- multilingual: "lk_end_of_utterance_multilingual"
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"
196
226
  };
197
227
  async function loadSileroVad() {
198
- let silero;
199
- try {
200
- silero = await import('@livekit/agents-plugin-silero');
201
- } catch (error) {
202
- throw new Error(
203
- "@mastra/livekit: voice activity detection requires '@livekit/agents-plugin-silero'. Install it, pass your own `vad` instance, or set `vad: false`.",
204
- { cause: error }
205
- );
206
- }
207
- return silero.VAD.load();
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();
208
235
  }
209
236
  async function loadTurnDetector(kind) {
210
- let plugin;
211
- try {
212
- plugin = await import('@livekit/agents-plugin-livekit');
213
- } catch (error) {
214
- throw new Error(
215
- `@mastra/livekit: turnDetection '${kind}' requires '@livekit/agents-plugin-livekit'. Install it or use a built-in mode like 'vad' or 'stt'.`,
216
- { cause: error }
217
- );
218
- }
219
- return kind === "english" ? new plugin.turnDetector.EnglishModel() : new plugin.turnDetector.MultilingualModel();
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();
220
244
  }
221
245
  async function resolveMastraAgent(options, args) {
222
- let ref = typeof options.agent === "function" ? await options.agent(args) : options.agent;
223
- ref ??= args.metadata.agentId;
224
- if (!ref) {
225
- throw new Error(
226
- "@mastra/livekit: no Mastra agent specified. Set `agent` on createLiveKitWorker or pass `agentId` in the dispatch metadata (e.g. via liveKitConnectionRoute)."
227
- );
228
- }
229
- if (typeof ref !== "string") return ref;
230
- try {
231
- return options.mastra.getAgentById(ref);
232
- } catch {
233
- return options.mastra.getAgent(ref);
234
- }
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
+ }
235
255
  }
236
256
  async function resolveWorkflow(options, args) {
237
- const resolver = options.workflow;
238
- const ref = typeof resolver === "function" ? await resolver(args) : resolver ?? "";
239
- if (!ref) {
240
- throw new Error("@mastra/livekit: no workflow specified. Set `workflow` on createLiveKitWorker.");
241
- }
242
- if (typeof ref !== "string") return { workflow: ref };
243
- return { workflow: options.mastra.getWorkflowById(ref) };
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) };
244
262
  }
245
263
  function resolveMemory(options, mastraAgent, args, roomName) {
246
- if (options.memory === false) return false;
247
- if (typeof options.memory === "function") return options.memory({ ...args, roomName });
248
- if (mastraAgent && !mastraAgent.hasOwnMemory()) return false;
249
- const thread = args.metadata.threadId ?? roomName;
250
- return { thread, resource: args.metadata.resourceId ?? thread };
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
+ };
251
275
  }
252
276
  async function resolveMemoryInstance(options, mastraAgent, args, requestContext) {
253
- if (mastraAgent) return await mastraAgent.getMemory({ requestContext }) ?? null;
254
- const resolver = options.memoryInstance;
255
- if (!resolver) return null;
256
- const instance = typeof resolver === "function" ? await resolver(args) : resolver;
257
- if (!instance) return null;
258
- instance.__registerMastra(options.mastra);
259
- if (!instance.hasOwnStorage) {
260
- const storage = options.mastra.getStorage();
261
- if (storage) instance.setStorage(storage);
262
- }
263
- return instance;
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;
264
288
  }
265
289
  function buildTurnHandling(options, turnDetection) {
266
- return {
267
- ...turnDetection ? { turnDetection } : {},
268
- // Preemptive generation re-runs the Mastra agent on interim transcripts (up to 3
269
- // times per turn), and every run persists the user message to the memory thread —
270
- // duplicating and even saving partial transcripts. Off by default; opt back in via
271
- // `turnHandling.preemptiveGeneration` if the latency win matters more than exact
272
- // thread history.
273
- preemptiveGeneration: { enabled: false },
274
- ...options.turnHandling
275
- };
290
+ return {
291
+ ...turnDetection ? { turnDetection } : {},
292
+ preemptiveGeneration: { enabled: false },
293
+ ...options.turnHandling
294
+ };
276
295
  }
277
296
  async function resolveInstructions(mastraAgent, requestContext) {
278
- try {
279
- const instructions = await mastraAgent.getInstructions({ requestContext });
280
- return typeof instructions === "string" ? instructions : void 0;
281
- } catch {
282
- return void 0;
283
- }
297
+ try {
298
+ const instructions = await mastraAgent.getInstructions({ requestContext });
299
+ return typeof instructions === "string" ? instructions : void 0;
300
+ } catch {
301
+ return;
302
+ }
284
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
+ */
285
310
  function resolveGreetingConfig(options) {
286
- return {
287
- text: options.greeting,
288
- persist: options.persistGreeting,
289
- ...options.configuration?.greeting
290
- };
311
+ return {
312
+ text: options.greeting,
313
+ persist: options.persistGreeting,
314
+ ...options.configuration?.greeting
315
+ };
291
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
+ */
292
322
  async function resolveGreetingText(text, context) {
293
- const resolved = typeof text === "function" ? await text(context) : text;
294
- return resolved || void 0;
323
+ return (typeof text === "function" ? await text(context) : text) || void 0;
295
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
+ */
296
330
  async function resolveSessionComponent(resolver, fallback, context) {
297
- const resolved = resolver ? await resolver(context) : void 0;
298
- return resolved ?? fallback;
331
+ return (resolver ? await resolver(context) : void 0) ?? fallback;
299
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
+ */
300
339
  async function speakGreeting(session, greeting) {
301
- if (!greeting.text) return void 0;
302
- const handle = session.say(
303
- greeting.text,
304
- greeting.allowInterruptions === void 0 ? void 0 : { allowInterruptions: greeting.allowInterruptions }
305
- );
306
- if (greeting.awaitPlayout) {
307
- await handle.waitForPlayout().catch(() => {
308
- });
309
- }
310
- return handle;
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;
311
344
  }
312
- var DEFAULT_END_CALL_TOOL = "endCall";
313
- var DEFAULT_END_CALL_REASON = "agent ended call";
314
- var DEFAULT_END_CALL_MAX_WAIT_MS = 3e4;
315
- var DEFAULT_END_CALL_DRAIN_MS = 800;
316
- var AGENT_BUSY_STATES = /* @__PURE__ */ new Set(["thinking", "speaking"]);
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
+ */
317
366
  function waitForAgentDoneSpeaking(session, maxWaitMs = DEFAULT_END_CALL_MAX_WAIT_MS) {
318
- if (!AGENT_BUSY_STATES.has(session.agentState)) return Promise.resolve();
319
- return new Promise((resolve) => {
320
- let timer;
321
- const onChange = (ev) => {
322
- if (AGENT_BUSY_STATES.has(ev.newState)) return;
323
- cleanup();
324
- resolve();
325
- };
326
- const cleanup = () => {
327
- session.off(voice.AgentSessionEventTypes.AgentStateChanged, onChange);
328
- if (timer) clearTimeout(timer);
329
- };
330
- session.on(voice.AgentSessionEventTypes.AgentStateChanged, onChange);
331
- timer = setTimeout(() => {
332
- cleanup();
333
- resolve();
334
- }, maxWaitMs);
335
- timer.unref?.();
336
- });
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
+ });
337
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
+ */
338
398
  async function runEndCall(session, ctx, config, logger) {
339
- try {
340
- await waitForAgentDoneSpeaking(session, config.maxWaitMs ?? DEFAULT_END_CALL_MAX_WAIT_MS);
341
- if (config.message) {
342
- await session.say(config.message, { allowInterruptions: false }).waitForPlayout().catch(() => {
343
- });
344
- }
345
- const drainMs = config.drainMs ?? DEFAULT_END_CALL_DRAIN_MS;
346
- if (drainMs > 0) await new Promise((resolve) => setTimeout(resolve, drainMs));
347
- } catch (error) {
348
- logger.warn("@mastra/livekit: waiting for the agent to finish before ending the call failed", error);
349
- } finally {
350
- try {
351
- await ctx.deleteRoom();
352
- } catch (error) {
353
- logger.warn("@mastra/livekit: deleteRoom while ending the call failed", error);
354
- }
355
- try {
356
- ctx.shutdown(config.reason ?? DEFAULT_END_CALL_REASON);
357
- } catch (error) {
358
- logger.warn("@mastra/livekit: shutdown while ending the call failed", error);
359
- }
360
- }
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
+ }
361
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
+ */
362
424
  function buildEndCallDetector(config, getSession, ctx, logger) {
363
- if (!config) return void 0;
364
- const toolName = config.tool ?? DEFAULT_END_CALL_TOOL;
365
- let triggered = false;
366
- return (turnCtx) => {
367
- if (triggered) return;
368
- if (!turnCtx.result.toolCalls.some((call) => call.toolName === toolName)) return;
369
- const session = getSession();
370
- if (!session) return;
371
- triggered = true;
372
- void runEndCall(session, ctx, config, logger);
373
- };
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
+ };
374
436
  }
437
+ /** Runs the worker's own turn-complete detector alongside the user's `onTurnComplete`, if any. */
375
438
  function composeTurnComplete(user, detector) {
376
- if (!detector) return user;
377
- return (ctx) => {
378
- void detector(ctx);
379
- return user?.(ctx);
380
- };
439
+ if (!detector) return user;
440
+ return (ctx) => {
441
+ detector(ctx);
442
+ return user?.(ctx);
443
+ };
381
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
+ */
382
469
  function createLiveKitWorker(options) {
383
- if (options.generate && (options.agent || options.workflow)) {
384
- throw new Error(
385
- "@mastra/livekit: set exactly one reply generator \u2014 `generate`, `agent`, or `workflow` \u2014 not a combination."
386
- );
387
- }
388
- if (options.agent && options.workflow) {
389
- throw new Error(
390
- "@mastra/livekit: set `agent` or `workflow`, not both \u2014 they are mutually exclusive reply generators."
391
- );
392
- }
393
- if (options.workflow && !options.workflowInput) {
394
- throw new Error(
395
- "@mastra/livekit: `workflowInput` is required when `workflow` is set. Map the turn into the workflow inputData, e.g. workflowInput: ({ chatCtx }) => ({ history: chatContextToMessages(chatCtx) })."
396
- );
397
- }
398
- if (options.generate && options.configuration?.endCall) {
399
- throw new Error(
400
- "@mastra/livekit: `configuration.endCall` has no effect with `generate` \u2014 the worker cannot observe tool calls from a custom reply generator. Detect the end-call tool inside your generator and call `runEndCall` directly instead."
401
- );
402
- }
403
- const wantsSileroVad = options.vad === void 0 || options.vad === "silero";
404
- if (options.turnDetection === "multilingual" || options.turnDetection === "english") {
405
- requestEouMethod(EOU_METHODS[options.turnDetection]);
406
- queueWorkerSetup(
407
- import('@livekit/agents-plugin-livekit').then(() => {
408
- for (const method of Object.values(EOU_METHODS)) {
409
- if (!isEouMethodRequested(method)) {
410
- delete InferenceRunner.registeredRunners[method];
411
- }
412
- }
413
- }).catch(() => {
414
- })
415
- );
416
- }
417
- return defineAgent({
418
- prewarm: async (proc) => {
419
- if (wantsSileroVad) {
420
- proc.userData.vad = await loadSileroVad();
421
- }
422
- },
423
- entry: async (ctx) => {
424
- const logger = options.mastra.getLogger();
425
- const metadata = parseSessionMetadata(ctx.job.metadata);
426
- const args = { metadata, ctx };
427
- const requestContext = metadata.requestContext ? new RequestContext(Object.entries(metadata.requestContext)) : void 0;
428
- const endCallDetector = buildEndCallDetector(options.configuration?.endCall, () => session, ctx, logger);
429
- const onTurnComplete = composeTurnComplete(options.onTurnComplete, endCallDetector);
430
- let mastraAgent;
431
- let replyGenerator;
432
- let agentLabel;
433
- if (options.generate) {
434
- replyGenerator = options.generate;
435
- agentLabel = "mastra-voice";
436
- } else if (options.workflow) {
437
- const { workflow } = await resolveWorkflow(options, args);
438
- agentLabel = workflow.id;
439
- const mapInput = options.workflowInput;
440
- replyGenerator = createWorkflowReplyGenerator({
441
- workflow,
442
- workflowInput: (turnCtx) => mapInput({ ...turnCtx, metadata }),
443
- replyStep: options.replyStep,
444
- resultText: options.resultText,
445
- toolFeedback: options.toolFeedback,
446
- onTurnComplete
447
- });
448
- } else {
449
- mastraAgent = await resolveMastraAgent(options, args);
450
- agentLabel = mastraAgent.id ?? mastraAgent.name;
451
- }
452
- await ctx.connect();
453
- const roomName = ctx.room.name ?? "mastra-voice";
454
- let vad;
455
- if (options.vad && options.vad !== "silero") {
456
- vad = options.vad;
457
- } else if (wantsSileroVad) {
458
- vad = ctx.proc.userData.vad ?? await loadSileroVad();
459
- }
460
- let turnDetection;
461
- if (options.turnDetection === "multilingual" || options.turnDetection === "english") {
462
- turnDetection = await loadTurnDetector(options.turnDetection);
463
- } else {
464
- turnDetection = options.turnDetection;
465
- }
466
- const memory = resolveMemory(options, mastraAgent, args, roomName);
467
- const memoryInstance = memory ? await resolveMemoryInstance(options, mastraAgent, args, requestContext) : null;
468
- if (memory && memoryInstance) {
469
- try {
470
- await ensureVoiceCallThread({
471
- memory: memoryInstance,
472
- threadId: memory.thread,
473
- resourceId: memory.resource ?? memory.thread,
474
- roomName
475
- });
476
- } catch (error) {
477
- logger.warn("@mastra/livekit: failed to create the voice call thread", error);
478
- }
479
- }
480
- const voiceObs = options.observability === false ? void 0 : startVoiceCallObservability({
481
- mastra: options.mastra,
482
- agentId: agentLabel,
483
- roomName,
484
- metadata,
485
- requestContext
486
- });
487
- if (voiceObs) {
488
- ctx.addShutdownCallback(async () => {
489
- voiceObs.finalize();
490
- });
491
- }
492
- if (options.onCallEnd) {
493
- const onCallEnd = options.onCallEnd;
494
- ctx.addShutdownCallback(async () => {
495
- try {
496
- await onCallEnd({
497
- memory,
498
- memoryInstance,
499
- metadata,
500
- requestContext,
501
- configuration: options.configuration,
502
- roomName,
503
- ctx
504
- });
505
- } catch (error) {
506
- logger.warn("@mastra/livekit: onCallEnd hook threw", error);
507
- }
508
- });
509
- }
510
- const greetingConfig = resolveGreetingConfig(options);
511
- const greetingReminder = greetingConfig.repeatEvery && greetingConfig.repeatEvery > 0 ? { everyMs: greetingConfig.repeatEvery, text: greetingConfig.repeatText } : void 0;
512
- const agent = createMastraVoiceAgent({
513
- ...replyGenerator ? { generate: replyGenerator } : { agent: mastraAgent },
514
- instructions: mastraAgent ? await resolveInstructions(mastraAgent, requestContext) : void 0,
515
- memory,
516
- requestContext,
517
- toolFeedback: options.toolFeedback,
518
- onTurnComplete,
519
- greetingReminder,
520
- streamOptions: voiceObs ? { tracingContext: voiceObs.tracingContext } : void 0
521
- });
522
- const callContext = { metadata, requestContext, roomName, ctx };
523
- const [stt, tts] = await Promise.all([
524
- resolveSessionComponent(options.configuration?.stt, options.stt, callContext),
525
- resolveSessionComponent(options.configuration?.tts, options.tts, callContext)
526
- ]);
527
- const session = new voice.AgentSession({
528
- stt,
529
- tts,
530
- vad,
531
- turnHandling: buildTurnHandling(options, turnDetection),
532
- ...options.sessionOptions
533
- });
534
- voiceObs?.attach(session);
535
- try {
536
- await session.start({
537
- agent,
538
- room: ctx.room,
539
- inputOptions: options.inputOptions,
540
- outputOptions: options.outputOptions
541
- });
542
- if (greetingConfig.text) {
543
- const greetingText = await resolveGreetingText(greetingConfig.text, callContext);
544
- if (greetingText) {
545
- await speakGreeting(session, { ...greetingConfig, text: greetingText });
546
- if (greetingConfig.persist !== false && memory && memoryInstance) {
547
- try {
548
- await persistSpokenGreeting({
549
- memory: memoryInstance,
550
- threadId: memory.thread,
551
- resourceId: memory.resource ?? memory.thread,
552
- greeting: greetingText
553
- });
554
- } catch (error) {
555
- logger.warn("@mastra/livekit: failed to persist the greeting", error);
556
- }
557
- }
558
- }
559
- }
560
- await options.onSessionStart?.({ session, ctx, agent, metadata });
561
- } catch (error) {
562
- voiceObs?.finalize({ error });
563
- throw error;
564
- }
565
- }
566
- });
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
+ });
567
636
  }
637
+ //#endregion
638
+ //#region src/run.ts
568
639
  function resolveWorkerEntryPath(entry) {
569
- if (entry instanceof URL) return fileURLToPath(entry);
570
- return entry.startsWith("file:") ? fileURLToPath(entry) : entry;
640
+ if (entry instanceof URL) return fileURLToPath(entry);
641
+ return entry.startsWith("file:") ? fileURLToPath(entry) : entry;
571
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
+ */
572
663
  function runLiveKitWorker(options) {
573
- void workerSetupComplete().then(() => {
574
- cli.runApp(
575
- new ServerOptions({
576
- agent: resolveWorkerEntryPath(options.entry),
577
- agentName: options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME,
578
- ...options.serverOptions
579
- })
580
- );
581
- });
664
+ workerSetupComplete().then(() => {
665
+ cli.runApp(new ServerOptions({
666
+ agent: resolveWorkerEntryPath(options.entry),
667
+ agentName: options.agentName ?? "mastra-voice",
668
+ ...options.serverOptions
669
+ }));
670
+ });
582
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 };
583
674
 
584
- export { DEFAULT_END_CALL_DRAIN_MS, DEFAULT_END_CALL_MAX_WAIT_MS, DEFAULT_END_CALL_REASON, DEFAULT_END_CALL_TOOL, createLiveKitWorker, runEndCall, runLiveKitWorker, speakGreeting, waitForAgentDoneSpeaking };
585
- //# sourceMappingURL=worker-entry.js.map
586
675
  //# sourceMappingURL=worker-entry.js.map