@mastra/livekit 0.3.0 → 0.3.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,10 +1,12 @@
1
1
  Portions of this software are licensed as follows:
2
2
 
3
- - All content that resides under any directory named "ee/" within this
3
+ - All content that resides under any directory named `ee/` within this
4
4
  repository, including but not limited to:
5
- - `packages/core/src/auth/ee/`
6
- - `packages/server/src/server/auth/ee/`
7
- is licensed under the license defined in `ee/LICENSE`.
5
+ - `@mastra/core/auth/ee`
6
+ - `@mastra/core/agent-builder/ee`
7
+ - `@mastra/editor/ee`
8
+
9
+ is licensed under the license defined in [`ee/LICENSE`](https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE).
8
10
 
9
11
  - All third-party components incorporated into the Mastra Software are
10
12
  licensed under the original license provided by the owner of the
package/README.md CHANGED
@@ -443,6 +443,6 @@ See the example's own [`README.md`](https://github.com/mastra-ai/mastra/tree/mai
443
443
 
444
444
  ## Documentation
445
445
 
446
- - [Using LiveKit with Mastra](https://mastra.ai/docs/voice/livekit)
446
+ - [Realtime voice](https://mastra.ai/docs/voice/realtime-voice)
447
447
  - [`@mastra/livekit` reference](https://mastra.ai/reference/voice/livekit)
448
448
  - [LiveKit Agents docs](https://docs.livekit.io/agents/)
@@ -1 +1 @@
1
- {"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,KAAK,EAAE,KAAK,IAAI,WAAW,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAA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,CAAC,CAAC,IAAI,CAAC,CAAC;IACvC,GAAG,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;IACzC,GAAG,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;IACzC,GAAG,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;IACzC,YAAY,CAAC,EAAE,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,cAAc,CAAC,CAAC;CAC5D;AAiCD;;;;;;;GAOG;AACH,qBAAa,gBAAiB,SAAQ,KAAK,CAAC,KAAK;IAC/C,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC;IACnC,QAAQ,CAAC,MAAM,EAAE,sBAAsB,GAAG,KAAK,CAAC;IAChD,QAAQ,CAAC,cAAc,CAAC,EAAE,cAAc,CAAC;IACzC,QAAQ,CAAC,aAAa,CAAC,EAAE,mBAAmB,CAAC;IAC7C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAsB;IACrD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAqB;IAE/C,YAAY,OAAO,EAAE,uBAAuB,EAuC3C;IAEc,OAAO,CACpB,OAAO,EAAE,GAAG,CAAC,WAAW,EACxB,QAAQ,EAAE,GAAG,CAAC,WAAW,EACzB,cAAc,EAAE,KAAK,CAAC,aAAa,GAClC,OAAO,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,GAAG,MAAM,CAAC,GAAG,IAAI,CAAC,CA0BxD;CACF;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,uBAAuB,GAAG,gBAAgB,CAEzF"}
package/dist/index.cjs CHANGED
@@ -1,151 +1,189 @@
1
- 'use strict';
2
-
3
- var chunkMWTEZOBS_cjs = require('./chunk-MWTEZOBS.cjs');
4
- var crypto = require('crypto');
5
- var protocol = require('@livekit/protocol');
6
- var livekitServerSdk = require('livekit-server-sdk');
7
- var tools = require('@mastra/core/tools');
8
- var zod = require('zod');
9
-
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_workflow_generator = require("./workflow-generator-B67QrY8L.cjs");
3
+ let crypto = require("crypto");
4
+ let _livekit_protocol = require("@livekit/protocol");
5
+ let livekit_server_sdk = require("livekit-server-sdk");
6
+ let _mastra_core_tools = require("@mastra/core/tools");
7
+ let zod = require("zod");
8
+ //#region src/routes.ts
10
9
  function stringField(body, key) {
11
- const value = body[key];
12
- return typeof value === "string" && value.length > 0 ? value : void 0;
10
+ const value = body[key];
11
+ return typeof value === "string" && value.length > 0 ? value : void 0;
13
12
  }
13
+ /**
14
+ * An ApiRoute for `server.apiRoutes` that mints a LiveKit access token with the Mastra
15
+ * voice agent dispatched into the room. Frontends call it to join a voice session:
16
+ *
17
+ * ```ts
18
+ * export const mastra = new Mastra({
19
+ * agents: { support },
20
+ * server: { apiRoutes: [liveKitConnectionRoute({ agentName: 'mastra-voice' })] },
21
+ * });
22
+ * ```
23
+ */
14
24
  function liveKitConnectionRoute(options = {}) {
15
- const handler = async (c) => {
16
- const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
17
- const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
18
- const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
19
- if (!serverUrl || !apiKey || !apiSecret) {
20
- return c.json(
21
- {
22
- error: "LiveKit is not configured. Set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET (or pass serverUrl/apiKey/apiSecret to liveKitConnectionRoute)."
23
- },
24
- 500
25
- );
26
- }
27
- const body = await c.req.json().then(
28
- (parsed) => parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}
29
- ).catch(() => ({}));
30
- const args = { body, context: c };
31
- const metadata = options.metadata ? await options.metadata(args) : {
32
- agentId: stringField(body, "agentId"),
33
- threadId: stringField(body, "threadId"),
34
- resourceId: stringField(body, "resourceId")
35
- };
36
- const roomName = typeof options.roomName === "function" ? options.roomName(args) : options.roomName ?? `mastra-voice-${crypto.randomUUID().slice(0, 8)}`;
37
- const identity = typeof options.participantIdentity === "function" ? options.participantIdentity(args) : options.participantIdentity ?? metadata.resourceId ?? `user-${crypto.randomUUID().slice(0, 8)}`;
38
- metadata.threadId ??= roomName;
39
- const token = new livekitServerSdk.AccessToken(apiKey, apiSecret, { identity, ttl: options.ttl ?? "15m" });
40
- token.addGrant({
41
- room: roomName,
42
- roomJoin: true,
43
- canPublish: true,
44
- canSubscribe: true,
45
- canPublishData: true,
46
- canUpdateOwnMetadata: true
47
- });
48
- token.roomConfig = new protocol.RoomConfiguration({
49
- agents: [
50
- new protocol.RoomAgentDispatch({
51
- agentName: options.agentName ?? chunkMWTEZOBS_cjs.DEFAULT_LIVEKIT_AGENT_NAME,
52
- metadata: chunkMWTEZOBS_cjs.serializeSessionMetadata(metadata)
53
- })
54
- ]
55
- });
56
- const details = {
57
- serverUrl,
58
- roomName,
59
- participantName: identity,
60
- participantToken: await token.toJwt()
61
- };
62
- return c.json(details);
63
- };
64
- return {
65
- path: options.path ?? "/voice/livekit/connection-details",
66
- method: "POST",
67
- requiresAuth: options.requiresAuth,
68
- handler
69
- };
25
+ const handler = async (c) => {
26
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
27
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
28
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
29
+ 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);
30
+ const body = await c.req.json().then((parsed) => parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}).catch(() => ({}));
31
+ const args = {
32
+ body,
33
+ context: c
34
+ };
35
+ const metadata = options.metadata ? await options.metadata(args) : {
36
+ agentId: stringField(body, "agentId"),
37
+ threadId: stringField(body, "threadId"),
38
+ resourceId: stringField(body, "resourceId")
39
+ };
40
+ const roomName = typeof options.roomName === "function" ? options.roomName(args) : options.roomName ?? `mastra-voice-${(0, crypto.randomUUID)().slice(0, 8)}`;
41
+ const identity = typeof options.participantIdentity === "function" ? options.participantIdentity(args) : options.participantIdentity ?? metadata.resourceId ?? `user-${(0, crypto.randomUUID)().slice(0, 8)}`;
42
+ metadata.threadId ??= roomName;
43
+ const token = new livekit_server_sdk.AccessToken(apiKey, apiSecret, {
44
+ identity,
45
+ ttl: options.ttl ?? "15m"
46
+ });
47
+ token.addGrant({
48
+ room: roomName,
49
+ roomJoin: true,
50
+ canPublish: true,
51
+ canSubscribe: true,
52
+ canPublishData: true,
53
+ canUpdateOwnMetadata: true
54
+ });
55
+ token.roomConfig = new _livekit_protocol.RoomConfiguration({ agents: [new _livekit_protocol.RoomAgentDispatch({
56
+ agentName: options.agentName ?? "mastra-voice",
57
+ metadata: require_workflow_generator.serializeSessionMetadata(metadata)
58
+ })] });
59
+ const details = {
60
+ serverUrl,
61
+ roomName,
62
+ participantName: identity,
63
+ participantToken: await token.toJwt()
64
+ };
65
+ return c.json(details);
66
+ };
67
+ return {
68
+ path: options.path ?? "/voice/livekit/connection-details",
69
+ method: "POST",
70
+ requiresAuth: options.requiresAuth,
71
+ handler
72
+ };
70
73
  }
74
+ //#endregion
75
+ //#region src/dispatch.ts
71
76
  function toHttpUrl(url) {
72
- return url.replace(/^ws/, "http");
77
+ return url.replace(/^ws/, "http");
73
78
  }
79
+ /**
80
+ * Programmatically dispatches a Mastra voice agent into a LiveKit room — for
81
+ * server-initiated sessions such as outbound calls or joining an existing room.
82
+ */
74
83
  async function dispatchVoiceSession(options) {
75
- const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
76
- const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
77
- const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
78
- if (!serverUrl) {
79
- throw new Error("@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.");
80
- }
81
- if (!apiKey || !apiSecret) {
82
- throw new Error(
83
- "@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession."
84
- );
85
- }
86
- const client = new livekitServerSdk.AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret);
87
- return client.createDispatch(options.roomName, options.agentName ?? chunkMWTEZOBS_cjs.DEFAULT_LIVEKIT_AGENT_NAME, {
88
- metadata: chunkMWTEZOBS_cjs.serializeSessionMetadata(options.metadata ?? {})
89
- });
84
+ const serverUrl = options.serverUrl ?? process.env.LIVEKIT_URL;
85
+ const apiKey = options.apiKey ?? process.env.LIVEKIT_API_KEY;
86
+ const apiSecret = options.apiSecret ?? process.env.LIVEKIT_API_SECRET;
87
+ if (!serverUrl) throw new Error("@mastra/livekit: set LIVEKIT_URL or pass serverUrl to dispatchVoiceSession.");
88
+ if (!apiKey || !apiSecret) throw new Error("@mastra/livekit: set LIVEKIT_API_KEY and LIVEKIT_API_SECRET or pass apiKey/apiSecret to dispatchVoiceSession.");
89
+ return new livekit_server_sdk.AgentDispatchClient(toHttpUrl(serverUrl), apiKey, apiSecret).createDispatch(options.roomName, options.agentName ?? "mastra-voice", { metadata: require_workflow_generator.serializeSessionMetadata(options.metadata ?? {}) });
90
90
  }
