@mastra/livekit 0.0.0-buttoned-spandex-20260824090603

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +433 -0
  2. package/LICENSE.md +30 -0
  3. package/README.md +448 -0
  4. package/dist/bridge.d.ts +229 -0
  5. package/dist/bridge.d.ts.map +1 -0
  6. package/dist/consent.d.ts +55 -0
  7. package/dist/consent.d.ts.map +1 -0
  8. package/dist/constants.d.ts +3 -0
  9. package/dist/constants.d.ts.map +1 -0
  10. package/dist/dispatch.d.ts +20 -0
  11. package/dist/dispatch.d.ts.map +1 -0
  12. package/dist/end-call.d.ts +50 -0
  13. package/dist/end-call.d.ts.map +1 -0
  14. package/dist/index.cjs +189 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.ts +14 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +182 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/llm-plugin.d.ts +112 -0
  21. package/dist/llm-plugin.d.ts.map +1 -0
  22. package/dist/messages.d.ts +50 -0
  23. package/dist/messages.d.ts.map +1 -0
  24. package/dist/metadata.d.ts +17 -0
  25. package/dist/metadata.d.ts.map +1 -0
  26. package/dist/observability.d.ts +46 -0
  27. package/dist/observability.d.ts.map +1 -0
  28. package/dist/plugin-entry.cjs +209 -0
  29. package/dist/plugin-entry.cjs.map +1 -0
  30. package/dist/plugin-entry.d.ts +6 -0
  31. package/dist/plugin-entry.d.ts.map +1 -0
  32. package/dist/plugin-entry.js +207 -0
  33. package/dist/plugin-entry.js.map +1 -0
  34. package/dist/remote-C9K3UzKv.js +629 -0
  35. package/dist/remote-C9K3UzKv.js.map +1 -0
  36. package/dist/remote-D0Y5P6e4.cjs +658 -0
  37. package/dist/remote-D0Y5P6e4.cjs.map +1 -0
  38. package/dist/remote.d.ts +68 -0
  39. package/dist/remote.d.ts.map +1 -0
  40. package/dist/routes.d.ts +52 -0
  41. package/dist/routes.d.ts.map +1 -0
  42. package/dist/run.d.ts +32 -0
  43. package/dist/run.d.ts.map +1 -0
  44. package/dist/voice-thread.d.ts +23 -0
  45. package/dist/voice-thread.d.ts.map +1 -0
  46. package/dist/worker-entry.cjs +686 -0
  47. package/dist/worker-entry.cjs.map +1 -0
  48. package/dist/worker-entry.d.ts +10 -0
  49. package/dist/worker-entry.d.ts.map +1 -0
  50. package/dist/worker-entry.js +675 -0
  51. package/dist/worker-entry.js.map +1 -0
  52. package/dist/worker-setup.d.ts +5 -0
  53. package/dist/worker-setup.d.ts.map +1 -0
  54. package/dist/worker.d.ts +461 -0
  55. package/dist/worker.d.ts.map +1 -0
  56. package/dist/workflow-generator-B67QrY8L.cjs +209 -0
  57. package/dist/workflow-generator-B67QrY8L.cjs.map +1 -0
  58. package/dist/workflow-generator-BtfClQcM.js +180 -0
  59. package/dist/workflow-generator-BtfClQcM.js.map +1 -0
  60. package/dist/workflow-generator.d.ts +92 -0
  61. package/dist/workflow-generator.d.ts.map +1 -0
  62. package/package.json +107 -0
