@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
package/dist/index.js ADDED
@@ -0,0 +1,281 @@
1
+ import { a as DEFAULT_LIVEKIT_AGENT_NAME, i as serializeSessionMetadata, n as pipeAgentReplyToWriter } from "./workflow-generator-5nHqlZV7.js";
2
+ import { RoomAgentDispatch, RoomConfiguration } from "@livekit/protocol";
3
+ import { AccessToken, AgentDispatchClient, RoomEgress, RoomServiceClient } from "livekit-server-sdk";
4
+ import { z } from "zod/v4";
5
+ import { createTool } from "@mastra/core/tools";
6
+ import { z as z$1 } from "zod";
7
+ //#region src/recording.ts
8
+ /** A recording-enabled session cannot reuse an existing LiveKit room. */
9
+ var LiveKitRecordingRoomConflictError = class extends Error {
10
+ roomName;
11
+ constructor(roomName) {
12
+ super(`@mastra/livekit: recording requires a new room, but room "${roomName}" already exists. Use a fresh room name.`);
13
+ this.name = "LiveKitRecordingRoomConflictError";
14
+ this.roomName = roomName;
15
+ }
16
+ };
17
+ /** Creates a fresh room with recording configured before any agent or caller joins. */
18
+ async function createRecordingRoom(options) {
19
+ const { recording, roomName } = options;
20
+ if (!recording.room && !recording.participant && !recording.tracks) throw new Error("@mastra/livekit: recording must configure at least one of room, participant, or tracks.");
21
+ const client = new RoomServiceClient(options.serverUrl.replace(/^ws/, "http"), options.apiKey, options.apiSecret);
22
+ if ((await client.listRooms([roomName])).length > 0) throw new LiveKitRecordingRoomConflictError(roomName);
23
+ return client.createRoom({
24
+ name: roomName,
25
+ egress: new RoomEgress(recording)
26
+ });
27
+ }
28
+ //#endregion
29
+ //#region src/dispatch.ts
30
+ function toHttpUrl(url) {
31
+ return url.replace(/^ws/, "http");
32
+ }
33
+ /**
34
+ * Programmatically dispatches a Mastra voice agent into a LiveKit room — for
35
+ * server-initiated sessions such as outbound calls or joining an existing room.
36
+ */
37
+ async function dispatchVoiceSession(options) {
38
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
39
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
40
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
41
+ if (!serverUrl) throw new Error("@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.");
42
+ if (!apiKey || !apiSecret) throw new Error("@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.");
43
+ const metadata = serializeSessionMetadata(options.metadata ?? {});
44
+ if (options.recording !== void 0) await createRecordingRoom({
45
+ roomName: options.roomName,
46
+ serverUrl,
47
+ apiKey,
48
+ apiSecret,
49
+ recording: options.recording
50
+ });
51
+ return new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret).createDispatch(options.roomName, options.agentName ?? "mastra-voice", { metadata });
52
+ }
53
+ //#endregion
54
+ //#region src/routes.ts
55
+ function stringField(body, key) {
56
+ const value = body[key];
57
+ return typeof value === "string" && value.length > 0 ? value : void 0;
58
+ }
59
+ /**
60
+ * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra
61
+ * voice agent dispatched into the room. Frontends call it to join a voice session:
62
+ *
63
+ * ```ts
64
+ * export const mastra = new Mastra({
65
+ * agents: { support },
66
+ * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },
67
+ * });
68
+ * ```
69
+ */
70
+ function liveKitConnectionRoute(options = {}) {
71
+ const handler = async (c) => {
72
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
73
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
74
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
75
+ if (!serverUrl || !apiKey || !apiSecret) return c.json({ error: "LiveKit is not configured. Set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET (or pass serverUrl/apiKey/apiSecret to liveKitConnectionRoute)." }, 500);
76
+ const body = await c.req.json().then((parsed) => parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}).catch(() => ({}));
77
+ const args = {
78
+ body,
79
+ context: c
80
+ };
81
+ const metadata = options.metadata ? await options.metadata(args) : {
82
+ agentId: stringField(body, "agentId"),
83
+ threadId: stringField(body, "threadId"),
84
+ resourceId: stringField(body, "resourceId")
85
+ };
86
+ const roomName = typeof options.roomName === "function" ? options.roomName(args) : options.roomName ?? `mastra-voice-${globalThis.crypto.randomUUID().slice(0, 8)}`;
87
+ const identity = typeof options.participantIdentity === "function" ? options.participantIdentity(args) : options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`;
88
+ metadata.threadId ??= roomName;
89
+ const recording = typeof options.recording === "function" ? await options.recording({
90
+ ...args,
91
+ roomName
92
+ }) : options.recording;
93
+ if (recording !== void 0) try {
94
+ await dispatchVoiceSession({
95
+ roomName,
96
+ agentName: options.agentName,
97
+ metadata,
98
+ serverUrl,
99
+ apiKey,
100
+ apiSecret,
101
+ recording
102
+ });
103
+ } catch (error) {
104
+ if (error instanceof LiveKitRecordingRoomConflictError) return c.json({ error: "Recording requires a new room. Use a unique roomName for each call." }, 409);
105
+ throw error;
106
+ }
107
+ const token = new AccessToken(apiKey, apiSecret, {
108
+ identity,
109
+ ttl: options.ttl ?? "15m"
110
+ });
111
+ token.addGrant({
112
+ room: roomName,
113
+ roomJoin: true,
114
+ canPublish: true,
115
+ canSubscribe: true,
116
+ canPublishData: true,
117
+ canUpdateOwnMetadata: true
118
+ });
119
+ if (recording === void 0) token.roomConfig = new RoomConfiguration({ agents: [new RoomAgentDispatch({
120
+ agentName: options.agentName ?? "mastra-voice",
121
+ metadata: serializeSessionMetadata(metadata)
122
+ })] });
123
+ const details = {
124
+ serverUrl,
125
+ roomName,
126
+ participantName: identity,
127
+ participantToken: await token.toJwt()
128
+ };
129
+ return c.json(details);
130
+ };
131
+ return {
132
+ path: options.path ?? "/voice/livekit/connection-details",
133
+ method: "POST",
134
+ requiresAuth: options.requiresAuth,
135
+ handler
136
+ };
137
+ }
138
+ //#endregion
139
+ //#region src/recording-route.ts
140
+ const traceIdSchema = z.string().min(1).max(256);
141
+ const recordingSchema = z.object({
142
+ url: z.url({ protocol: /^https?$/ }),
143
+ expiresAt: z.string().datetime().optional()
144
+ });
145
+ /** Resolves a voice call trace to a recording without persisting signed URLs in traces. */
146
+ function liveKitRecordingRoute(options) {
147
+ if (typeof options.authorize !== "function") throw new Error("liveKitRecordingRoute requires an authorize callback.");
148
+ return {
149
+ path: options.path ?? "/voice/livekit/recordings/:traceId",
150
+ method: "GET",
151
+ requiresAuth: options.requiresAuth ?? true,
152
+ handler: async (context) => {
153
+ context.header("Cache-Control", "no-store");
154
+ const input = traceIdSchema.safeParse(context.req.param("traceId"));
155
+ if (!input.success) return context.json({ error: "A valid trace ID is required." }, 400);
156
+ const traceId = input.data;
157
+ try {
158
+ if (await options.authorize({
159
+ traceId,
160
+ context
161
+ }) !== true) return context.json({ error: "Access to this recording is denied." }, 403);
162
+ const store = await context.get("mastra").getStorage()?.getStore("observability");
163
+ if (!store) return context.json({ error: "Trace storage is not configured." }, 503);
164
+ const calls = (await store.getTrace({ traceId }))?.spans.filter((span) => span.name === "voice call" && typeof span.metadata?.roomName === "string" && span.metadata.roomName.length > 0) ?? [];
165
+ if (!calls.length) return context.json({ error: "Voice call trace not found." }, 404);
166
+ if (calls.length !== 1) return context.json({ error: "This trace contains multiple voice calls." }, 409);
167
+ const span = calls[0];
168
+ const roomName = span.metadata?.roomName;
169
+ if (typeof roomName !== "string") return context.json({ error: "Voice call trace not found." }, 404);
170
+ const recording = await options.resolveRecording({
171
+ traceId,
172
+ roomName,
173
+ span,
174
+ context
175
+ });
176
+ if (!recording) return context.json({ status: "unavailable" });
177
+ const result = recordingSchema.safeParse(recording);
178
+ if (!result.success) return context.json({ error: "Unable to load the call recording." }, 502);
179
+ return context.json({
180
+ status: "ready",
181
+ ...result.data
182
+ });
183
+ } catch {
184
+ return context.json({ error: "Unable to load the call recording." }, 502);
185
+ }
186
+ }
187
+ };
188
+ }
189
+ //#endregion
190
+ //#region src/consent.ts
191
+ const DEFAULT_DESCRIPTION$1 = "Record the caller's consent decision for a data-processing item (for example, storing a summary of the call). Call this as soon as the caller answers a consent question: granted = true if they agree, false if they decline. Do not proceed with an activity that requires consent until you have recorded the caller granting it.";
192
+ /**
193
+ * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to
194
+ * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add
195
+ * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /
196
+ * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime
197
+ * grants live only where `onGrant` put them: enforce consent by reading them back from your own
198
+ * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared
199
+ * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the
200
+ * policy, never the grants).
201
+ *
202
+ * ```ts
203
+ * // agent tools
204
+ * recordConsent: createConsentTool({
205
+ * items: ['summaryStorage'],
206
+ * onGrant: async ({ item, granted, resourceId }) => {
207
+ * if (resourceId) await db.saveConsent(resourceId, item, granted);
208
+ * },
209
+ * }),
210
+ * ```
211
+ */
212
+ function createConsentTool(options) {
213
+ const items = options.items;
214
+ const itemSchema = items && items.length > 0 ? z$1.enum([...items]) : z$1.string();
215
+ return createTool({
216
+ id: options.id ?? "recordConsent",
217
+ description: options.description ?? DEFAULT_DESCRIPTION$1,
218
+ inputSchema: z$1.object({
219
+ item: itemSchema.describe("The consent item the caller is answering for (matches the deployment's required consents)."),
220
+ granted: z$1.boolean().describe("True if the caller agreed, false if they declined.")
221
+ }),
222
+ execute: async ({ item, granted }, { agent }) => {
223
+ await options.onGrant({
224
+ item,
225
+ granted,
226
+ resourceId: agent?.resourceId,
227
+ threadId: agent?.threadId
228
+ });
229
+ return {
230
+ recorded: true,
231
+ item,
232
+ granted
233
+ };
234
+ }
235
+ });
236
+ }
237
+ //#endregion
238
+ //#region src/end-call.ts
239
+ const DEFAULT_DESCRIPTION = "End the phone call. Call this only after you have said goodbye and there is nothing left to do — for example the caller says goodbye, or the task is complete and you have wrapped up. Say your closing line first, then call this as your final action; the call hangs up once your words finish playing. Your closing line must be a final statement, never a question — if you are asking the caller anything (for example whether they need anything else), do NOT call this in that reply; wait for their answer. Do not call it if the caller still needs something.";
240
+ /**
241
+ * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the
242
+ * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional
243
+ * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the
244
+ * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the
245
+ * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).
246
+ * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on
247
+ * the agent and workflow reply paths alike.
248
+ *
249
+ * ```ts
250
+ * // agent tools
251
+ * endCall: createEndCallTool({
252
+ * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),
253
+ * }),
254
+ * // worker
255
+ * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });
256
+ * ```
257
+ */
258
+ function createEndCallTool(options = {}) {
259
+ return createTool({
260
+ id: options.id ?? "endCall",
261
+ description: options.description ?? DEFAULT_DESCRIPTION,
262
+ inputSchema: z$1.object({ reason: z$1.string().nullish().describe("Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".") }),
263
+ outputSchema: z$1.object({ ended: z$1.boolean() }),
264
+ execute: async ({ reason }, { agent }) => {
265
+ try {
266
+ await options.onEndCall?.({
267
+ reason: reason ?? void 0,
268
+ resourceId: agent?.resourceId,
269
+ threadId: agent?.threadId
270
+ });
271
+ } catch (error) {
272
+ console.warn("@mastra/livekit: onEndCall hook threw", error);
273
+ }
274
+ return { ended: true };
275
+ }
276
+ });
277
+ }
278
+ //#endregion
279
+ export { DEFAULT_LIVEKIT_AGENT_NAME, LiveKitRecordingRoomConflictError, createConsentTool, createEndCallTool, dispatchVoiceSession, liveKitConnectionRoute, liveKitRecordingRoute, pipeAgentReplyToWriter, serializeSessionMetadata };
280
+
281
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["DEFAULT_DESCRIPTION","z","z"],"sources":["../src/recording.ts","../src/dispatch.ts","../src/routes.ts","../src/recording-route.ts","../src/consent.ts","../src/end-call.ts"],"sourcesContent":["import { RoomEgress, RoomServiceClient } from 'livekit-server-sdk';\n\n/**\n * LiveKit auto-egress settings, accepted as a plain object or a RoomEgress instance.\n * Use `room.audioOnly` and `room.fileOutputs` for a single mixed audio recording.\n * Storage credentials belong here on the server, never in session metadata or tokens.\n */\nexport type LiveKitRecordingOptions = NonNullable<ConstructorParameters<typeof RoomEgress>[0]>;\n\n/** A recording-enabled session cannot reuse an existing LiveKit room. */\nexport class LiveKitRecordingRoomConflictError extends Error {\n readonly roomName: string;\n\n constructor(roomName: string) {\n super(\n `@mastra/livekit: recording requires a new room, but room \"${roomName}\" already exists. Use a fresh room name.`,\n );\n this.name = 'LiveKitRecordingRoomConflictError';\n this.roomName = roomName;\n }\n}\n\n/** Creates a fresh room with recording configured before any agent or caller joins. */\nexport async function createRecordingRoom(options: {\n roomName: string;\n serverUrl: string;\n apiKey: string;\n apiSecret: string;\n recording: LiveKitRecordingOptions;\n}) {\n const { recording, roomName } = options;\n if (!recording.room && !recording.participant && !recording.tracks) {\n throw new Error('@mastra/livekit: recording must configure at least one of room, participant, or tracks.');\n }\n\n const client = new RoomServiceClient(options.serverUrl.replace(/^ws/, 'http'), options.apiKey, options.apiSecret);\n // CreateRoom reuses existing rooms without applying room-composite auto-egress.\n // This preflight is not atomic: callers must use a fresh name and serialize room creation.\n const rooms = await client.listRooms([roomName]);\n if (rooms.length > 0) {\n throw new LiveKitRecordingRoomConflictError(roomName);\n }\n\n return client.createRoom({ name: roomName, egress: new RoomEgress(recording) });\n}\n","import { AgentDispatchClient } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { createRecordingRoom } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\nexport interface DispatchVoiceSessionOptions {\n /**\n * Room to dispatch the agent into (created on demand). With recording enabled, use a unique\n * name for each call. An existing room throws LiveKitRecordingRoomConflictError.\n */\n roomName: string;\n /** Must match the worker's `agentName`. Defaults to `'mastra-voice'`. */\n agentName?: string;\n metadata?: LiveKitSessionMetadata;\n /** Create a fresh room with automatic recording before dispatch. Omit to keep dispatch-only behavior. */\n recording?: LiveKitRecordingOptions;\n /** Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n}\n\nfunction toHttpUrl(url: string): string {\n return url.replace(/^ws/, 'http');\n}\n\n/**\n * Programmatically dispatches a Mastra voice agent into a LiveKit room — for\n * server-initiated sessions such as outbound calls or joining an existing room.\n */\nexport async function dispatchVoiceSession(options: DispatchVoiceSessionOptions) {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl) {\n throw new Error('@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.');\n }\n if (!apiKey || !apiSecret) {\n throw new Error(\n '@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.',\n );\n }\n const metadata = serializeSessionMetadata(options.metadata ?? {});\n if (options.recording !== undefined) {\n await createRecordingRoom({\n roomName: options.roomName,\n serverUrl,\n apiKey,\n apiSecret,\n recording: options.recording,\n });\n }\n const client = new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret);\n return client.createDispatch(options.roomName, options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME, {\n metadata,\n });\n}\n","import { RoomAgentDispatch, RoomConfiguration } from '@livekit/protocol';\nimport type { ContextWithMastra, ApiRoute } from '@mastra/core/server';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { dispatchVoiceSession } from './dispatch';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\nimport { LiveKitRecordingRoomConflictError } from './recording';\nimport type { LiveKitRecordingOptions } from './recording';\n\n/** Response body of the connection-details route. Matches LiveKit's frontend starter contract. */\nexport interface LiveKitConnectionDetails {\n serverUrl: string;\n roomName: string;\n participantName: string;\n participantToken: string;\n}\n\nexport interface ConnectionRequestArgs {\n body: Record<string, unknown>;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitConnectionRouteOptions {\n /**\n * Route path. Defaults to `/voice/livekit/connection-details`. Mastra reserves the\n * `/api` prefix for built-in routes, so custom paths must not start with `/api`.\n */\n path?: string;\n /** LiveKit server URL (`wss://...`). Defaults to `LIVEKIT_URL`. */\n serverUrl?: string;\n /** Defaults to `LIVEKIT_API_KEY`. */\n apiKey?: string;\n /** Defaults to `LIVEKIT_API_SECRET`. */\n apiSecret?: string;\n /** LiveKit agent name for explicit dispatch. Must match the worker's `agentName`. */\n agentName?: string;\n /** Token time-to-live. Defaults to `'15m'`. */\n ttl?: string | number;\n /** Defaults to `true` (Mastra custom routes require auth unless opted out). */\n requiresAuth?: boolean;\n /**\n * Room name or a function that derives one from the request. Defaults to a generated name.\n * With recording enabled, use a unique name for each call. An existing room returns HTTP 409\n * before agent dispatch or token issuance.\n */\n roomName?: string | ((args: ConnectionRequestArgs) => string);\n participantIdentity?: string | ((args: ConnectionRequestArgs) => string);\n /**\n * Session metadata delivered to the worker via agent dispatch. Defaults to passing\n * through `agentId`, `threadId`, and `resourceId` from the request body.\n */\n metadata?: (args: ConnectionRequestArgs) => LiveKitSessionMetadata | Promise<LiveKitSessionMetadata>;\n /**\n * Create a fresh room with automatic recording and dispatch the agent before returning a token.\n * The server-side callback receives the resolved room name; return undefined to skip recording.\n * Recording settings and storage credentials are never included in the participant token.\n */\n recording?:\n | LiveKitRecordingOptions\n | ((\n args: ConnectionRequestArgs & { roomName: string },\n ) => LiveKitRecordingOptions | undefined | Promise<LiveKitRecordingOptions | undefined>);\n}\n\nfunction stringField(body: Record<string, unknown>, key: string): string | undefined {\n const value = body[key];\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\n/**\n * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra\n * voice agent dispatched into the room. Frontends call it to join a voice session:\n *\n * ```ts\n * export const mastra = new Mastra({\n * agents: { support },\n * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },\n * });\n * ```\n */\nexport function liveKitConnectionRoute(options: LiveKitConnectionRouteOptions = {}): ApiRoute {\n const handler = async (c: ContextWithMastra) => {\n const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;\n const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;\n const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;\n if (!serverUrl || !apiKey || !apiSecret) {\n return c.json(\n {\n error:\n 'LiveKit is not configured. Set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET ' +\n '(or pass serverUrl/apiKey/apiSecret to liveKitConnectionRoute).',\n },\n 500,\n );\n }\n\n const body: Record<string, unknown> = await c.req\n .json()\n .then((parsed: unknown) =>\n parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {},\n )\n .catch(() => ({}));\n const args: ConnectionRequestArgs = { body, context: c };\n\n const metadata: LiveKitSessionMetadata = options.metadata\n ? await options.metadata(args)\n : {\n agentId: stringField(body, 'agentId'),\n threadId: stringField(body, 'threadId'),\n resourceId: stringField(body, 'resourceId'),\n };\n\n const roomName =\n typeof options.roomName === 'function'\n ? options.roomName(args)\n : (options.roomName ?? `mastra-voice-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n const identity =\n typeof options.participantIdentity === 'function'\n ? options.participantIdentity(args)\n : (options.participantIdentity ?? metadata.resourceId ?? `user-${globalThis.crypto.randomUUID().slice(0, 8)}`);\n // One memory thread per room unless the caller pins a thread explicitly.\n metadata.threadId ??= roomName;\n\n const recording =\n typeof options.recording === 'function' ? await options.recording({ ...args, roomName }) : options.recording;\n if (recording !== undefined) {\n try {\n await dispatchVoiceSession({\n roomName,\n agentName: options.agentName,\n metadata,\n serverUrl,\n apiKey,\n apiSecret,\n recording,\n });\n } catch (error) {\n if (error instanceof LiveKitRecordingRoomConflictError) {\n return c.json({ error: 'Recording requires a new room. Use a unique roomName for each call.' }, 409);\n }\n throw error;\n }\n }\n\n const token = new AccessToken(apiKey, apiSecret, { identity, ttl: options.ttl ?? '15m' });\n token.addGrant({\n room: roomName,\n roomJoin: true,\n canPublish: true,\n canSubscribe: true,\n canPublishData: true,\n canUpdateOwnMetadata: true,\n });\n // A pre-created room needs explicit dispatch; token roomConfig only applies at room creation.\n if (recording === undefined) {\n token.roomConfig = new RoomConfiguration({\n agents: [\n new RoomAgentDispatch({\n agentName: options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME,\n metadata: serializeSessionMetadata(metadata),\n }),\n ],\n });\n }\n\n const details: LiveKitConnectionDetails = {\n serverUrl,\n roomName,\n participantName: identity,\n participantToken: await token.toJwt(),\n };\n return c.json(details);\n };\n\n return {\n // Studio calls this default path and /api/system/packages reports it — change all three together.\n path: options.path ?? '/voice/livekit/connection-details',\n method: 'POST',\n requiresAuth: options.requiresAuth,\n handler,\n } as ApiRoute;\n}\n","import type { ApiRoute, ContextWithMastra } from '@mastra/core/server';\nimport type { SpanRecord } from '@mastra/core/storage';\nimport { z } from 'zod/v4';\nimport type { LiveKitRecording, LiveKitRecordingResponse } from './recording-types';\n\nconst traceIdSchema = z.string().min(1).max(256);\nexport const recordingSchema = z.object({\n url: z.url({ protocol: /^https?$/ }),\n expiresAt: z.string().datetime().optional(),\n}) satisfies z.ZodType<LiveKitRecording>;\n\nexport interface LiveKitRecordingResolverArgs {\n traceId: string;\n /** Taken from the stored voice call span, never from the browser request. */\n roomName: string;\n span: SpanRecord;\n context: ContextWithMastra;\n}\n\nexport interface LiveKitRecordingRouteOptions {\n /** Studio discovers this route at its default path: /voice/livekit/recordings/:traceId. */\n path?: string;\n /** Defaults to true. Only disable for a local demo. */\n requiresAuth?: boolean;\n /** Required trace-specific access policy. Only true permits trace lookup and URL resolution. */\n authorize: (args: { traceId: string; context: ContextWithMastra }) => boolean | Promise<boolean>;\n /** Return a playable URL, or undefined if the recording is not available yet. */\n resolveRecording: (args: LiveKitRecordingResolverArgs) => Promise<LiveKitRecording | undefined>;\n}\n\n/** Resolves a voice call trace to a recording without persisting signed URLs in traces. */\nexport function liveKitRecordingRoute(options: LiveKitRecordingRouteOptions): ApiRoute {\n if (typeof options.authorize !== 'function') {\n throw new Error('liveKitRecordingRoute requires an authorize callback.');\n }\n return {\n path: options.path ?? '/voice/livekit/recordings/:traceId',\n method: 'GET',\n requiresAuth: options.requiresAuth ?? true,\n handler: async (context: ContextWithMastra) => {\n context.header('Cache-Control', 'no-store');\n const input = traceIdSchema.safeParse(context.req.param('traceId'));\n if (!input.success) return context.json({ error: 'A valid trace ID is required.' }, 400);\n const traceId = input.data;\n try {\n if ((await options.authorize({ traceId, context })) !== true) {\n return context.json({ error: 'Access to this recording is denied.' }, 403);\n }\n const store = await context.get('mastra').getStorage()?.getStore('observability');\n if (!store) return context.json({ error: 'Trace storage is not configured.' }, 503);\n const trace = await store.getTrace({ traceId });\n const calls =\n trace?.spans.filter(\n span =>\n span.name === 'voice call' &&\n typeof span.metadata?.roomName === 'string' &&\n span.metadata.roomName.length > 0,\n ) ?? [];\n if (!calls.length) return context.json({ error: 'Voice call trace not found.' }, 404);\n if (calls.length !== 1) return context.json({ error: 'This trace contains multiple voice calls.' }, 409);\n const span = calls[0]!;\n const roomName = span.metadata?.roomName;\n if (typeof roomName !== 'string') return context.json({ error: 'Voice call trace not found.' }, 404);\n const recording = await options.resolveRecording({ traceId, roomName, span, context });\n if (!recording) return context.json({ status: 'unavailable' } satisfies LiveKitRecordingResponse);\n // Validate and strip extra fields so storage credentials cannot accidentally become response fields.\n const result = recordingSchema.safeParse(recording);\n if (!result.success) return context.json({ error: 'Unable to load the call recording.' }, 502);\n return context.json({ status: 'ready', ...result.data } satisfies LiveKitRecordingResponse);\n } catch {\n // Storage/provider errors can contain credentials or signed request details.\n return context.json({ error: 'Unable to load the call recording.' }, 502);\n }\n },\n };\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** A consent decision captured from the caller during a call. */\nexport interface ConsentGrant {\n /**\n * The consent item, matching a key in the worker's `configuration.consentPolicy` (e.g.\n * `'summaryStorage'`).\n */\n item: string;\n /** `true` if the caller agreed, `false` if they declined. */\n granted: boolean;\n /** The caller the grant belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread the grant was captured on, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface ConsentToolOptions {\n /**\n * Persist the caller's decision to YOUR system of record (database, CRM, consent ledger). Called\n * each time the caller answers a consent question — keep it quick, it runs inside the turn. This\n * tool owns extracting the caller's identity from the tool execution context; you own storage, so\n * consent lives in a durable, compliant place rather than an opaque plugin store. Read those\n * grants back at `onCallEnd` (or before any consent-gated step) to enforce the requirement.\n */\n onGrant: (grant: ConsentGrant) => void | Promise<void>;\n /** Tool id the agent calls. Defaults to `'recordConsent'`. */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /** Restrict the accepted consent items to this set (becomes an enum). Defaults to any string. */\n items?: readonly string[];\n}\n\nconst DEFAULT_DESCRIPTION =\n \"Record the caller's consent decision for a data-processing item (for example, storing a summary \" +\n 'of the call). Call this as soon as the caller answers a consent question: granted = true if they ' +\n 'agree, false if they decline. Do not proceed with an activity that requires consent until you ' +\n 'have recorded the caller granting it.';\n\n/**\n * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to\n * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add\n * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /\n * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime\n * grants live only where `onGrant` put them: enforce consent by reading them back from your own\n * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared\n * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the\n * policy, never the grants).\n *\n * ```ts\n * // agent tools\n * recordConsent: createConsentTool({\n * items: ['summaryStorage'],\n * onGrant: async ({ item, granted, resourceId }) => {\n * if (resourceId) await db.saveConsent(resourceId, item, granted);\n * },\n * }),\n * ```\n */\nexport function createConsentTool(options: ConsentToolOptions) {\n const items = options.items;\n const itemSchema = items && items.length > 0 ? z.enum([...items] as [string, ...string[]]) : z.string();\n return createTool({\n id: options.id ?? 'recordConsent',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n item: itemSchema.describe(\n \"The consent item the caller is answering for (matches the deployment's required consents).\",\n ),\n granted: z.boolean().describe('True if the caller agreed, false if they declined.'),\n }),\n execute: async ({ item, granted }, { agent }) => {\n await options.onGrant({ item, granted, resourceId: agent?.resourceId, threadId: agent?.threadId });\n return { recorded: true as const, item, granted };\n },\n });\n}\n","// Server-safe: only depends on `@mastra/core` + zod, never the `@livekit/agents` runtime — so it\n// can be added to agents defined in server/shared code and re-exported from the root entry\n// (`index.ts`). `index.test.ts` enforces that boundary.\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\n/** Details of the agent's decision to end the call, handed to {@link EndCallToolOptions.onEndCall}. */\nexport interface EndCallRequest {\n /** Short reason the agent gave for ending the call, if any (e.g. \"caller said goodbye\"). */\n reason?: string;\n /** The caller the call belongs to (the memory `resource`), when the call is memory-scoped. */\n resourceId?: string;\n /** The call thread, when the call is memory-scoped. */\n threadId?: string;\n}\n\nexport interface EndCallToolOptions {\n /**\n * Tool id the agent calls to end the call. Must match the worker's\n * `configuration.endCall.tool` (both default to `'endCall'`), since that's the name the worker\n * watches for to hang up.\n */\n id?: string;\n /** Override the description the model sees when deciding to call the tool. */\n description?: string;\n /**\n * Optional bookkeeping hook, called when the agent invokes the tool (records the reason, marks\n * the call resolved in your CRM, …). Runs inside the turn — keep it quick. It does NOT hang up\n * the call; the worker does that once the agent's final words finish playing. The tool reads the\n * caller's identity from its execution context and passes it here.\n */\n onEndCall?: (request: EndCallRequest) => void | Promise<void>;\n}\n\nconst DEFAULT_DESCRIPTION =\n 'End the phone call. Call this only after you have said goodbye and there is nothing left to do — ' +\n 'for example the caller says goodbye, or the task is complete and you have wrapped up. Say your ' +\n 'closing line first, then call this as your final action; the call hangs up once your words finish ' +\n 'playing. Your closing line must be a final statement, never a question — if you are asking the ' +\n 'caller anything (for example whether they need anything else), do NOT call this in that reply; ' +\n 'wait for their answer. Do not call it if the caller still needs something.';\n\n/**\n * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the\n * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional\n * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the\n * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the\n * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).\n * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on\n * the agent and workflow reply paths alike.\n *\n * ```ts\n * // agent tools\n * endCall: createEndCallTool({\n * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),\n * }),\n * // worker\n * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });\n * ```\n */\nexport function createEndCallTool(options: EndCallToolOptions = {}) {\n return createTool({\n id: options.id ?? 'endCall',\n description: options.description ?? DEFAULT_DESCRIPTION,\n inputSchema: z.object({\n reason: z\n .string()\n .nullish()\n .describe('Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".'),\n }),\n outputSchema: z.object({ ended: z.boolean() }),\n execute: async ({ reason }, { agent }) => {\n try {\n await options.onEndCall?.({\n reason: reason ?? undefined,\n resourceId: agent?.resourceId,\n threadId: agent?.threadId,\n });\n } catch (error) {\n // Bookkeeping is best-effort — the tool must still signal `{ ended: true }` so the worker's\n // end-call detector runs and the call actually hangs up.\n console.warn('@mastra/livekit: onEndCall hook threw', error);\n }\n return { ended: true as const };\n },\n });\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,oCAAb,cAAuD,MAAM;CAC3D;CAEA,YAAY,UAAkB;EAC5B,MACE,6DAA6D,SAAS,yCACxE;EACA,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;AAGA,eAAsB,oBAAoB,SAMvC;CACD,MAAM,EAAE,WAAW,aAAa;CAChC,IAAI,CAAC,UAAU,QAAQ,CAAC,UAAU,eAAe,CAAC,UAAU,QAC1D,MAAM,IAAI,MAAM,yFAAyF;CAG3G,MAAM,SAAS,IAAI,kBAAkB,QAAQ,UAAU,QAAQ,OAAO,MAAM,GAAG,QAAQ,QAAQ,QAAQ,SAAS;CAIhH,KAAI,MADgB,OAAO,UAAU,CAAC,QAAQ,CAAC,EAAA,CACrC,SAAS,GACjB,MAAM,IAAI,kCAAkC,QAAQ;CAGtD,OAAO,OAAO,WAAW;EAAE,MAAM;EAAU,QAAQ,IAAI,WAAW,SAAS;CAAE,CAAC;AAChF;;;AClBA,SAAS,UAAU,KAAqB;CACtC,OAAO,IAAI,QAAQ,OAAO,MAAM;AAClC;;;;;AAMA,eAAsB,qBAAqB,SAAsC;CAC/E,MAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;CACnD,MAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;CAC7C,MAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;CACnD,I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AgB,kBAAkB,UAA8B,CAAC,GAAG;CAClE,OAAO,WAAW;EAChB,IAAI,QAAQ,MAAM;EAClB,aAAa,QAAQ,eAAe;EACpC,aAAaC,IAAE,OAAO,EACpB,QAAQA,IACL,OAAO,CAAC,CACR,QAAQ,CAAC,CACT,SAAS,qFAAiF,EAC/F,CAAC;EACD,cAAcA,IAAE,OAAO,EAAE,OAAOA,IAAE,QAAQ,EAAE,CAAC;EAC7C,SAAS,OAAO,EAAE,UAAU,EAAE,YAAY;GACxC,IAAI;IACF,MAAM,QAAQ,YAAY;KACxB,QAAQ,UAAU,KAAA;KAClB,YAAY,OAAO;KACnB,UAAU,OAAO;IACnB,CAAC;GACH,SAAS,OAAO;IAGd,QAAQ,KAAK,yCAAyC,KAAK;GAC7D;GACA,OAAO,EAAE,OAAO,KAAc;EAChC;CACF,CAAC;AACH"}
@@ -0,0 +1,117 @@
1
+ import { llm } from '@livekit/agents';
2
+ import type { APIConnectOptions } from '@livekit/agents';
3
+ import type { Agent as MastraAgent } from '@mastra/core/agent';
4
+ import { RequestContext } from '@mastra/core/request-context';
5
+ import type { MastraVoiceAgentMemory, VoiceReplyGenerator, VoiceToolCall, VoiceTurnCompleteHook } from './bridge.js';
6
+ import type { RemoteMastraAgentOptions } from './remote.js';
7
+ import type { VoiceTurnMetricsHook } from './turn-metrics.js';
8
+ export type { RemoteMastraAgentOptions } from './remote.js';
9
+ /**
10
+ * Options for {@link MastraLLM}. Provide **exactly one** reply source — `remote` (the headline: a
11
+ * Mastra app on a remote server), `agent` (an in-process Mastra agent), or `generate` (a custom
12
+ * {@link VoiceReplyGenerator}). The `toolFeedback` / `onToolCall` / `onTurnComplete` hooks apply to
13
+ * the `remote` and `agent` sources; a `generate` source owns its own hooks.
14
+ */
15
+ export interface MastraLLMOptions {
16
+ /** Per-attempt metrics; use observeVoiceSession for playback metrics. */
17
+ onTurnMetrics?: VoiceTurnMetricsHook;
18
+ /** Remote Mastra server. Provide exactly one of `remote`, `agent`, `generate`. */
19
+ remote?: RemoteMastraAgentOptions;
20
+ /** In-process Mastra agent (reuses `createAgentReplyGenerator`). */
21
+ agent?: MastraAgent;
22
+ /** Custom reply source (escape hatch; owns its own tool-feedback / turn-complete behavior). */
23
+ generate?: VoiceReplyGenerator;
24
+ /**
25
+ * Conversation persistence, resolved by the customer per call (from SIP/caller identity). When set,
26
+ * only messages new since the agent last spoke are sent each turn and Mastra Memory supplies
27
+ * history. When omitted/false, the full LiveKit chat context is sent every turn.
28
+ *
29
+ * NOTE: incompatible with the session's `preemptiveGeneration` option — a speculative turn
30
+ * persists a partial user message and a partial reply before being discarded. Leave preemptive
31
+ * generation off when using `memory`, or set `memory.options.readOnly` and persist committed
32
+ * turns yourself from the session's conversation-item events.
33
+ *
34
+ * The plugin cannot detect the combination at runtime, so this stays a documented constraint
35
+ * rather than a warning: the LLM interface never receives the session (so the option can't be
36
+ * read), a preemptive `chat()` is shape-identical to a real turn (LiveKit drives the same
37
+ * `generateReply` with a draft transcript and no marker), and the observable signature — a
38
+ * cancelled stream followed by a `chat()` whose trailing user message changed — is exactly what
39
+ * an ordinary barge-in correction looks like, so a heuristic would warn on every barge-in.
40
+ */
41
+ memory?: MastraVoiceAgentMemory | false;
42
+ /** Request context forwarded to generation (tenant, dialed number, ...). */
43
+ requestContext?: RequestContext | Record<string, unknown>;
44
+ /** Speak a short filler while a (server-side) tool runs. Applies to the `remote`/`agent` sources. */
45
+ toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;
46
+ /** Notified as each tool-call chunk arrives, mid-stream. Applies to the `remote`/`agent` sources. */
47
+ onToolCall?: (toolCall: VoiceToolCall) => void;
48
+ /** Fired off the audio path after each reply finishes. Applies to the `remote`/`agent` sources. */
49
+ onTurnComplete?: VoiceTurnCompleteHook;
50
+ }
51
+ /**
52
+ * A standard LiveKit LLM plugin (`llm.LLM`) backed by a Mastra agent. Drop it into the `llm` slot of a
53
+ * customer-owned `voice.AgentSession` and the Mastra app (agent loop, tools, memory, observability)
54
+ * runs wherever it's deployed — most importantly on a **remote** Mastra server reached over HTTP.
55
+ *
56
+ * Tools are defined and executed **server-side** on the Mastra agent; LiveKit-side `toolCtx` is
57
+ * ignored (with a one-time warning). Tool activity surfaces via `toolFeedback` (spoken) and
58
+ * `onToolCall` / `onTurnComplete` (programmatic). `voice.Agent` instructions do **not** reach the
59
+ * Mastra agent — put instructions on the Mastra agent instead.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const session = new voice.AgentSession({
64
+ * stt: 'deepgram/nova-3',
65
+ * tts: 'cartesia/sonic-3',
66
+ * llm: new MastraLLM({
67
+ * remote: { baseUrl: process.env.MASTRA_URL!, agentId: 'callCenter' },
68
+ * memory: { thread: callId, resource: callerId },
69
+ * }),
70
+ * });
71
+ * ```
72
+ */
73
+ export declare class MastraLLM extends llm.LLM {
74
+ #private;
75
+ constructor(options: MastraLLMOptions);
76
+ label(): string;
77
+ get model(): string;
78
+ get provider(): string;
79
+ /**
80
+ * Resolves the reply generator for a turn. Non-remote sources are built once; the remote transport
81
+ * is built per turn so its connect + first-token timeout can come from the session's
82
+ * `connOptions.timeoutMs`, with base-class retries owning retry (transport `retries: 0`).
83
+ */
84
+ private resolveGenerator;
85
+ chat({ chatCtx, toolCtx, connOptions, }: {
86
+ chatCtx: llm.ChatContext;
87
+ toolCtx?: llm.ToolContext;
88
+ connOptions?: APIConnectOptions;
89
+ parallelToolCalls?: boolean;
90
+ toolChoice?: llm.ToolChoice;
91
+ extraKwargs?: Record<string, unknown>;
92
+ }): llm.LLMStream;
93
+ /** No-op in v1: nothing in the LiveKit session/worker ever calls `prewarm()` automatically. */
94
+ prewarm(): void;
95
+ }
96
+ interface MastraLLMStreamOptions {
97
+ onTurnMetrics?: VoiceTurnMetricsHook;
98
+ chatCtx: llm.ChatContext;
99
+ toolCtx?: llm.ToolContext;
100
+ connOptions: APIConnectOptions;
101
+ generator: VoiceReplyGenerator;
102
+ memory: MastraVoiceAgentMemory | false;
103
+ requestContext?: RequestContext;
104
+ }
105
+ /**
106
+ * The `llm.LLMStream` `MastraLLM` returns per turn. `run()` extracts the turn's messages, drives
107
+ * the reply generator, and pushes assistant `ChatChunk`s into `this.queue` (NOT `this.output` — the
108
+ * base class drains queue → output and computes TTFT / duration / usage). Barge-in aborts via
109
+ * `this.abortController` and `run()` returns silently.
110
+ */
111
+ declare class MastraLLMStream extends llm.LLMStream {
112
+ #private;
113
+ constructor(mastraLLM: MastraLLM, options: MastraLLMStreamOptions);
114
+ protected run(): Promise<void>;
115
+ }
116
+ export { MastraLLMStream };
117
+ //# sourceMappingURL=llm-plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"llm-plugin.d.ts","sourceRoot":"","sources":["../src/llm-plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,GAAG,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,KAAK,EAAE,KAAK,IAAI,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EACV,sBAAsB,EACtB,mBAAmB,EACnB,aAAa,EACb,qBAAqB,EAGtB,MAAM,UAAU,CAAC;AAGlB,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAG3D,YAAY,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,yEAAyE;IACzE,aAAa,CAAC,EAAE,oBAAoB,CAAC;IACrC,kFAAkF;IAClF,MAAM,CAAC,EAAE,wBAAwB,CAAC;IAClC,oEAAoE;IACpE,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,+FAA+F;IAC/F,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAE/B;;;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O,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC;IAC1B,WAAW,EAAE,iBAAiB,CAAC;IAC/B,SAAS,EAAE,mBAAmB,CAAC;IAC/B,MAAM,EAAE,sBAAsB,GAAG,KAAK,CAAC;IACvC,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAED;;;;;GAKG;AACH,cAAM,eAAgB,SAAQ,GAAG,CAAC,SAAS;;IAMzC,YAAY,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,sBAAsB,EAMhE;IAED,UAAgB,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAuDnC;CACF;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
@@ -0,0 +1,50 @@
1
+ import type { llm } from '@livekit/agents';
2
+ /**
3
+ * Fixed id LiveKit gives the customer Agent's instructions when it injects them as a leading
4
+ * `role: 'system'` message into the chat context passed to `chat()` / `llmNode`. We drop this
5
+ * item so the server-side Mastra agent's own system prompt is authoritative.
6
+ */
7
+ export declare const LIVEKIT_INSTRUCTIONS_MESSAGE_ID = "lk.agent_task.instructions";
8
+ /**
9
+ * A message bound for `agent.stream(...)` (in-process) or the Mastra server stream route (remote).
10
+ * `id` carries the LiveKit `ChatMessage.id` so the server can dedupe/upsert by id — making
11
+ * base-class retries, preemptive double-sends, and the interrupted-turn reconciliation recipe idempotent.
12
+ */
13
+ export type VoiceTurnMessage = {
14
+ role: 'system';
15
+ content: string;
16
+ id?: string;
17
+ } | {
18
+ role: 'user';
19
+ content: string;
20
+ id?: string;
21
+ } | {
22
+ role: 'assistant';
23
+ content: string;
24
+ id?: string;
25
+ };
26
+ /**
27
+ * Extracts only the messages added since the agent last spoke. Used when Mastra Memory is
28
+ * the source of truth for conversation history: prior turns are already persisted in the
29
+ * thread, so re-sending them would duplicate history.
30
+ *
31
+ * Two extensions over the naive "slice after the last assistant message":
32
+ *
33
+ * - **Interrupted-turn self-heal:** when the last assistant message was cut off by barge-in
34
+ * (`interrupted: true`), the server never persisted it — aborted runs skip persistence — so
35
+ * its heard-only text is missing from the thread. Re-send that fragment (ordered first) this
36
+ * turn to backfill it. It stops being "the last assistant message" once a full reply lands,
37
+ * so each interrupted fragment is sent exactly once, on the following turn.
38
+ * - **Instructions filter:** LiveKit injects the customer Agent's `instructions` as a
39
+ * leading `system` message ({@link LIVEKIT_INSTRUCTIONS_MESSAGE_ID}); the server-side Mastra
40
+ * agent owns its own system prompt, so drop it (it would otherwise ship on the first turn,
41
+ * before any assistant message).
42
+ */
43
+ export declare function extractNewTurnMessages(chatCtx: llm.ChatContext): VoiceTurnMessage[];
44
+ /**
45
+ * Converts the full LiveKit chat context to Mastra messages. Used when the bridge runs
46
+ * without Mastra Memory and LiveKit's in-session context is the only history. The agent's
47
+ * LiveKit-level instructions are excluded — the Mastra agent applies its own instructions.
48
+ */
49
+ export declare function chatContextToMessages(chatCtx: llm.ChatContext): VoiceTurnMessage[];
50
+ //# sourceMappingURL=messages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,+BAA+B,CAAC;AAE5E;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,GAChD;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,GAC9C;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AA2BxD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,GAAG,CAAC,WAAW,GAAG,gBAAgB,EAAE,CAuBnF;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,GAAG,CAAC,WAAW,GAAG,gBAAgB,EAAE,CAQlF"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Session metadata passed from the Mastra server to the LiveKit agent worker through
3
+ * LiveKit's job dispatch metadata (a plain string, so this is JSON-serialized).
4
+ */
5
+ export interface LiveKitSessionMetadata {
6
+ /** Mastra agent to run, by registered key or agent id. */
7
+ agentId?: string;
8
+ /** Memory thread id. Defaults to the LiveKit room name when omitted. */
9
+ threadId?: string;
10
+ /** Memory resource id (typically the end user id). */
11
+ resourceId?: string;
12
+ /** Plain-object entries restored into a RequestContext for agent execution. */
13
+ requestContext?: Record<string, unknown>;
14
+ }
15
+ export declare function parseSessionMetadata(raw: string | undefined | null): LiveKitSessionMetadata;
16
+ export declare function serializeSessionMetadata(metadata: LiveKitSessionMetadata): string;
17
+ //# sourceMappingURL=metadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACrC,0DAA0D;IAC1D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sDAAsD;IACtD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,sBAAsB,CAW3F;AAED,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,sBAAsB,GAAG,MAAM,CAEjF"}
@@ -0,0 +1,49 @@
1
+ import { voice } from '@livekit/agents';
2
+ import type { Mastra } from '@mastra/core/mastra';
3
+ import { SpanType } from '@mastra/core/observability';
4
+ import type { Span, TracingContext } from '@mastra/core/observability';
5
+ import type { RequestContext } from '@mastra/core/request-context';
6
+ import type { LiveKitSessionMetadata } from './metadata.js';
7
+ import type { VoiceTurnMetrics } from './turn-metrics.js';
8
+ export interface VoiceCallObservabilityOptions {
9
+ /** The Mastra instance whose observability config receives the spans. */
10
+ mastra: Mastra;
11
+ /** Resolved Mastra agent id/key answering the call (for span attribution). */
12
+ agentId: string;
13
+ /** LiveKit room name for this session. */
14
+ roomName: string;
15
+ /** Dispatch metadata for the session. */
16
+ metadata: LiveKitSessionMetadata;
17
+ /** Request context forwarded to span sampling. */
18
+ requestContext?: RequestContext;
19
+ }
20
+ export interface VoiceCallObservability {
21
+ /** The root `voice call` span. Each turn's agent run and every pipeline metric nests under it. */
22
+ readonly span: Span<SpanType.GENERIC>;
23
+ /** Thread into the bridge's `streamOptions` so each turn's agent run nests under the call. */
24
+ readonly tracingContext: TracingContext;
25
+ /** Subscribe to the session's `metrics_collected` events. Call once, before `session.start()`. */
26
+ attach(session: voice.AgentSession): void;
27
+ /** Record a generation or playback measurement with its correlation IDs. */
28
+ recordTurn(metric: VoiceTurnMetrics): void;
29
+ /** Close the call span with the usage roll-up. Idempotent; safe to call from a shutdown hook. */
30
+ finalize(options?: {
31
+ error?: unknown;
32
+ }): void;
33
+ }
34
+ /**
35
+ * Opens a `voice call` trace for one LiveKit session and bridges LiveKit's voice-pipeline
36
+ * metrics into Mastra observability.
37
+ *
38
+ * The returned root span groups everything about the call: each conversation turn's Mastra
39
+ * agent run (nested via {@link VoiceCallObservability.tracingContext}) plus an event span for
40
+ * every STT, TTS, end-of-utterance, VAD, and LLM-latency metric LiveKit emits. Metrics are
41
+ * point-in-time, so they're recorded as event spans (no duration) with the value in the name.
42
+ * The root closes on the session `close` event with a per-model usage roll-up (token, character,
43
+ * and audio totals for the whole call) from a `ModelUsageCollector`.
44
+ *
45
+ * Returns `undefined` when the Mastra instance has no observability configured, so callers
46
+ * can treat instrumentation as a no-op without branching on config.
47
+ */
48
+ export declare function startVoiceCallObservability(options: VoiceCallObservabilityOptions): VoiceCallObservability | undefined;
49
+ //# sourceMappingURL=observability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../src/observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,KAAK,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAmB,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,MAAM,WAAW,6BAA6B;IAC5C,yEAAyE;IACzE,MAAM,EAAE,MAAM,CAAC;IACf,8EAA8E;IAC9E,OAAO,EAAE,MAAM,CAAC;IAChB,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,yCAAyC;IACzC,QAAQ,EAAE,sBAAsB,CAAC;IACjC,kDAAkD;IAClD,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAED,MAAM,WAAW,sBAAsB;IACrC,kGAAkG;IAClG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACtC,8FAA8F;IAC9F,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC,kGAAkG;IAClG,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,GAAG,IAAI,CAAC;IAC1C,4EAA4E;IAC5E,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC3C,iGAAiG;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