91
- var DEFAULT_DESCRIPTION = "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.";
91
+ //#endregion
92
+ //#region src/consent.ts
93
+ 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.";
94
+ /**
95
+ * Builds a Mastra tool that captures the caller's consent decisions at runtime — the companion to
96
+ * the worker's `configuration.consentPolicy`, which only DECLARES which consents a call needs. Add
97
+ * it to the agent that answers the call; on each call the tool reads the caller's `resourceId` /
98
+ * `threadId` from its execution context and hands the decision to your `onGrant` store. The runtime
99
+ * grants live only where `onGrant` put them: enforce consent by reading them back from your own
100
+ * store — at `onCallEnd` or before any consent-gated action — cross-checking against the declared
101
+ * requirements in `VoiceCallEndArgs.configuration.consentPolicy` (the configuration carries the
102
+ * policy, never the grants).
103
+ *
104
+ * ```ts
105
+ * // agent tools
106
+ * recordConsent: createConsentTool({
107
+ * items: ['summaryStorage'],
108
+ * onGrant: async ({ item, granted, resourceId }) => {
109
+ * if (resourceId) await db.saveConsent(resourceId, item, granted);
110
+ * },
111
+ * }),
112
+ * ```
113
+ */
92
114
  function createConsentTool(options) {
93
- const items = options.items;
94
- const itemSchema = items && items.length > 0 ? zod.z.enum([...items]) : zod.z.string();
95
- return tools.createTool({
96
- id: options.id ?? "recordConsent",
97
- description: options.description ?? DEFAULT_DESCRIPTION,
98
- inputSchema: zod.z.object({
99
- item: itemSchema.describe(
100
- "The consent item the caller is answering for (matches the deployment's required consents)."
101
- ),
102
- granted: zod.z.boolean().describe("True if the caller agreed, false if they declined.")
103
- }),
104
- execute: async ({ item, granted }, { agent }) => {
105
- await options.onGrant({ item, granted, resourceId: agent?.resourceId, threadId: agent?.threadId });
106
- return { recorded: true, item, granted };
107
- }
108
- });
115
+ const items = options.items;
116
+ const itemSchema = items && items.length > 0 ? zod.z.enum([...items]) : zod.z.string();
117
+ return (0, _mastra_core_tools.createTool)({
118
+ id: options.id ?? "recordConsent",
119
+ description: options.description ?? DEFAULT_DESCRIPTION$1,
120
+ inputSchema: zod.z.object({
121
+ item: itemSchema.describe("The consent item the caller is answering for (matches the deployment's required consents)."),
122
+ granted: zod.z.boolean().describe("True if the caller agreed, false if they declined.")
123
+ }),
124
+ execute: async ({ item, granted }, { agent }) => {
125
+ await options.onGrant({
126
+ item,
127
+ granted,
128
+ resourceId: agent?.resourceId,
129
+ threadId: agent?.threadId
130
+ });
131
+ return {
132
+ recorded: true,
133
+ item,
134
+ granted
135
+ };
136
+ }
137
+ });
109
138
  }