package/dist/index.js ADDED
@@ -0,0 +1,182 @@
1
+ import { a as DEFAULT_LIVEKIT_AGENT_NAME, i as serializeSessionMetadata, n as pipeAgentReplyToWriter } from "./workflow-generator-BtfClQcM.js";
2
+ import { randomUUID } from "crypto";
3
+ import { RoomAgentDispatch, RoomConfiguration } from "@livekit/protocol";
4
+ import { AccessToken, AgentDispatchClient } from "livekit-server-sdk";
5
+ import { createTool } from "@mastra/core/tools";
6
+ import { z } from "zod";
7
+ //#region src/routes.ts
8
+ function stringField(body, key) {
9
+ const value = body[key];
10
+ return typeof value === "string" && value.length > 0 ? value : void 0;
11
+ }
12
+ /**
13
+ * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra
14
+ * voice agent dispatched into the room. Frontends call it to join a voice session:
15
+ *
16
+ * ```ts
17
+ * export const mastra = new Mastra({
18
+ * agents: { support },
19
+ * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },
20
+ * });
21
+ * ```
22
+ */
23
+ function liveKitConnectionRoute(options = {}) {
24
+ const handler = async (c) => {
25
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
26
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
27
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
28
+ 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);
29
+ const body = await c.req.json().then((parsed) => parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}).catch(() => ({}));
30
+ const args = {
31
+ body,
32
+ context: c
33
+ };
34
+ const metadata = options.metadata ? await options.metadata(args) : {
35
+ agentId: stringField(body, "agentId"),
36
+ threadId: stringField(body, "threadId"),
37
+ resourceId: stringField(body, "resourceId")
38
+ };
39
+ const roomName = typeof options.roomName === "function" ? options.roomName(args) : options.roomName ?? `mastra-voice-${randomUUID().slice(0, 8)}`;
40
+ const identity = typeof options.participantIdentity === "function" ? options.participantIdentity(args) : options.participantIdentity ?? metadata.resourceId ?? `user-${randomUUID().slice(0, 8)}`;
41
+ metadata.threadId ??= roomName;
42
+ const token = new AccessToken(apiKey, apiSecret, {
43
+ identity,
44
+ ttl: options.ttl ?? "15m"
45
+ });
46
+ token.addGrant({
47
+ room: roomName,
48
+ roomJoin: true,
49
+ canPublish: true,
50
+ canSubscribe: true,
51
+ canPublishData: true,
52
+ canUpdateOwnMetadata: true
53
+ });
54
+ token.roomConfig = new RoomConfiguration({ agents: [new RoomAgentDispatch({
55
+ agentName: options.agentName ?? "mastra-voice",
56
+ metadata: serializeSessionMetadata(metadata)
57
+ })] });
58
+ const details = {
59
+ serverUrl,
60
+ roomName,
61
+ participantName: identity,
62
+ participantToken: await token.toJwt()
63
+ };
64
+ return c.json(details);
65
+ };
66
+ return {
67
+ path: options.path ?? "/voice/livekit/connection-details",
68
+ method: "POST",
69
+ requiresAuth: options.requiresAuth,
70
+ handler
71
+ };
72
+ }
73
+ //#endregion
74
+ //#region src/dispatch.ts
75
+ function toHttpUrl(url) {
76
+ return url.replace(/^ws/, "http");
77
+ }
78
+ /**
79
+ * Programmatically dispatches a Mastra voice agent into a LiveKit room — for
80
+ * server-initiated sessions such as outbound calls or joining an existing room.
81
+ */
82
+ async function dispatchVoiceSession(options) {
83
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
84
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
85
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
86
+ if (!serverUrl) throw new Error("@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.");
87
+ if (!apiKey || !apiSecret) throw new Error("@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.");
88
+ return new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret).createDispatch(options.roomName, options.agentName ?? "mastra-voice", { metadata: serializeSessionMetadata(options.metadata ?? {}) });
89
+ }
90
+ //#endregion
91
+ //#region src/consent.ts
92
+ 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.";
93
+ /**
94
+ * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to
95
+ * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add
96
+ * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /
97
+ * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime
98
+ * grants live only where `onGrant` put them: enforce consent by reading them back from your own
99
+ * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared
100
+ * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the
101
+ * policy, never the grants).
102
+ *
103
+ * ```ts
104
+ * // agent tools
105
+ * recordConsent: createConsentTool({
106
+ * items: ['summaryStorage'],
107
+ * onGrant: async ({ item, granted, resourceId }) => {
108
+ * if (resourceId) await db.saveConsent(resourceId, item, granted);
109
+ * },
110
+ * }),
111
+ * ```
112
+ */
113
+ function createConsentTool(options) {
114
+ const items = options.items;
115
+ const itemSchema = items && items.length > 0 ? z.enum([...items]) : z.string();
116
+ return createTool({
117
+ id: options.id ?? "recordConsent",
118
+ description: options.description ?? DEFAULT_DESCRIPTION$1,
119
+ inputSchema: z.object({
120
+ item: itemSchema.describe("The consent item the caller is answering for (matches the deployment's required consents)."),
121
+ granted: z.boolean().describe("True if the caller agreed, false if they declined.")
122
+ }),
123
+ execute: async ({ item, granted }, { agent }) => {
124
+ await options.onGrant({
125
+ item,
126
+ granted,
127
+ resourceId: agent?.resourceId,
128
+ threadId: agent?.threadId
129
+ });
130
+ return {
131
+ recorded: true,
132
+ item,
133
+ granted
134
+ };
135
+ }
136
+ });
137
+ }
138
+ //#endregion
139
+ //#region src/end-call.ts
140
+ 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.";
141
+ /**
142
+ * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the
143
+ * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional
144
+ * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the
145
+ * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the
146
+ * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).
147
+ * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on
148
+ * the agent and workflow reply paths alike.
149
+ *
150
+ * ```ts
151
+ * // agent tools
152
+ * endCall: createEndCallTool({
153
+ * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),
154
+ * }),
155
+ * // worker
156
+ * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });
157
+ * ```
158
+ */
159
+ function createEndCallTool(options = {}) {
160
+ return createTool({
161
+ id: options.id ?? "endCall",
162
+ description: options.description ?? DEFAULT_DESCRIPTION,
163
+ inputSchema: z.object({ reason: z.string().nullish().describe("Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".") }),
164
+ outputSchema: z.object({ ended: z.boolean() }),
165
+ execute: async ({ reason }, { agent }) => {
166
+ try {
167
+ await options.onEndCall?.({
168
+ reason: reason ?? void 0,
169
+ resourceId: agent?.resourceId,
170
+ threadId: agent?.threadId
171
+ });
172
+ } catch (error) {
173
+ console.warn("@mastra/livekit: onEndCall hook threw", error);
174
+ }
175
+ return { ended: true };
176
+ }
177
+ });
178
+ }
179
+ //#endregion
180
+ export { DEFAULT_LIVEKIT_AGENT_NAME, createConsentTool, createEndCallTool, dispatchVoiceSession, liveKitConnectionRoute, pipeAgentReplyToWriter, serializeSessionMetadata };
181
+
182
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["DEFAULT_DESCRIPTION"],"sources":["../src/routes.ts","../src/dispatch.ts","../src/consent.ts","../src/end-call.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { 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 { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\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 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\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-${randomUUID().slice(0, 8)}`);\n const identity =\n typeof options.participantIdentity === 'function'\n ? options.participantIdentity(args)\n : (options.participantIdentity ?? metadata.resourceId ?? `user-${randomUUID().slice(0, 8)}`);\n // One memory thread per room unless the caller pins a thread explicitly.\n metadata.threadId ??= roomName;\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 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 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 path: options.path ?? '/voice/livekit/connection-details',\n method: 'POST',\n requiresAuth: options.requiresAuth,\n handler,\n } as ApiRoute;\n}\n","import { AgentDispatchClient } from 'livekit-server-sdk';\nimport { DEFAULT_LIVEKIT_AGENT_NAME } from './constants';\nimport { serializeSessionMetadata } from './metadata';\nimport type { LiveKitSessionMetadata } from './metadata';\n\nexport interface DispatchVoiceSessionOptions {\n /** Room to dispatch the agent into (created on demand). */\n roomName: string;\n /** Must match the worker's `agentName`. Defaults to `'mastra-voice'`. */\n agentName?: string;\n metadata?: LiveKitSessionMetadata;\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 client = new AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret);\n return client.createDispatch(options.roomName, options.agentName ?? DEFAULT_LIVEKIT_AGENT_NAME, {\n metadata: serializeSessionMetadata(options.metadata ?? {}),\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":";;;;;;;AAgDA,SAAS,YAAY,MAA+B,KAAiC;CACnF,MAAM,QAAQ,KAAK;CACnB,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE;;;;;;;;;;;;AAaA,SAAgB,uBAAuB,UAAyC,CAAC,GAAa;CAC5F,MAAM,UAAU,OAAO,MAAyB;EAC9C,MAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;EACnD,M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M;GAAQ;EAClD;CACF,CAAC;AACH;;;AC/CA,MAAM,sBACJ;;;;;;;;;;;;;;;;;;;AAyBF,SAAgB,kBAAkB,UAA8B,CAAC,GAAG;CAClE,OAAO,WAAW;EAChB,IAAI,QAAQ,MAAM;EAClB,aAAa,QAAQ,eAAe;EACpC,aAAa,EAAE,OAAO,EACpB,QAAQ,EACL,OAAO,CAAC,CACR,QAAQ,CAAC,CACT,SAAS,qFAAiF,EAC/F,CAAC;EACD,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,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,112 @@
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
+ export type { RemoteMastraAgentOptions } from './remote.js';
8
+ /**
9
+ * Options for {@link MastraLLM}. Provide **exactly one** reply source — `remote` (the headline: a
10
+ * Mastra app on a remote server), `agent` (an in-process Mastra agent), or `generate` (a custom
11
+ * {@link VoiceReplyGenerator}). The `toolFeedback` / `onToolCall` / `onTurnComplete` hooks apply to
12
+ * the `remote` and `agent` sources; a `generate` source owns its own hooks.
13
+ */
14
+ export interface MastraLLMOptions {
15
+ /** Remote Mastra server. Provide exactly one of `remote`, `agent`, `generate`. */
16
+ remote?: RemoteMastraAgentOptions;
17
+ /** In-process Mastra agent (reuses `createAgentReplyGenerator`). */
18
+ agent?: MastraAgent;
19
+ /** Custom reply source (escape hatch; owns its own tool-feedback / turn-complete behavior). */
20
+ generate?: VoiceReplyGenerator;
21
+ /**
22
+ * Conversation persistence, resolved by the customer per call (from SIP/caller identity). When set,
23
+ * only messages new since the agent last spoke are sent each turn and Mastra Memory supplies
24
+ * history. When omitted/false, the full LiveKit chat context is sent every turn.
25
+ *
26
+ * NOTE: incompatible with the session's `preemptiveGeneration` option — a speculative turn that
27
+ * completes before being discarded pollutes the thread. Leave preemptive generation off when
28
+ * using `memory`.
29
+ *
30
+ * The plugin cannot detect the combination at runtime, so this stays a documented constraint
31
+ * rather than a warning: the LLM interface never receives the session (so the option can't be
32
+ * read), a preemptive `chat()` is shape-identical to a real turn (LiveKit drives the same
33
+ * `generateReply` with a draft transcript and no marker), and the observable signature — a
34
+ * cancelled stream followed by a `chat()` whose trailing user message changed — is exactly what
35
+ * an ordinary barge-in correction looks like, so a heuristic would warn on every barge-in.
36
+ */
37
+ memory?: MastraVoiceAgentMemory | false;
38
+ /** Request context forwarded to generation (tenant, dialed number, ...). */
39
+ requestContext?: RequestContext | Record<string, unknown>;
40
+ /** Speak a short filler while a (server-side) tool runs. Applies to the `remote`/`agent` sources. */
41
+ toolFeedback?: (toolCall: VoiceToolCall) => string | undefined | void;
42
+ /** Notified as each tool-call chunk arrives, mid-stream. Applies to the `remote`/`agent` sources. */
43
+ onToolCall?: (toolCall: VoiceToolCall) => void;
44
+ /** Fired off the audio path after each reply finishes. Applies to the `remote`/`agent` sources. */
45
+ onTurnComplete?: VoiceTurnCompleteHook;
46
+ }
47
+ /**
48
+ * A standard LiveKit LLM plugin (`llm.LLM`) backed by a Mastra agent. Drop it into the `llm` slot of a
49
+ * customer-owned `voice.AgentSession` and the Mastra app (agent loop, tools, memory, observability)
50
+ * runs wherever it's deployed — most importantly on a **remote** Mastra server reached over HTTP.
51
+ *
52
+ * Tools are defined and executed **server-side** on the Mastra agent; LiveKit-side `toolCtx` is
53
+ * ignored (with a one-time warning). Tool activity surfaces via `toolFeedback` (spoken) and
54
+ * `onToolCall` / `onTurnComplete` (programmatic). `voice.Agent` instructions do **not** reach the
55
+ * Mastra agent — put instructions on the Mastra agent instead.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * const session = new voice.AgentSession({
60
+ * stt: 'deepgram/nova-3',
61
+ * tts: 'cartesia/sonic-3',
62
+ * llm: new MastraLLM({
63
+ * remote: { baseUrl: process.env.MASTRA_URL!, agentId: 'callCenter' },
64
+ * memory: { thread: callId, resource: callerId },
65
+ * }),
66
+ * });
67
+ * ```
68
+ */
69
+ export declare class MastraLLM extends llm.LLM {
70
+ #private;
71
+ constructor(options: MastraLLMOptions);
72
+ label(): string;
73
+ get model(): string;
74
+ get provider(): string;
75
+ /**
76
+ * Resolves the reply generator for a turn. Non-remote sources are built once; the remote transport
77
+ * is built per turn so its connect + first-token timeout can come from the session's
78
+ * `connOptions.timeoutMs`, with base-class retries owning retry (transport `retries: 0`).
79
+ */
80
+ private resolveGenerator;
81
+ chat({ chatCtx, toolCtx, connOptions, }: {
82
+ chatCtx: llm.ChatContext;
83
+ toolCtx?: llm.ToolContext;
84
+ connOptions?: APIConnectOptions;
85
+ parallelToolCalls?: boolean;
86
+ toolChoice?: llm.ToolChoice;
87
+ extraKwargs?: Record<string, unknown>;
88
+ }): llm.LLMStream;
89
+ /** No-op in v1: nothing in the LiveKit session/worker ever calls `prewarm()` automatically. */
90
+ prewarm(): void;
91
+ }
92
+ interface MastraLLMStreamOptions {
93
+ chatCtx: llm.ChatContext;
94
+ toolCtx?: llm.ToolContext;
95
+ connOptions: APIConnectOptions;
96
+ generator: VoiceReplyGenerator;
97
+ memory: MastraVoiceAgentMemory | false;
98
+ requestContext?: RequestContext;
99
+ }
100
+ /**
101
+ * The `llm.LLMStream` `MastraLLM` returns per turn. `run()` extracts the turn's messages, drives
102
+ * the reply generator, and pushes assistant `ChatChunk`s into `this.queue` (NOT `this.output` — the
103
+ * base class drains queue → output and computes TTFT / duration / usage). Barge-in aborts via
104
+ * `this.abortController` and `run()` returns silently.
105
+ */
106
+ declare class MastraLLMStream extends llm.LLMStream {
107
+ #private;
108
+ constructor(mastraLLM: MastraLLM, options: MastraLLMStreamOptions);
109
+ protected run(): Promise<void>;
110
+ }
111
+ export { MastraLLMStream };
112
+ //# 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;AAEzD,YAAY,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AAEzD;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,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;;;;;;;;;;;;;;;OAeG;IACH,MAAM,CAAC,EAAE,sBAAsB,GAAG,KAAK,CAAC;IACxC,4EAA4E;IAC5E,cAAc,CAAC,EAAE,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE1D,qGAAqG;IACrG,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,aAAa,KAA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BAAsB;cAOjD,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CAgDrC;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,46 @@
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
+ export interface VoiceCallObservabilityOptions {
8
+ /** The Mastra instance whose observability config receives the spans. */
9
+ mastra: Mastra;
10
+ /** Resolved Mastra agent id/key answering the call (for span attribution). */
11
+ agentId: string;
12
+ /** LiveKit room name for this session. */
13
+ roomName: string;
14
+ /** Dispatch metadata for the session. */
15
+ metadata: LiveKitSessionMetadata;
16
+ /** Request context forwarded to span sampling. */
17
+ requestContext?: RequestContext;
18
+ }
19
+ export interface VoiceCallObservability {
20
+ /** The root `voice call` span. Each turn's agent run and every pipeline metric nests under it. */
21
+ readonly span: Span<SpanType.GENERIC>;
22
+ /** Thread into the bridge's `streamOptions` so each turn's agent run nests under the call. */
23
+ readonly tracingContext: TracingContext;
24
+ /** Subscribe to the session's `metrics_collected` events. Call once, before `session.start()`. */
25
+ attach(session: voice.AgentSession): void;
26
+ /** Close the call span with the usage roll-up. Idempotent; safe to call from a shutdown hook. */
27
+ finalize(options?: {
28
+ error?: unknown;
29
+ }): void;
30
+ }
31
+ /**
32
+ * Opens a `voice call` trace for one LiveKit session and bridges LiveKit's voice-pipeline
33
+ * metrics into Mastra observability.
34
+ *
35
+ * The returned root span groups everything about the call: each conversation turn's Mastra
36
+ * agent run (nested via {@link VoiceCallObservability.tracingContext}) plus an event span for
37
+ * every STT, TTS, end-of-utterance, VAD, and LLM-latency metric LiveKit emits. Metrics are
38
+ * point-in-time, so they're recorded as event spans (no duration) with the value in the name.
39
+ * The root closes on the session `close` event with a per-model usage roll-up (token, character,
40
+ * and audio totals for the whole call) from a `ModelUsageCollector`.
41
+ *
42
+ * Returns `undefined` when the Mastra instance has no observability configured, so callers
43
+ * can treat instrumentation as a no-op without branching on config.
44
+ */
45
+ export declare function startVoiceCallObservability(options: VoiceCallObservabilityOptions): VoiceCallObservability | undefined;
46
+ //# 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;AAEzD,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,iGAAiG;IACjG,QAAQ,CAAC,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;CAC/C;AAgGD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,6BAA6B,GACrC,sBAAsB,GAAG,SAAS,CAsDpC"}