110
- var DEFAULT_DESCRIPTION2 = "End the phone call. Call this only after you have said goodbye and there is nothing left to do \u2014 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 \u2014 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.";
139
+ //#endregion
140
+ //#region src/end-call.ts
141
+ 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.";
142
+ /**
143
+ * Builds a Mastra tool the agent calls to end the call itself (say goodbye → hang up). It is the
144
+ * agent-visible half of agent-initiated hang-up: the tool only SIGNALS intent (and runs optional
145
+ * bookkeeping) — it can't reach the LiveKit room from inside `agent.stream()`. The worker owns the
146
+ * hang-up: with `configuration.endCall` set, it watches each turn for this tool, waits for the
147
+ * agent's closing words to finish playing, then disconnects (running `onCallEnd` on the way out).
148
+ * Keeping the tool inside the single agent means it stays visible/editable in Studio and works on
149
+ * the agent and workflow reply paths alike.
150
+ *
151
+ * ```ts
152
+ * // agent tools
153
+ * endCall: createEndCallTool({
154
+ * onEndCall: ({ reason, resourceId }) => log.info('agent ended call', { reason, resourceId }),
155
+ * }),
156
+ * // worker
157
+ * createLiveKitWorker({ mastra, agent: 'support', configuration: { endCall: {} } });
158
+ * ```
159
+ */
111
160
  function createEndCallTool(options = {}) {
112
- return tools.createTool({
113
- id: options.id ?? "endCall",
114
- description: options.description ?? DEFAULT_DESCRIPTION2,
115
- inputSchema: zod.z.object({
116
- reason: zod.z.string().nullish().describe('Short reason the call is ending, e.g. "caller said goodbye" or "task complete".')
117
- }),
118
- outputSchema: zod.z.object({ ended: zod.z.boolean() }),
119
- execute: async ({ reason }, { agent }) => {
120
- try {
121
- await options.onEndCall?.({
122
- reason: reason ?? void 0,
123
- resourceId: agent?.resourceId,
124
- threadId: agent?.threadId
125
- });
126
- } catch (error) {
127
- console.warn("@mastra/livekit: onEndCall hook threw", error);
128
- }
129
- return { ended: true };
130
- }
131
- });
161
+ return (0, _mastra_core_tools.createTool)({
162
+ id: options.id ?? "endCall",
163
+ description: options.description ?? DEFAULT_DESCRIPTION,
164
+ inputSchema: zod.z.object({ reason: zod.z.string().nullish().describe("Short reason the call is ending, e.g. \"caller said goodbye\" or \"task complete\".") }),
165
+ outputSchema: zod.z.object({ ended: zod.z.boolean() }),
166
+ execute: async ({ reason }, { agent }) => {
167
+ try {
168
+ await options.onEndCall?.({
169
+ reason: reason ?? void 0,
170
+ resourceId: agent?.resourceId,
171
+ threadId: agent?.threadId
172
+ });
173
+ } catch (error) {
174
+ console.warn("@mastra/livekit: onEndCall hook threw", error);
175
+ }
176
+ return { ended: true };
177
+ }
178
+ });
132
179
  }
133
-
134
- Object.defineProperty(exports, "DEFAULT_LIVEKIT_AGENT_NAME", {
135
- enumerable: true,
136
- get: function () { return chunkMWTEZOBS_cjs.DEFAULT_LIVEKIT_AGENT_NAME; }
137
- });
138
- Object.defineProperty(exports, "pipeAgentReplyToWriter", {
139
- enumerable: true,
140
- get: function () { return chunkMWTEZOBS_cjs.pipeAgentReplyToWriter; }
141
- });
142
- Object.defineProperty(exports, "serializeSessionMetadata", {
143
- enumerable: true,
144
- get: function () { return chunkMWTEZOBS_cjs.serializeSessionMetadata; }
145
- });
180
+ //#endregion
181
+ exports.DEFAULT_LIVEKIT_AGENT_NAME = require_workflow_generator.DEFAULT_LIVEKIT_AGENT_NAME;
146
182
  exports.createConsentTool = createConsentTool;
147
183
  exports.createEndCallTool = createEndCallTool;
148
184
  exports.dispatchVoiceSession = dispatchVoiceSession;
149
185
  exports.liveKitConnectionRoute = liveKitConnectionRoute;
150
- //# sourceMappingURL=index.cjs.map
186
+ exports.pipeAgentReplyToWriter = require_workflow_generator.pipeAgentReplyToWriter;
187
+ exports.serializeSessionMetadata = require_workflow_generator.serializeSessionMetadata;
188
+
151
189
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/routes.ts","../src/dispatch.ts","../src/consent.ts","../src/end-call.ts"],"names":["randomUUID","AccessToken","RoomConfiguration","RoomAgentDispatch","DEFAULT_LIVEKIT_AGENT_NAME","serializeSessionMetadata","AgentDispatchClient","z","createTool","DEFAULT_DESCRIPTION"],"mappings":";;;;;;;;;AAgDA,SAAS,WAAA,CAAY,MAA+B,GAAA,EAAiC;AACnF,EAAA,MAAM,KAAA,GAAQ,KAAK,GAAG,CAAA;AACtB,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,MAAA,GAAS,IAAI,KAAA,GAAQ,MAAA;AACjE;AAaO,SAAS,sBAAA,CAAuB,OAAA,GAAyC,EAAC,EAAa;AAC5F,EAAA,MAAM,OAAA,GAAU,OAAO,CAAA,KAAyB;AAC9C,IAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,GAAA,CAAI,WAAA;AACnD,IAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,GAAA,CAAI,eAAA;AAC7C,IAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,GAAA,CAAI,kBAAA;AACnD,IAAA,IAAI,CAAC,SAAA,IAAa,CAAC,MAAA,IAAU,CAAC,SAAA,EAAW;AACvC,MAAA,OAAO,CAAA,CAAE,IAAA;AAAA,QACP;AAAA,UACE,KAAA,EACE;AAAA,SAEJ;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAEA,IAAA,MAAM,IAAA,GAAgC,MA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IAAA,EAAM,OAAA,EAAS,UAAA,EAAY,KAAA,EAAO,UAAA,EAAY,QAAA,EAAU,KAAA,EAAO,QAAA,EAAU,CAAA;AACjG,MAAA,OAAO,EAAE,QAAA,EAAU,IAAA,EAAe,IAAA,EAAM,OAAA,EAAQ;AAAA,IAClD;AAAA,GACD,CAAA;AACH;AC/CA,IAAME,oBAAAA,GACJ,sjBAAA;AAyBK,SAAS,iBAAA,CAAkB,OAAA,GAA8B,EAAC,EAAG;AAClE,EAAA,OAAOD,gBAAAA,CAAW;AAAA,IAChB,EAAA,EAAI,QAAQ,EAAA,IAAM,SAAA;AAAA,IAClB,WAAA,EAAa,QAAQ,WAAA,IAAeC,oBAAAA;AAAA,IACpC,WAAA,EAAaF,MAAE,MAAA,CAAO;AAAA,MACpB,QAAQA,KAAAA,CACL,MAAA,GACA,OAAA,EAAQ,CACR,SAAS,iFAAiF;AAAA,KAC9F,CAAA;AAAA,IACD,YAAA,EAAcA,MAAE,MAAA,CAAO,EAAE,OAAOA,KAAAA,CAAE,OAAA,IAAW,CAAA;AAAA,IAC7C,SAAS,OAAO,EAAE,QAAO,EAAG,EAAE,OAAM,KAAM;AACxC,MAAA,IAAI;AACF,QAAA,MAAM,QAAQ,SAAA,GAAY;AAAA,UACxB,QAAQ,MAAA,IAAU,MAAA;AAAA,UAClB,YAAY,KAAA,EAAO,UAAA;AAAA,UACnB,UAAU,KAAA,EAAO;AAAA,SAClB,CAAA;AAAA,MACH,SAAS,KAAA,EAAO;AAGd,QAAA,OAAA,CAAQ,IAAA,CAAK,yCAAyC,KAAK,CAAA;AAAA,MAC7D;AACA,MAAA,OAAO,EAAE,OAAO,IAAA,EAAc;AAAA,IAChC;AAAA,GACD,CAAA;AACH","file":"index.cjs","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"]}
1
+ {"version":3,"file":"index.cjs","names":["AccessToken","RoomConfiguration","RoomAgentDispatch","serializeSessionMetadata","AgentDispatchClient","serializeSessionMetadata","DEFAULT_DESCRIPTION","z","z"],"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,MAAM,SAAS,QAAQ,UAAU,QAAQ,IAAI;EAC7C,MAAM,YAAY,QAAQ,aAAa,QAAQ,IAAI;EACnD,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,WAC5B,OAAO,EAAE,KACP,EACE,OACE,sJAEJ,GACA,GACF;EAGF,MAAM,OAAgC,MAAM,EAAE,IAC3C,KAAK,CAAC,CACN,MAAM,WACL,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IAAK,SAAqC,CAAC,CAC1G,CAAC,CACA,aAAa,CAAC,EAAE;EACnB,MAAM,OAA8B;GAAE;GAAM,SAAS;EAAE;EAEvD,MAAM,WAAmC,QAAQ,WAC7C,MAAM,QAAQ,SAAS,IAAI,IAC3B;GACE,SAAS,YAAY,MAAM,SAAS;GACpC,UAAU,YAAY,MAAM,UAAU;GACtC,YAAY,YAAY,MAAM,YAAY;EAC5C;EAEJ,MAAM,WACJ,OAAO,QAAQ,aAAa,aACxB,QAAQ,SAAS,IAAI,IACpB,QAAQ,YAAY,iBAAA,GAAA,OAAA,WAAA,CAA2B,CAAC,CAAC,MAAM,GAAG,CAAC;EAClE,MAAM,WACJ,OAAO,QAAQ,wBAAwB,aACnC,QAAQ,oBAAoB,IAAI,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